mdns_responder_unittest.cc 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. // Copyright 2018 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. #include <map>
  5. #include <memory>
  6. #include <string>
  7. #include <utility>
  8. #include <vector>
  9. #include "services/network/mdns_responder.h"
  10. #include "base/bind.h"
  11. #include "base/callback_helpers.h"
  12. #include "base/check_op.h"
  13. #include "base/memory/scoped_refptr.h"
  14. #include "base/strings/string_number_conversions.h"
  15. #include "base/strings/string_piece.h"
  16. #include "base/test/metrics/histogram_tester.h"
  17. #include "base/test/scoped_feature_list.h"
  18. #include "base/test/task_environment.h"
  19. #include "mojo/public/cpp/bindings/connector.h"
  20. #include "mojo/public/cpp/bindings/remote.h"
  21. #include "net/base/ip_address.h"
  22. #include "net/base/net_errors.h"
  23. #include "net/dns/dns_query.h"
  24. #include "net/dns/dns_response.h"
  25. #include "net/dns/dns_util.h"
  26. #include "net/dns/mock_mdns_socket_factory.h"
  27. #include "net/dns/public/dns_protocol.h"
  28. #include "services/network/public/cpp/features.h"
  29. #include "services/network/public/mojom/mdns_responder.mojom.h"
  30. #include "testing/gmock/include/gmock/gmock.h"
  31. #include "testing/gtest/include/gtest/gtest.h"
  32. namespace network {
  33. namespace {
  34. using ::testing::_;
  35. using ::testing::AnyNumber;
  36. using ::testing::AtLeast;
  37. using ::testing::Invoke;
  38. using ::testing::NiceMock;
  39. using ::testing::Return;
  40. using ServiceError = MdnsResponderManager::ServiceError;
  41. const net::IPAddress kPublicAddrs[2] = {net::IPAddress(11, 11, 11, 11),
  42. net::IPAddress(22, 22, 22, 22)};
  43. const net::IPAddress kPublicAddrsIpv6[2] = {
  44. net::IPAddress(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
  45. net::IPAddress(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)};
  46. const base::TimeDelta kDefaultTtl = base::Seconds(120);
  47. const int kNumAnnouncementsPerInterface = 2;
  48. const int kNumMaxRetriesPerResponse = 2;
  49. // Keep in sync with the histogram name in ReportServiceError in
  50. // mdns_responder.cc
  51. const char kServiceErrorHistogram[] =
  52. "NetworkService.MdnsResponder.ServiceError";
  53. // Keep in sync with |kMdnsNameGeneratorServiceInstanceName| in
  54. // mdns_responder.cc.
  55. const char kMdnsNameGeneratorServiceInstanceName[] =
  56. "Generated-Names._mdns_name_generator._udp.local";
  57. std::string CreateMdnsQuery(uint16_t query_id,
  58. const std::string& dotted_name,
  59. uint16_t qtype = net::dns_protocol::kTypeA) {
  60. std::string qname;
  61. net::DNSDomainFromDot(dotted_name, &qname);
  62. net::DnsQuery query(query_id, qname, qtype);
  63. return std::string(query.io_buffer()->data(), query.io_buffer()->size());
  64. }
  65. // Creates an mDNS response as announcement, resolution for queries or goodbye.
  66. std::string CreateResolutionResponse(
  67. const base::TimeDelta& ttl,
  68. const std::map<std::string, net::IPAddress>& name_addr_map) {
  69. auto buf = network::mdns_helper::CreateResolutionResponse(ttl, name_addr_map);
  70. DCHECK(buf != nullptr);
  71. return std::string(buf->data(), buf->size());
  72. }
  73. std::string CreateNegativeResponse(
  74. const std::map<std::string, net::IPAddress>& name_addr_map) {
  75. auto buf = network::mdns_helper::CreateNegativeResponse(name_addr_map);
  76. DCHECK(buf != nullptr);
  77. return std::string(buf->data(), buf->size());
  78. }
  79. std::string CreateResponseToMdnsNameGeneratorServiceQuery(
  80. const base::TimeDelta& ttl,
  81. const std::set<std::string>& names) {
  82. auto buf =
  83. network::mdns_helper::CreateResponseToMdnsNameGeneratorServiceQuery(
  84. ttl, names);
  85. DCHECK(buf != nullptr);
  86. return std::string(buf->data(), buf->size());
  87. }
  88. std::string CreateResponseToMdnsNameGeneratorServiceQueryWithCacheFlush(
  89. const std::set<std::string>& names) {
  90. auto buf =
  91. network::mdns_helper::CreateResponseToMdnsNameGeneratorServiceQuery(
  92. kDefaultTtl, names);
  93. // Deserialize to set the cache-flush bit before serializing again.
  94. net::DnsResponse response(buf.get(), buf->size());
  95. bool rv = response.InitParseWithoutQuery(buf->size());
  96. DCHECK(rv);
  97. DCHECK_EQ(response.answer_count(), 1u);
  98. net::DnsResourceRecord txt_record;
  99. rv = response.Parser().ReadRecord(&txt_record);
  100. DCHECK(rv);
  101. DCHECK_EQ(net::dns_protocol::kTypeTXT, txt_record.type);
  102. txt_record.klass |= net::dns_protocol::kFlagCacheFlush;
  103. // Parsed record does not own the RDATA. Copy the owned RDATA before
  104. // constructing a new response.
  105. const std::string owned_rdata(txt_record.rdata);
  106. txt_record.SetOwnedRdata(owned_rdata);
  107. std::vector<net::DnsResourceRecord> answers(1, txt_record);
  108. net::DnsResponse response_cache_flush(0 /* id */, true /* is_authoritative */,
  109. answers, {} /* authority_records */,
  110. {} /* additional_records */,
  111. absl::nullopt /* query */);
  112. DCHECK(response_cache_flush.io_buffer() != nullptr);
  113. buf = base::MakeRefCounted<net::IOBufferWithSize>(
  114. response_cache_flush.io_buffer_size());
  115. memcpy(buf->data(), response_cache_flush.io_buffer()->data(),
  116. response_cache_flush.io_buffer_size());
  117. return std::string(buf->data(), buf->size());
  118. }
  119. // A mock mDNS socket factory to create sockets that can fail sending or
  120. // receiving packets.
  121. class MockFailingMdnsSocketFactory : public net::MDnsSocketFactory {
  122. public:
  123. MockFailingMdnsSocketFactory(
  124. scoped_refptr<base::SingleThreadTaskRunner> task_runner)
  125. : task_runner_(std::move(task_runner)) {}
  126. ~MockFailingMdnsSocketFactory() override = default;
  127. MOCK_METHOD1(CreateSockets,
  128. void(std::vector<std::unique_ptr<net::DatagramServerSocket>>*));
  129. MOCK_METHOD1(OnSendTo, void(const std::string&));
  130. // Emulates the asynchronous contract of invoking |callback| in the SendTo
  131. // primitive but failed sending;
  132. int FailToSend(const std::string& packet,
  133. const std::string& address,
  134. net::CompletionOnceCallback callback) {
  135. OnSendTo(packet);
  136. task_runner_->PostTask(FROM_HERE, base::BindOnce(std::move(callback), -1));
  137. return -1;
  138. }
  139. // Emulates IO blocking in sending packets if |BlockSend()| is called, in
  140. // which case the completion callback is not invoked until |ResumeSend()| is
  141. // called.
  142. int MaybeBlockSend(const std::string& packet,
  143. const std::string& address,
  144. net::CompletionOnceCallback callback) {
  145. OnSendTo(packet);
  146. if (block_send_) {
  147. blocked_packet_size_ = packet.size();
  148. blocked_send_callback_ = std::move(callback);
  149. } else {
  150. task_runner_->PostTask(
  151. FROM_HERE, base::BindOnce(std::move(callback), packet.size()));
  152. }
  153. return -1;
  154. }
  155. void BlockSend() {
  156. DCHECK(!block_send_);
  157. block_send_ = true;
  158. }
  159. void ResumeSend() {
  160. DCHECK(block_send_);
  161. block_send_ = false;
  162. std::move(blocked_send_callback_).Run(blocked_packet_size_);
  163. }
  164. // Emulates the asynchronous contract of invoking |callback| in the RecvFrom
  165. // primitive but failed receiving;
  166. int FailToRecv(net::IOBuffer* buffer,
  167. int size,
  168. net::IPEndPoint* address,
  169. net::CompletionOnceCallback callback) {
  170. task_runner_->PostTask(
  171. FROM_HERE, base::BindOnce(std::move(callback), net::ERR_FAILED));
  172. return net::ERR_IO_PENDING;
  173. }
  174. private:
  175. bool block_send_ = false;
  176. size_t blocked_packet_size_ = 0;
  177. net::CompletionOnceCallback blocked_send_callback_;
  178. scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  179. };
  180. } // namespace
  181. // Tests of the response creation helpers. For positive responses, we have the
  182. // address records in the Answer section and, if TTL is nonzero, the
  183. // corresponding NSEC records in the Additional section. For negative responses,
  184. // the NSEC records are placed in the Answer section with the address records in
  185. // the Answer section.
  186. TEST(CreateMdnsResponseTest, SingleARecordAnswer) {
  187. const uint8_t response_data[]{
  188. 0x00, 0x00, // mDNS response ID mus be zero.
  189. 0x84, 0x00, // flags, response with authoritative answer
  190. 0x00, 0x00, // number of questions
  191. 0x00, 0x01, // number of answer rr
  192. 0x00, 0x00, // number of name server rr
  193. 0x00, 0x01, // number of additional rr
  194. 0x03, 'w', 'w', 'w', 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'c',
  195. 'o', 'm',
  196. 0x00, // null label
  197. 0x00, 0x01, // type A Record
  198. 0x80, 0x01, // class IN, cache-flush bit set
  199. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  200. 0x00, 0x04, // rdlength, 32 bits
  201. 0xc0, 0xa8, 0x00, 0x01, // 192.168.0.1
  202. // Additional section
  203. 0x03, 'w', 'w', 'w', 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'c',
  204. 'o', 'm',
  205. 0x00, // null label
  206. 0x00, 0x2f, // type NSEC Record
  207. 0x80, 0x01, // class IN, cache-flush bit set
  208. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  209. 0x00, 0x05, // rdlength, 5 bytes
  210. 0xc0, 0x2b, // pointer to the previous "www.example.com"
  211. 0x00, 0x01, 0x40, // type bit map of type A: window block 0, bitmap
  212. // length 1, bitmap with bit 1 set
  213. };
  214. std::string expected_response(reinterpret_cast<const char*>(response_data),
  215. sizeof(response_data));
  216. std::string actual_response = CreateResolutionResponse(
  217. kDefaultTtl,
  218. {{"www.example.com", net::IPAddress(0xc0, 0xa8, 0x00, 0x01)}});
  219. EXPECT_EQ(expected_response, actual_response);
  220. }
  221. TEST(CreateMdnsResponseTest, SingleARecordGoodbye) {
  222. const uint8_t response_data[]{
  223. 0x00, 0x00, // mDNS response ID mus be zero.
  224. 0x84, 0x00, // flags, response with authoritative answer
  225. 0x00, 0x00, // number of questions
  226. 0x00, 0x01, // number of answer rr
  227. 0x00, 0x00, // number of name server rr
  228. 0x00, 0x00, // number of additional rr
  229. 0x03, 'w', 'w', 'w', 0x07, 'e', 'x', 'a',
  230. 'm', 'p', 'l', 'e', 0x03, 'c', 'o', 'm',
  231. 0x00, // null label
  232. 0x00, 0x01, // type A Record
  233. 0x80, 0x01, // class IN, cache-flush bit set
  234. 0x00, 0x00, 0x00, 0x00, // zero TTL
  235. 0x00, 0x04, // rdlength, 32 bits
  236. 0xc0, 0xa8, 0x00, 0x01, // 192.168.0.1
  237. };
  238. std::string expected_response(reinterpret_cast<const char*>(response_data),
  239. sizeof(response_data));
  240. std::string actual_response = CreateResolutionResponse(
  241. base::TimeDelta(),
  242. {{"www.example.com", net::IPAddress(0xc0, 0xa8, 0x00, 0x01)}});
  243. EXPECT_EQ(expected_response, actual_response);
  244. }
  245. TEST(CreateMdnsResponseTest, SingleQuadARecordAnswer) {
  246. const uint8_t response_data[] = {
  247. 0x00, 0x00, // mDNS response ID mus be zero.
  248. 0x84, 0x00, // flags, response with authoritative answer
  249. 0x00, 0x00, // number of questions
  250. 0x00, 0x01, // number of answer rr
  251. 0x00, 0x00, // number of name server rr
  252. 0x00, 0x01, // number of additional rr
  253. 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'o', 'r', 'g',
  254. 0x00, // null label
  255. 0x00, 0x1c, // type AAAA Record
  256. 0x80, 0x01, // class IN, cache-flush bit set
  257. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  258. 0x00, 0x10, // rdlength, 128 bits
  259. 0xfd, 0x12, 0x34, 0x56, 0x78, 0x9a, 0x00, 0x01, // fd12:3456:789a:1::1
  260. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  261. // Additional section
  262. 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'o', 'r', 'g',
  263. 0x00, // null label
  264. 0x00, 0x2f, // type NSEC Record
  265. 0x80, 0x01, // class IN, cache-flush bit set
  266. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  267. 0x00, 0x08, // rdlength, 8 bytes
  268. 0xc0, 0x33, // pointer to the previous "example.org"
  269. 0x00, 0x04, 0x00, 0x00, 0x00,
  270. 0x08, // type bit map of type AAAA: window block 0, bitmap
  271. // length 4, bitmap with bit 28 set
  272. };
  273. std::string expected_response(reinterpret_cast<const char*>(response_data),
  274. sizeof(response_data));
  275. std::string actual_response = CreateResolutionResponse(
  276. kDefaultTtl,
  277. {{"example.org",
  278. net::IPAddress(0xfd, 0x12, 0x34, 0x56, 0x78, 0x9a, 0x00, 0x01, 0x00,
  279. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01)}});
  280. EXPECT_EQ(expected_response, actual_response);
  281. }
  282. TEST(CreateMdnsResponseTest, SingleNsecRecordAnswer) {
  283. const uint8_t response_data[] = {
  284. 0x00, 0x00, // mDNS response ID mus be zero.
  285. 0x84, 0x00, // flags, response with authoritative answer
  286. 0x00, 0x00, // number of questions
  287. 0x00, 0x01, // number of answer rr
  288. 0x00, 0x00, // number of name server rr
  289. 0x00, 0x01, // number of additional rr
  290. 0x03, 'w', 'w', 'w', 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'c',
  291. 'o', 'm',
  292. 0x00, // null label
  293. 0x00, 0x2f, // type NSEC Record
  294. 0x80, 0x01, // class IN, cache-flush bit set
  295. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  296. 0x00, 0x05, // rdlength, 5 bytes
  297. 0xc0, 0x0c, // pointer to the previous "www.example.com"
  298. 0x00, 0x01, 0x40, // type bit map of type A: window block 0, bitmap
  299. // length 1, bitmap with bit 1 set
  300. // Additional section
  301. 0x03, 'w', 'w', 'w', 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 0x03, 'c',
  302. 'o', 'm',
  303. 0x00, // null label
  304. 0x00, 0x01, // type A Record
  305. 0x80, 0x01, // class IN, cache-flush bit set
  306. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  307. 0x00, 0x04, // rdlength, 32 bits
  308. 0xc0, 0xa8, 0x00, 0x01, // 192.168.0.1
  309. };
  310. std::string expected_response(reinterpret_cast<const char*>(response_data),
  311. sizeof(response_data));
  312. std::string actual_response = CreateNegativeResponse(
  313. {{"www.example.com", net::IPAddress(0xc0, 0xa8, 0x00, 0x01)}});
  314. EXPECT_EQ(expected_response, actual_response);
  315. }
  316. TEST(CreateMdnsResponseTest,
  317. SingleTxtRecordAnswerToMdnsNameGeneratorServiceQuery) {
  318. const uint8_t response_data[] = {
  319. 0x00, 0x00, // mDNS response ID mus be zero.
  320. 0x84, 0x00, // flags, response with authoritative answer
  321. 0x00, 0x00, // number of questions
  322. 0x00, 0x01, // number of answer rr
  323. 0x00, 0x00, // number of name server rr
  324. 0x00, 0x00, // number of additional rr
  325. 0x0f, 'G', 'e', 'n', 'e', 'r', 'a', 't', 'e', 'd', '-', 'N',
  326. 'a', 'm', 'e', 's', 0x14, '_', 'm', 'd', 'n', 's', '_', 'n',
  327. 'a', 'm', 'e', '_', 'g', 'e', 'n', 'e', 'r', 'a', 't', 'o',
  328. 'r', 0x04, '_', 'u', 'd', 'p', 0x05, 'l', 'o', 'c', 'a', 'l',
  329. 0x00, // null label
  330. 0x00, 0x10, // type A Record
  331. 0x00, 0x01, // class IN, cache-flush bit NOT set
  332. 0x00, 0x00, 0x00, 0x78, // TTL, 120 seconds
  333. 0x00, 0x2e, // rdlength, 46 bytes for the following kv pairs
  334. 0x0d, 'n', 'a', 'm', 'e', '0', '=', '1', '.', 'l', 'o', 'c',
  335. 'a', 'l', 0x15, 'n', 'a', 'm', 'e', '1', '=', 'w', 'w', 'w',
  336. '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm',
  337. 0x09, 't', 'x', 't', 'v', 'e', 'r', 's', '=', '1'};
  338. std::string expected_response(reinterpret_cast<const char*>(response_data),
  339. sizeof(response_data));
  340. std::string actual_response = CreateResponseToMdnsNameGeneratorServiceQuery(
  341. kDefaultTtl, {"1.local", "www.example.com"});
  342. EXPECT_EQ(expected_response, actual_response);
  343. }
  344. class SimpleNameGenerator : public MdnsResponderManager::NameGenerator {
  345. public:
  346. std::string CreateName() override {
  347. return base::NumberToString(next_available_id_++);
  348. }
  349. private:
  350. uint32_t next_available_id_ = 0;
  351. };
  352. // Test suite for the mDNS responder utilities provided by the service.
  353. class MdnsResponderTest : public testing::Test {
  354. public:
  355. MdnsResponderTest()
  356. : failing_socket_factory_(task_environment_.GetMainThreadTaskRunner()) {
  357. feature_list_.InitAndEnableFeature(
  358. features::kMdnsResponderGeneratedNameListing);
  359. Reset();
  360. }
  361. ~MdnsResponderTest() {
  362. // Goodbye messages are scheduled when the responder service |host_manager_|
  363. // is destroyed and can be synchronously sent if the rate limiting permits.
  364. // See ResponseScheduler::DispatchPendingPackets().
  365. EXPECT_CALL(socket_factory_, OnSendTo(_)).Times(AnyNumber());
  366. EXPECT_CALL(failing_socket_factory_, OnSendTo(_)).Times(AnyNumber());
  367. }
  368. void Reset(bool use_failing_socket_factory = false) {
  369. client_[0].reset();
  370. client_[1].reset();
  371. if (use_failing_socket_factory)
  372. host_manager_ =
  373. std::make_unique<MdnsResponderManager>(&failing_socket_factory_);
  374. else
  375. host_manager_ = std::make_unique<MdnsResponderManager>(&socket_factory_);
  376. host_manager_->SetNameGeneratorForTesting(
  377. std::make_unique<SimpleNameGenerator>());
  378. host_manager_->SetTickClockForTesting(task_environment_.GetMockTickClock());
  379. CreateMdnsResponders();
  380. }
  381. void CreateMdnsResponders() {
  382. host_manager_->CreateMdnsResponder(client_[0].BindNewPipeAndPassReceiver());
  383. client_[0].set_disconnect_handler(base::BindOnce(
  384. &MdnsResponderTest::OnMojoConnectionError, base::Unretained(this), 0));
  385. host_manager_->CreateMdnsResponder(client_[1].BindNewPipeAndPassReceiver());
  386. client_[1].set_disconnect_handler(base::BindOnce(
  387. &MdnsResponderTest::OnMojoConnectionError, base::Unretained(this), 1));
  388. }
  389. // The following method is synchronous for testing by waiting on running the
  390. // task runner.
  391. std::string CreateNameForAddress(int client_id, const net::IPAddress& addr) {
  392. client_[client_id]->CreateNameForAddress(
  393. addr, base::BindOnce(&MdnsResponderTest::OnNameCreatedForAddress,
  394. base::Unretained(this), addr));
  395. RunUntilNoTasksRemain();
  396. return last_name_created_;
  397. }
  398. void RemoveNameForAddress(int client_id,
  399. const net::IPAddress& addr,
  400. bool expected_removed,
  401. bool expected_goodbye_sched) {
  402. client_[client_id]->RemoveNameForAddress(
  403. addr, base::BindOnce(&MdnsResponderTest::OnNameRemovedForAddress,
  404. base::Unretained(this), expected_removed,
  405. expected_goodbye_sched));
  406. }
  407. void RemoveNameForAddressAndExpectDone(int client_id,
  408. const net::IPAddress& addr) {
  409. RemoveNameForAddress(client_id, addr, true, true);
  410. }
  411. void CloseConnectionToResponderHost(int client_id) {
  412. client_[client_id].reset();
  413. }
  414. void OnMojoConnectionError(int client_id) { client_[client_id].reset(); }
  415. protected:
  416. void OnNameCreatedForAddress(const net::IPAddress& addr,
  417. const std::string& name,
  418. bool announcement_scheduled) {
  419. last_name_created_ = name;
  420. }
  421. void OnNameRemovedForAddress(bool expected_removed,
  422. bool expected_goodbye_scheduled,
  423. bool actual_removed,
  424. bool actual_goodbye_scheduled) {
  425. EXPECT_EQ(expected_removed, actual_removed);
  426. EXPECT_EQ(expected_goodbye_scheduled, actual_goodbye_scheduled);
  427. }
  428. void RunUntilNoTasksRemain() {
  429. task_environment_.FastForwardUntilNoTasksRemain();
  430. }
  431. void RunFor(base::TimeDelta duration) {
  432. task_environment_.FastForwardBy(duration);
  433. }
  434. base::test::ScopedFeatureList feature_list_;
  435. base::test::TaskEnvironment task_environment_{
  436. base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  437. // Overrides the current thread task runner, so we can simulate the passage
  438. // of time and avoid any actual sleeps.
  439. NiceMock<net::MockMDnsSocketFactory> socket_factory_;
  440. NiceMock<MockFailingMdnsSocketFactory> failing_socket_factory_;
  441. mojo::Remote<mojom::MdnsResponder> client_[2];
  442. std::unique_ptr<MdnsResponderManager> host_manager_;
  443. std::string last_name_created_;
  444. };
  445. // Test that a name-to-address map does not change for the same client after
  446. // it is created.
  447. TEST_F(MdnsResponderTest, PersistentNameAddressMapForTheSameClient) {
  448. const auto& addr1 = kPublicAddrs[0];
  449. const auto& addr2 = kPublicAddrs[1];
  450. const auto name1 = CreateNameForAddress(0, addr1);
  451. const auto name2 = CreateNameForAddress(0, addr2);
  452. EXPECT_NE(name1, name2);
  453. EXPECT_EQ(name1, CreateNameForAddress(0, addr1));
  454. }
  455. // Test that a name-to-address map can be removed when reaching zero refcount
  456. // and can be updated afterwards.
  457. TEST_F(MdnsResponderTest, NameAddressMapCanBeRemovedByOwningClient) {
  458. const auto& addr = kPublicAddrs[0];
  459. const auto prev_name = CreateNameForAddress(0, addr);
  460. RemoveNameForAddressAndExpectDone(0, addr);
  461. RunUntilNoTasksRemain();
  462. EXPECT_NE(prev_name, CreateNameForAddress(0, addr));
  463. }
  464. // Test that a name-to-address map is not removed with a positive refcount.
  465. TEST_F(MdnsResponderTest,
  466. NameAddressMapCanOnlyBeRemovedWhenReachingZeroRefcount) {
  467. const auto& addr = kPublicAddrs[0];
  468. const auto prev_name = CreateNameForAddress(0, addr);
  469. EXPECT_EQ(prev_name, CreateNameForAddress(0, addr));
  470. RemoveNameForAddress(0, addr, false /* expected removed */,
  471. false /* expected goodbye scheduled */);
  472. RunUntilNoTasksRemain();
  473. EXPECT_EQ(prev_name, CreateNameForAddress(0, addr));
  474. }
  475. // Test that different clients have isolated space of name-to-address maps.
  476. TEST_F(MdnsResponderTest, ClientsHaveIsolatedNameSpaceForAddresses) {
  477. const net::IPAddress& addr = kPublicAddrs[0];
  478. // The same address is mapped to different names for different clients.
  479. const auto name_client1 = CreateNameForAddress(0, addr);
  480. const auto name_client2 = CreateNameForAddress(1, addr);
  481. EXPECT_NE(name_client1, name_client2);
  482. // Removing a name-address association by client 2 does not change the
  483. // mapping for client 1.
  484. RemoveNameForAddressAndExpectDone(1, addr);
  485. EXPECT_EQ(name_client1, CreateNameForAddress(0, addr));
  486. }
  487. // Test that the mDNS responder sends an mDNS response to announce the
  488. // ownership of an address and its newly mapped name, but not for a previously
  489. // announced name-to-address map.
  490. TEST_F(MdnsResponderTest,
  491. CreatingNameForAddressOnlySendsAnnouncementForNewName) {
  492. const net::IPAddress& addr = kPublicAddrs[0];
  493. std::string expected_announcement =
  494. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr}});
  495. // MockMdnsSocketFactory binds sockets to two interfaces.
  496. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement))
  497. .Times(2 * kNumAnnouncementsPerInterface);
  498. EXPECT_EQ("0.local", CreateNameForAddress(0, addr)); // SimpleNameGenerator.
  499. // Sends no announcement for a name that is already mapped to an address.
  500. CreateNameForAddress(0, addr);
  501. RunUntilNoTasksRemain();
  502. }
  503. // Test that the announcements are sent for isolated spaces of name-to-address
  504. // maps owned by different clients.
  505. TEST_F(MdnsResponderTest,
  506. CreatingNamesForSameAddressButTwoClientsSendsDistinctAnnouncements) {
  507. const auto& addr = kPublicAddrs[0];
  508. std::string expected_announcement1 =
  509. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr}});
  510. std::string expected_announcement2 =
  511. CreateResolutionResponse(kDefaultTtl, {{"1.local", addr}});
  512. // MockMdnsSocketFactory binds sockets to two interfaces.
  513. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement1))
  514. .Times(2 * kNumAnnouncementsPerInterface);
  515. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement2))
  516. .Times(2 * kNumAnnouncementsPerInterface);
  517. CreateNameForAddress(0, addr);
  518. CreateNameForAddress(1, addr);
  519. RunUntilNoTasksRemain();
  520. }
  521. // Test that the goodbye message with zero TTL for a name is sent only
  522. // when we remove a name in an existing name-to-address map.
  523. TEST_F(MdnsResponderTest,
  524. RemovingNameForAddressOnlySendsResponseWithZeroTtlForExistingName) {
  525. const auto& addr = kPublicAddrs[0];
  526. std::string expected_announcement =
  527. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr}});
  528. std::string expected_goodbye =
  529. CreateResolutionResponse(base::TimeDelta(), {{"0.local", addr}});
  530. // MockMdnsSocketFactory binds sockets to two interfaces.
  531. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement))
  532. .Times(2 * kNumAnnouncementsPerInterface);
  533. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye)).Times(2);
  534. CreateNameForAddress(0, addr);
  535. RemoveNameForAddressAndExpectDone(0, addr);
  536. // Sends no goodbye message for a name that is already removed.
  537. RemoveNameForAddress(0, addr, false /* expected removed */,
  538. false /* expected goodbye scheduled */);
  539. RunUntilNoTasksRemain();
  540. }
  541. // Test that the responder can reply to an incoming query about a name it
  542. // knows.
  543. TEST_F(MdnsResponderTest, SendResponseToQueryForOwnedName) {
  544. const auto& addr = kPublicAddrs[0];
  545. const auto name = CreateNameForAddress(0, addr);
  546. std::string query1 = CreateMdnsQuery(0, name);
  547. std::string query2 = CreateMdnsQuery(0, "unknown_name");
  548. std::string expected_response =
  549. CreateResolutionResponse(kDefaultTtl, {{name, addr}});
  550. // SimulateReceive only lets the last created socket receive.
  551. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  552. socket_factory_.SimulateReceive(
  553. reinterpret_cast<const uint8_t*>(query1.data()), query1.size());
  554. socket_factory_.SimulateReceive(
  555. reinterpret_cast<const uint8_t*>(query2.data()), query2.size());
  556. RunUntilNoTasksRemain();
  557. }
  558. // Test that the responder does not respond to any query about a name that is
  559. // unknown to it.
  560. TEST_F(MdnsResponderTest, SendNoResponseToQueryForRemovedName) {
  561. const auto& addr = kPublicAddrs[0];
  562. const auto name = CreateNameForAddress(0, addr);
  563. RemoveNameForAddressAndExpectDone(0, addr);
  564. RunUntilNoTasksRemain();
  565. std::string query = CreateMdnsQuery(0, {name});
  566. EXPECT_CALL(socket_factory_, OnSendTo(_)).Times(0);
  567. socket_factory_.SimulateReceive(
  568. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  569. RunUntilNoTasksRemain();
  570. }
  571. // Test that the responder sends a negative response to any query that is not
  572. // of type A, AAAA, or ANY.
  573. TEST_F(MdnsResponderTest, SendNegativeResponseToQueryForNonAddressRecord) {
  574. const auto& addr = kPublicAddrs[0];
  575. const auto name = CreateNameForAddress(0, addr);
  576. const std::set<uint16_t> non_address_qtypes = {
  577. net::dns_protocol::kTypeCNAME, net::dns_protocol::kTypeSOA,
  578. net::dns_protocol::kTypePTR, net::dns_protocol::kTypeTXT,
  579. net::dns_protocol::kTypeSRV, net::dns_protocol::kTypeOPT,
  580. net::dns_protocol::kTypeNSEC,
  581. };
  582. std::string expected_negative_response =
  583. CreateNegativeResponse({{name, addr}});
  584. for (auto qtype : non_address_qtypes) {
  585. std::string query = CreateMdnsQuery(0, {name}, qtype);
  586. EXPECT_CALL(socket_factory_, OnSendTo(expected_negative_response)).Times(1);
  587. socket_factory_.SimulateReceive(
  588. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  589. RunUntilNoTasksRemain();
  590. }
  591. }
  592. // Test that the mDNS responder service can respond to an mDNS name generator
  593. // service query with all existing names.
  594. TEST_F(MdnsResponderTest,
  595. SendResponseToMdnsNameGeneratorServiceQueryWithAllExistingNames) {
  596. const auto& addr1 = kPublicAddrs[0];
  597. const auto& addr2 = kPublicAddrs[1];
  598. // Let two names be created by different clients.
  599. const std::string name1 = CreateNameForAddress(0, addr1);
  600. const std::string name2 = CreateNameForAddress(1, addr2);
  601. const std::string query = CreateMdnsQuery(
  602. 0, kMdnsNameGeneratorServiceInstanceName, net::dns_protocol::kTypeTXT);
  603. // The response should contain both names.
  604. const std::string expected_response1 =
  605. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl,
  606. {name1, name2});
  607. EXPECT_CALL(socket_factory_, OnSendTo(expected_response1)).Times(1);
  608. socket_factory_.SimulateReceive(
  609. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  610. RunUntilNoTasksRemain();
  611. // Remove |name2|.
  612. std::string expected_goodbye =
  613. CreateResolutionResponse(base::TimeDelta(), {{name2, addr2}});
  614. // Goodbye on both interfaces.
  615. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye)).Times(2);
  616. RemoveNameForAddressAndExpectDone(1 /* client_id */, addr2);
  617. RunUntilNoTasksRemain();
  618. // The response should contain only |name1|.
  619. const std::string expected_response2 =
  620. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl, {name1});
  621. EXPECT_CALL(socket_factory_, OnSendTo(expected_response2)).Times(1);
  622. socket_factory_.SimulateReceive(
  623. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  624. RunUntilNoTasksRemain();
  625. }
  626. // Test that the responder manager closes the connection after
  627. // an invalid IP address is given to create a name for.
  628. TEST_F(MdnsResponderTest,
  629. HostClosesMojoConnectionWhenCreatingNameForInvalidAddress) {
  630. base::HistogramTester tester;
  631. const net::IPAddress addr;
  632. ASSERT_TRUE(!addr.IsValid());
  633. EXPECT_TRUE(client_[0].is_bound());
  634. // No packet should be sent out from interfaces.
  635. EXPECT_CALL(socket_factory_, OnSendTo(_)).Times(0);
  636. CreateNameForAddress(0, addr);
  637. EXPECT_FALSE(client_[0].is_bound());
  638. tester.ExpectBucketCount(kServiceErrorHistogram,
  639. ServiceError::kInvalidIpToRegisterName, 1);
  640. tester.ExpectTotalCount(kServiceErrorHistogram, 1);
  641. }
  642. // Test that the responder manager closes the connection after observing
  643. // conflicting name resolution in the network.
  644. TEST_F(MdnsResponderTest,
  645. HostClosesMojoConnectionAfterObservingAddressNameConflict) {
  646. const auto& addr1 = kPublicAddrs[0];
  647. const auto& addr2 = kPublicAddrs[1];
  648. const auto name1 = CreateNameForAddress(0, addr1);
  649. const auto name2 = CreateNameForAddress(0, addr2);
  650. std::string query1 = CreateMdnsQuery(0, {name1});
  651. std::string query2 = CreateMdnsQuery(0, {name2});
  652. std::string conflicting_response =
  653. CreateResolutionResponse(kDefaultTtl, {{name1, addr2}});
  654. std::string expected_goodbye = CreateResolutionResponse(
  655. base::TimeDelta(), {{name1, addr1}, {name2, addr2}});
  656. EXPECT_TRUE(client_[0].is_bound());
  657. // MockMdnsSocketFactory binds sockets to two interfaces.
  658. // We should send only two goodbyes before closing the connection and no
  659. // packet should be sent out from interfaces after the connection is closed.
  660. EXPECT_CALL(socket_factory_, OnSendTo(_)).Times(0);
  661. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye)).Times(2);
  662. socket_factory_.SimulateReceive(
  663. reinterpret_cast<const uint8_t*>(conflicting_response.data()),
  664. conflicting_response.size());
  665. RunUntilNoTasksRemain();
  666. // The responder should have observed the conflict and the responder manager
  667. // should have closed the Mojo connection and sent out the goodbye messages
  668. // for owned names.
  669. EXPECT_FALSE(client_[0].is_bound());
  670. // Also, as a result, we should have stopped responding to the following
  671. // queries.
  672. socket_factory_.SimulateReceive(
  673. reinterpret_cast<const uint8_t*>(query1.data()), query1.size());
  674. socket_factory_.SimulateReceive(
  675. reinterpret_cast<const uint8_t*>(query2.data()), query2.size());
  676. RunUntilNoTasksRemain();
  677. }
  678. // Test that we stop sending response to the mDNS name generator service queries
  679. // when there is an external response carrying a TXT record with the same
  680. // service instance name and the cache-flush bit set.
  681. TEST_F(MdnsResponderTest,
  682. StopRespondingToGeneratorServiceQueryAfterObservingTxtNameConflict) {
  683. const auto& addr = kPublicAddrs[0];
  684. const std::string name = CreateNameForAddress(0, addr);
  685. const std::string query = CreateMdnsQuery(
  686. 0, kMdnsNameGeneratorServiceInstanceName, net::dns_protocol::kTypeTXT);
  687. // Verify that we can respond to the service query.
  688. const std::string expected_response =
  689. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl, {name});
  690. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  691. socket_factory_.SimulateReceive(
  692. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  693. RunUntilNoTasksRemain();
  694. // Receive a conflicting response.
  695. const std::string conflicting_response =
  696. CreateResponseToMdnsNameGeneratorServiceQueryWithCacheFlush(
  697. {"dummy.local"});
  698. socket_factory_.SimulateReceive(
  699. reinterpret_cast<const uint8_t*>(conflicting_response.data()),
  700. conflicting_response.size());
  701. RunUntilNoTasksRemain();
  702. // We should have stopped responding to service queries.
  703. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(0);
  704. socket_factory_.SimulateReceive(
  705. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  706. RunUntilNoTasksRemain();
  707. }
  708. // Test that an external response with the same service instance name but
  709. // without the cache-flush bit set is not considered a conflict.
  710. TEST_F(MdnsResponderTest,
  711. NoConflictResolutionIfCacheFlushBitSetInExternalResponse) {
  712. const auto& addr = kPublicAddrs[0];
  713. const std::string name = CreateNameForAddress(0, addr);
  714. // Receive an external response to the same instance name but without the
  715. // cache-flush bit set in the TXT record.
  716. const std::string nonconflict_response =
  717. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl,
  718. {"dummy.local"});
  719. socket_factory_.SimulateReceive(
  720. reinterpret_cast<const uint8_t*>(nonconflict_response.data()),
  721. nonconflict_response.size());
  722. RunUntilNoTasksRemain();
  723. const std::string query = CreateMdnsQuery(
  724. 0, kMdnsNameGeneratorServiceInstanceName, net::dns_protocol::kTypeTXT);
  725. // We can still respond to the service query.
  726. const std::string expected_response =
  727. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl, {name});
  728. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  729. socket_factory_.SimulateReceive(
  730. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  731. RunUntilNoTasksRemain();
  732. }
  733. // Test that scheduled responses to mDNS name generator service queries can be
  734. // cancelled after observing conflict with external records.
  735. TEST_F(MdnsResponderTest,
  736. CancelResponseToGeneratorServiceQueryAfterObservingTxtNameConflict) {
  737. const auto& addr = kPublicAddrs[0];
  738. const std::string name = CreateNameForAddress(0, addr);
  739. // Receive a series of queries so that we have delayed responses scheduled
  740. // because of rate limiting. We will also receive a conflicting response after
  741. // the first response sent to cancel the subsequent ones.
  742. const std::string query = CreateMdnsQuery(
  743. 0, kMdnsNameGeneratorServiceInstanceName, net::dns_protocol::kTypeTXT);
  744. const std::string expected_response =
  745. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl, {name});
  746. // We should have only the first response sent and the rest cancelled after
  747. // encountering the conflicting.
  748. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  749. socket_factory_.SimulateReceive(
  750. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  751. socket_factory_.SimulateReceive(
  752. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  753. socket_factory_.SimulateReceive(
  754. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  755. RunFor(base::Milliseconds(900));
  756. // Receive a conflicting response.
  757. const std::string conflicting_response =
  758. CreateResponseToMdnsNameGeneratorServiceQueryWithCacheFlush(
  759. {"dummy.local"});
  760. socket_factory_.SimulateReceive(
  761. reinterpret_cast<const uint8_t*>(conflicting_response.data()),
  762. conflicting_response.size());
  763. RunUntilNoTasksRemain();
  764. }
  765. // Test that if we ever send any response to mDNS name generator service
  766. // queries, a goodbye packet is sent when the responder manager is destroyed.
  767. TEST_F(MdnsResponderTest,
  768. SendGoodbyeForMdnsNameGeneratorServiceAfterManagerDestroyed) {
  769. const auto& addr = kPublicAddrs[0];
  770. const std::string name = CreateNameForAddress(0, addr);
  771. const std::string query = CreateMdnsQuery(
  772. 0, kMdnsNameGeneratorServiceInstanceName, net::dns_protocol::kTypeTXT);
  773. const std::string expected_response =
  774. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl, {name});
  775. // Respond to a generator service query once.
  776. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  777. socket_factory_.SimulateReceive(
  778. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  779. RunFor(base::Milliseconds(1000));
  780. // Goodbye on both interfaces.
  781. const std::string expected_goodbye =
  782. CreateResponseToMdnsNameGeneratorServiceQuery(base::TimeDelta(), {name});
  783. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye)).Times(2);
  784. host_manager_ = nullptr;
  785. RunUntilNoTasksRemain();
  786. }
  787. // Test that we do not send any goodbye packet to flush TXT records of
  788. // owned names when the responder manager is destroyed, if we have not sent any
  789. // response to mDNS name generator service queries.
  790. TEST_F(MdnsResponderTest,
  791. NoGoodbyeForMdnsNameGeneratorServiceIfNoPreviousServiceResponseSent) {
  792. const auto& addr = kPublicAddrs[0];
  793. const std::string name = CreateNameForAddress(0, addr);
  794. const std::string goodbye =
  795. CreateResponseToMdnsNameGeneratorServiceQuery(base::TimeDelta(), {name});
  796. EXPECT_CALL(socket_factory_, OnSendTo(goodbye)).Times(0);
  797. host_manager_ = nullptr;
  798. RunUntilNoTasksRemain();
  799. }
  800. // Test that the responder host clears all name-address maps in one goodbye
  801. // message with zero TTL for a client after the Mojo connection between them is
  802. // lost.
  803. TEST_F(MdnsResponderTest, ResponderHostDoesCleanUpAfterMojoConnectionError) {
  804. const auto& addr1 = kPublicAddrs[0];
  805. const auto& addr2 = kPublicAddrs[1];
  806. const auto name1 = CreateNameForAddress(0, addr1);
  807. const auto name2 = CreateNameForAddress(0, addr2);
  808. std::string expected_goodbye = CreateResolutionResponse(
  809. base::TimeDelta(), {{name1, addr1}, {name2, addr2}});
  810. // MockMdnsSocketFactory binds sockets to two interfaces.
  811. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye)).Times(2);
  812. CloseConnectionToResponderHost(0);
  813. RunUntilNoTasksRemain();
  814. }
  815. // Test that the host generates a Mojo connection error when no socket handler
  816. // is successfully started, and subsequent retry attempts are throttled.
  817. TEST_F(MdnsResponderTest, ClosesBindingWhenNoSocketHanlderStarted) {
  818. // Expect only one attempt to create sockets before start throttling prevents
  819. // further attempts.
  820. EXPECT_CALL(failing_socket_factory_, CreateSockets(_)).WillOnce(Return());
  821. Reset(true /* use_failing_socket_factory */);
  822. RunUntilNoTasksRemain();
  823. // MdnsResponderTest::OnMojoConnectionError.
  824. EXPECT_FALSE(client_[0].is_bound());
  825. EXPECT_FALSE(client_[1].is_bound());
  826. // Little extra fudge around throttle delays as it is not essential for it to
  827. // be precise, and don't need the test to be too restrictive.
  828. const base::TimeDelta kThrottleFudge = base::Milliseconds(2);
  829. // Expect socket creation to not be attempted again too soon.
  830. EXPECT_CALL(failing_socket_factory_, CreateSockets(_)).Times(0);
  831. RunFor(MdnsResponderManager::kManagerStartThrottleDelay - kThrottleFudge);
  832. CreateMdnsResponders();
  833. RunUntilNoTasksRemain();
  834. EXPECT_FALSE(client_[0].is_bound());
  835. EXPECT_FALSE(client_[1].is_bound());
  836. // Expect no change for subsequent responder creation attempts if socket
  837. // creation still fails.
  838. EXPECT_CALL(failing_socket_factory_, CreateSockets(_)).WillOnce(Return());
  839. RunFor(2 * kThrottleFudge);
  840. CreateMdnsResponders();
  841. RunUntilNoTasksRemain();
  842. EXPECT_FALSE(client_[0].is_bound());
  843. EXPECT_FALSE(client_[1].is_bound());
  844. // Expect socket creation to not be attempted again too soon.
  845. EXPECT_CALL(failing_socket_factory_, CreateSockets(_)).Times(0);
  846. RunFor(MdnsResponderManager::kManagerStartThrottleDelay - kThrottleFudge);
  847. CreateMdnsResponders();
  848. RunUntilNoTasksRemain();
  849. EXPECT_FALSE(client_[0].is_bound());
  850. EXPECT_FALSE(client_[1].is_bound());
  851. // Simulate socket creation fixing itself, and expect responder creation
  852. // should be able to succeed through retry.
  853. EXPECT_CALL(failing_socket_factory_, CreateSockets(_))
  854. .WillOnce(
  855. Invoke(&socket_factory_, &net::MockMDnsSocketFactory::CreateSockets));
  856. RunFor(2 * kThrottleFudge);
  857. CreateMdnsResponders();
  858. RunUntilNoTasksRemain();
  859. EXPECT_TRUE(client_[0].is_bound());
  860. EXPECT_TRUE(client_[1].is_bound());
  861. // After success, new responders can be created without repeating socket
  862. // creation.
  863. EXPECT_CALL(failing_socket_factory_, CreateSockets(_)).Times(0);
  864. RunFor(MdnsResponderManager::kManagerStartThrottleDelay + kThrottleFudge);
  865. mojo::Remote<mojom::MdnsResponder> responder;
  866. host_manager_->CreateMdnsResponder(responder.BindNewPipeAndPassReceiver());
  867. RunUntilNoTasksRemain();
  868. EXPECT_TRUE(responder.is_bound());
  869. }
  870. // Test that an announcement is retried after send failure.
  871. TEST_F(MdnsResponderTest, AnnouncementRetriedAfterSendFailure) {
  872. auto create_send_failing_socket =
  873. [this](std::vector<std::unique_ptr<net::DatagramServerSocket>>* sockets) {
  874. auto socket =
  875. std::make_unique<NiceMock<net::MockMDnsDatagramServerSocket>>(
  876. net::ADDRESS_FAMILY_IPV4);
  877. ON_CALL(*socket, SendToInternal(_, _, _))
  878. .WillByDefault(Invoke(&failing_socket_factory_,
  879. &MockFailingMdnsSocketFactory::FailToSend));
  880. ON_CALL(*socket, RecvFrom(_, _, _, _)).WillByDefault(Return(-1));
  881. sockets->push_back(std::move(socket));
  882. };
  883. EXPECT_CALL(failing_socket_factory_, CreateSockets(_))
  884. .WillOnce(Invoke(create_send_failing_socket));
  885. Reset(true /* use_failing_socket_factory */);
  886. const auto& addr = kPublicAddrs[0];
  887. std::string expected_announcement =
  888. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr}});
  889. // Mocked CreateSockets above only creates one socket.
  890. EXPECT_CALL(failing_socket_factory_, OnSendTo(expected_announcement))
  891. .Times(kNumAnnouncementsPerInterface + kNumMaxRetriesPerResponse);
  892. const auto name = CreateNameForAddress(0, addr);
  893. RunUntilNoTasksRemain();
  894. }
  895. // Test that responses as announcements are sent following the per-response rate
  896. // limit.
  897. TEST_F(MdnsResponderTest, AnnouncementsAreRateLimitedPerResponse) {
  898. const auto& addr1 = kPublicAddrs[0];
  899. const auto& addr2 = kPublicAddrs[1];
  900. std::string expected_announcement1 =
  901. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr1}});
  902. std::string expected_announcement2 =
  903. CreateResolutionResponse(kDefaultTtl, {{"1.local", addr2}});
  904. // First announcement for 0.local.
  905. // MockMdnsSocketFactory binds sockets to two interfaces.
  906. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement1)).Times(2);
  907. // We need the async call from the client.
  908. client_[0]->CreateNameForAddress(addr1, base::DoNothing());
  909. client_[0]->CreateNameForAddress(addr2, base::DoNothing());
  910. RunFor(base::Milliseconds(900));
  911. // Second announcement for 0.local.
  912. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement1)).Times(2);
  913. RunFor(base::Seconds(1));
  914. // First announcement for 1.local.
  915. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement2)).Times(2);
  916. RunFor(base::Seconds(1));
  917. // Second announcement for 1.local.
  918. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement2)).Times(2);
  919. RunUntilNoTasksRemain();
  920. }
  921. // Test that responses as goodbyes are sent following the per-response rate
  922. // limit.
  923. TEST_F(MdnsResponderTest, GoodbyesAreRateLimitedPerResponse) {
  924. const auto& addr1 = kPublicAddrs[0];
  925. const auto& addr2 = kPublicAddrs[1];
  926. // Note that the wrapper method calls below are sync and announcements are
  927. // sent after they return.
  928. auto name1 = CreateNameForAddress(0, addr1);
  929. auto name2 = CreateNameForAddress(0, addr2);
  930. std::string expected_goodbye1 =
  931. CreateResolutionResponse(base::TimeDelta(), {{name1, addr1}});
  932. std::string expected_goodbye2 =
  933. CreateResolutionResponse(base::TimeDelta(), {{name2, addr2}});
  934. // Goodbye for 0.local.
  935. // MockMdnsSocketFactory binds sockets to two interfaces.
  936. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye1)).Times(2);
  937. // Note that the wrapper method calls below are async.
  938. RemoveNameForAddressAndExpectDone(0, addr1);
  939. RemoveNameForAddressAndExpectDone(0, addr2);
  940. RunFor(base::Milliseconds(900));
  941. // Goodbye for 1.local.
  942. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye2)).Times(2);
  943. RunUntilNoTasksRemain();
  944. }
  945. // Test that the mixture of announcements and goodbyes are sent following the
  946. // per-response rate limit.
  947. TEST_F(MdnsResponderTest, AnnouncementsAndGoodbyesAreRateLimitedPerResponse) {
  948. const auto& addr1 = kPublicAddrs[0];
  949. const auto& addr2 = kPublicAddrs[1];
  950. std::string expected_announcement1 =
  951. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr1}});
  952. std::string expected_announcement2 =
  953. CreateResolutionResponse(kDefaultTtl, {{"1.local", addr2}});
  954. std::string expected_goodbye1 =
  955. CreateResolutionResponse(base::TimeDelta(), {{"0.local", addr1}});
  956. std::string expected_goodbye2 =
  957. CreateResolutionResponse(base::TimeDelta(), {{"1.local", addr2}});
  958. // First announcement for 0.local.
  959. // MockMdnsSocketFactory binds sockets to two interfaces.
  960. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement1)).Times(2);
  961. // We need the async call from the client.
  962. client_[0]->CreateNameForAddress(addr1, base::DoNothing());
  963. RemoveNameForAddressAndExpectDone(0, addr1);
  964. client_[0]->CreateNameForAddress(addr2, base::DoNothing());
  965. RemoveNameForAddressAndExpectDone(0, addr2);
  966. RunFor(base::Milliseconds(900));
  967. // Second announcement for 0.local.
  968. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement1)).Times(2);
  969. RunFor(base::Seconds(1));
  970. // Goodbye for 0.local.
  971. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye1)).Times(2);
  972. RunFor(base::Seconds(1));
  973. // First announcement for 1.local.
  974. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement2)).Times(2);
  975. RunFor(base::Seconds(1));
  976. // Second announcement for 1.local.
  977. EXPECT_CALL(socket_factory_, OnSendTo(expected_announcement2)).Times(2);
  978. RunFor(base::Seconds(1));
  979. // Goodbye for 1.local.
  980. EXPECT_CALL(socket_factory_, OnSendTo(expected_goodbye2)).Times(2);
  981. RunUntilNoTasksRemain();
  982. }
  983. // Test that responses to the name generator service queries are sent following
  984. // the per-record rate limit, so that each message is separated by at least one
  985. // second.
  986. TEST_F(MdnsResponderTest,
  987. MdnsNameGeneratorServiceResponsesAreRateLimitedPerRecord) {
  988. const auto& addr = kPublicAddrs[0];
  989. const std::string name = CreateNameForAddress(0, addr);
  990. // After a name has been created for |addr|, let the responder receive
  991. // queries. Their responses should be scheduled sequentially, each separated
  992. // by at least one second. Note that responses to the mDNS name generator
  993. // service queries have an extra delay of 20-120ms as the service instance
  994. // name is shared among Chrome instances.
  995. const std::string query = CreateMdnsQuery(
  996. 0, kMdnsNameGeneratorServiceInstanceName, net::dns_protocol::kTypeTXT);
  997. socket_factory_.SimulateReceive(
  998. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  999. socket_factory_.SimulateReceive(
  1000. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  1001. const std::string expected_response =
  1002. CreateResponseToMdnsNameGeneratorServiceQuery(kDefaultTtl, {"0.local"});
  1003. // Response to the first query is sent right after the query is received.
  1004. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  1005. // Response to the second received query will be delayed for another one
  1006. // second plus an extra delay of 20-120ms.
  1007. RunFor(base::Milliseconds(1015));
  1008. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(1);
  1009. RunUntilNoTasksRemain();
  1010. }
  1011. // Test that responses with resource records for name resolution are sent based
  1012. // on a per-record rate limit.
  1013. TEST_F(MdnsResponderTest, ResolutionResponsesAreRateLimitedPerRecord) {
  1014. const auto& addr1 = kPublicAddrs[0];
  1015. const auto& addr2 = kPublicAddrs[1];
  1016. auto name1 = CreateNameForAddress(0, addr1);
  1017. auto name2 = CreateNameForAddress(0, addr2);
  1018. // kPublicAddrs are IPv4.
  1019. std::string query1 = CreateMdnsQuery(0, {name1}, net::dns_protocol::kTypeA);
  1020. std::string query2 = CreateMdnsQuery(0, {name2}, net::dns_protocol::kTypeA);
  1021. std::string expected_response1 =
  1022. CreateResolutionResponse(kDefaultTtl, {{name1, addr1}});
  1023. std::string expected_response2 =
  1024. CreateResolutionResponse(kDefaultTtl, {{name2, addr2}});
  1025. // Resolution for name1.
  1026. EXPECT_CALL(socket_factory_, OnSendTo(expected_response1)).Times(1);
  1027. // Resolution for name2.
  1028. EXPECT_CALL(socket_factory_, OnSendTo(expected_response2)).Times(1);
  1029. // SimulateReceive only lets the last created socket receive.
  1030. socket_factory_.SimulateReceive(
  1031. reinterpret_cast<const uint8_t*>(query1.data()), query1.size());
  1032. socket_factory_.SimulateReceive(
  1033. reinterpret_cast<const uint8_t*>(query2.data()), query2.size());
  1034. socket_factory_.SimulateReceive(
  1035. reinterpret_cast<const uint8_t*>(query1.data()), query1.size());
  1036. RunFor(base::Milliseconds(900));
  1037. // Resolution for name1 for the second query about it.
  1038. EXPECT_CALL(socket_factory_, OnSendTo(expected_response1)).Times(1);
  1039. RunUntilNoTasksRemain();
  1040. }
  1041. // Test that negative responses to queries for non-existing records are sent
  1042. // based on a per-record rate limit.
  1043. TEST_F(MdnsResponderTest, NegativeResponsesAreRateLimitedPerRecord) {
  1044. const auto& addr1 = kPublicAddrs[0];
  1045. const auto& addr2 = kPublicAddrs[1];
  1046. auto name1 = CreateNameForAddress(0, addr1);
  1047. auto name2 = CreateNameForAddress(0, addr2);
  1048. // kPublicAddrs are IPv4 and type AAAA records do not exist.
  1049. std::string query1 =
  1050. CreateMdnsQuery(0, {name1}, net::dns_protocol::kTypeAAAA);
  1051. std::string query2 =
  1052. CreateMdnsQuery(0, {name2}, net::dns_protocol::kTypeAAAA);
  1053. std::string expected_response1 = CreateNegativeResponse({{name1, addr1}});
  1054. std::string expected_response2 = CreateNegativeResponse({{name2, addr2}});
  1055. // Negative response for name1.
  1056. EXPECT_CALL(socket_factory_, OnSendTo(expected_response1)).Times(1);
  1057. // Negative response for name2.
  1058. EXPECT_CALL(socket_factory_, OnSendTo(expected_response2)).Times(1);
  1059. // SimulateReceive only lets the last created socket receive.
  1060. socket_factory_.SimulateReceive(
  1061. reinterpret_cast<const uint8_t*>(query1.data()), query1.size());
  1062. socket_factory_.SimulateReceive(
  1063. reinterpret_cast<const uint8_t*>(query2.data()), query2.size());
  1064. socket_factory_.SimulateReceive(
  1065. reinterpret_cast<const uint8_t*>(query1.data()), query1.size());
  1066. RunFor(base::Milliseconds(900));
  1067. // Negative response for name1 for the second query about it.
  1068. EXPECT_CALL(socket_factory_, OnSendTo(expected_response1)).Times(1);
  1069. RunUntilNoTasksRemain();
  1070. }
  1071. // Test that the mixture of resolution and negative responses are sent following
  1072. // the per-record rate limit.
  1073. TEST_F(MdnsResponderTest,
  1074. ResolutionAndNegativeResponsesAreRateLimitedPerRecord) {
  1075. const auto& addr = kPublicAddrs[0];
  1076. auto name = CreateNameForAddress(0, addr);
  1077. // kPublicAddrs are IPv4 and type AAAA records do not exist.
  1078. std::string query_a = CreateMdnsQuery(0, {name}, net::dns_protocol::kTypeA);
  1079. std::string query_aaaa =
  1080. CreateMdnsQuery(0, {name}, net::dns_protocol::kTypeAAAA);
  1081. std::string expected_resolution =
  1082. CreateResolutionResponse(kDefaultTtl, {{name, addr}});
  1083. std::string expected_negative_resp = CreateNegativeResponse({{name, addr}});
  1084. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution)).Times(1);
  1085. socket_factory_.SimulateReceive(
  1086. reinterpret_cast<const uint8_t*>(query_a.data()), query_a.size());
  1087. socket_factory_.SimulateReceive(
  1088. reinterpret_cast<const uint8_t*>(query_aaaa.data()), query_aaaa.size());
  1089. RunFor(base::Milliseconds(900));
  1090. EXPECT_CALL(socket_factory_, OnSendTo(expected_negative_resp)).Times(1);
  1091. RunUntilNoTasksRemain();
  1092. }
  1093. // Test that we send responses immediately to probing queries with qtype ANY.
  1094. TEST_F(MdnsResponderTest, ResponsesToProbesAreNotRateLimited) {
  1095. const auto& addr = kPublicAddrs[0];
  1096. auto name = CreateNameForAddress(0, addr);
  1097. // Type ANY for probing queries.
  1098. //
  1099. // TODO(qingsi): Setting the type to kTypeAny is not sufficient to construct a
  1100. // proper probe query. We also need to include a record in the Authority
  1101. // section. See the comment inside IsProbeQuery in mdns_responder.cc. After we
  1102. // support parsing the Authority section of a query in DnsQuery, we should
  1103. // create the following probe query by the standard definition.
  1104. std::string query = CreateMdnsQuery(0, {name}, net::dns_protocol::kTypeANY);
  1105. std::string expected_response =
  1106. CreateResolutionResponse(kDefaultTtl, {{name, addr}});
  1107. EXPECT_CALL(socket_factory_, OnSendTo(expected_response)).Times(2);
  1108. // SimulateReceive only lets the last created socket receive.
  1109. socket_factory_.SimulateReceive(
  1110. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  1111. socket_factory_.SimulateReceive(
  1112. reinterpret_cast<const uint8_t*>(query.data()), query.size());
  1113. RunFor(base::Milliseconds(500));
  1114. }
  1115. // Test that different rate limit schemes effectively form different queues of
  1116. // responses that do not interfere with each other.
  1117. TEST_F(MdnsResponderTest, RateLimitSchemesDoNotInterfere) {
  1118. const auto& addr1 = kPublicAddrsIpv6[0];
  1119. const auto& addr2 = kPublicAddrsIpv6[1];
  1120. // SimpleNameGenerator.
  1121. std::string name1 = "0.local";
  1122. std::string name2 = "1.local";
  1123. std::string query1_a = CreateMdnsQuery(0, {name1}, net::dns_protocol::kTypeA);
  1124. std::string query1_aaaa =
  1125. CreateMdnsQuery(0, {name1}, net::dns_protocol::kTypeAAAA);
  1126. std::string query1_any =
  1127. CreateMdnsQuery(0, {name1}, net::dns_protocol::kTypeANY);
  1128. std::string query2_a = CreateMdnsQuery(0, {name2}, net::dns_protocol::kTypeA);
  1129. std::string query2_aaaa =
  1130. CreateMdnsQuery(0, {name2}, net::dns_protocol::kTypeAAAA);
  1131. std::string query2_any =
  1132. CreateMdnsQuery(0, {name2}, net::dns_protocol::kTypeANY);
  1133. std::string expected_resolution1 =
  1134. CreateResolutionResponse(kDefaultTtl, {{name1, addr1}});
  1135. std::string expected_resolution2 =
  1136. CreateResolutionResponse(kDefaultTtl, {{name2, addr2}});
  1137. std::string expected_negative_resp1 =
  1138. CreateNegativeResponse({{name1, addr1}});
  1139. std::string expected_negative_resp2 =
  1140. CreateNegativeResponse({{name2, addr2}});
  1141. auto do_sequence_after_name_created =
  1142. [](net::MockMDnsSocketFactory* socket_factory, const std::string& query_a,
  1143. const std::string& query_aaaa, const std::string& query_any,
  1144. const std::string& /* name */, bool /* announcement_scheduled */) {
  1145. socket_factory->SimulateReceive(
  1146. reinterpret_cast<const uint8_t*>(query_a.data()), query_a.size());
  1147. socket_factory->SimulateReceive(
  1148. reinterpret_cast<const uint8_t*>(query_aaaa.data()),
  1149. query_aaaa.size());
  1150. socket_factory->SimulateReceive(
  1151. reinterpret_cast<const uint8_t*>(query_any.data()),
  1152. query_any.size());
  1153. };
  1154. // 2 first announcements for name1 from 2 interfaces (per-response limit) and
  1155. // 1 response to the probing query1_any (no limit).
  1156. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution1)).Times(3);
  1157. // 1 negative response to query1_a (per-record limit).
  1158. EXPECT_CALL(socket_factory_, OnSendTo(expected_negative_resp1)).Times(1);
  1159. // 1 response to the probing query2_any (no limit).
  1160. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution2)).Times(1);
  1161. // 1 negative response to query2_a (per-record limit).
  1162. EXPECT_CALL(socket_factory_, OnSendTo(expected_negative_resp2)).Times(1);
  1163. client_[0]->CreateNameForAddress(
  1164. addr1, base::BindOnce(do_sequence_after_name_created, &socket_factory_,
  1165. query1_a, query1_aaaa, query1_any));
  1166. client_[0]->CreateNameForAddress(
  1167. addr2, base::BindOnce(do_sequence_after_name_created, &socket_factory_,
  1168. query2_a, query2_aaaa, query2_any));
  1169. RunFor(base::Milliseconds(900));
  1170. // 2 second announcements for name1 from 2 interfaces, and 1 response to
  1171. // query1_aaaa (per-record limit).
  1172. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution1)).Times(3);
  1173. // 1 response to query2_aaaa (per-record limit).
  1174. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution2)).Times(1);
  1175. RunFor(base::Seconds(1));
  1176. // 2 first announcements for name2 from 2 interfaces.
  1177. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution2)).Times(2);
  1178. RunFor(base::Seconds(1));
  1179. // 2 second announcements for name2 from 2 interfaces.
  1180. EXPECT_CALL(socket_factory_, OnSendTo(expected_resolution2)).Times(2);
  1181. RunUntilNoTasksRemain();
  1182. }
  1183. // Test that the responder does not send an announcement if the current
  1184. // scheduled delay exceeds the maximum delay allowed, and the client side gets
  1185. // notified of the result.
  1186. TEST_F(MdnsResponderTest, LongDelayedAnnouncementIsNotScheduled) {
  1187. const auto& addr = kPublicAddrs[0];
  1188. // Enqueue announcements and delays so that we reach the maximum delay
  1189. // allowed of the per-response rate limit. Our current implementation defines
  1190. // a 10-second maximum scheduled delay (see kMaxScheduledDelay in
  1191. // mdns_responder.cc).
  1192. for (int i = 0; i < 5; ++i) {
  1193. // Use the async call from the client.
  1194. client_[0]->CreateNameForAddress(addr, base::DoNothing());
  1195. client_[0]->RemoveNameForAddress(addr, base::DoNothing());
  1196. }
  1197. client_[0]->CreateNameForAddress(
  1198. addr, base::BindOnce([](const std::string&, bool announcement_scheduled) {
  1199. EXPECT_FALSE(announcement_scheduled);
  1200. }));
  1201. RunUntilNoTasksRemain();
  1202. }
  1203. // Test that all pending sends scheduled are cancelled if the responder manager
  1204. // is destroyed.
  1205. TEST_F(MdnsResponderTest, ScheduledSendsAreCancelledAfterManagerDestroyed) {
  1206. const auto& addr = kPublicAddrs[0];
  1207. EXPECT_CALL(socket_factory_, OnSendTo(_)).Times(0);
  1208. // Use the async call from the client.
  1209. client_[0]->CreateNameForAddress(addr, base::DoNothing());
  1210. client_[0]->RemoveNameForAddress(addr, base::DoNothing());
  1211. host_manager_.reset();
  1212. RunUntilNoTasksRemain();
  1213. }
  1214. // Test that if all socket handlers fail to read, the manager restarts itself.
  1215. TEST_F(MdnsResponderTest, ManagerCanRestartAfterAllSocketHandlersFailToRead) {
  1216. base::HistogramTester tester;
  1217. auto create_read_failing_socket =
  1218. [this](std::vector<std::unique_ptr<net::DatagramServerSocket>>* sockets) {
  1219. auto socket =
  1220. std::make_unique<NiceMock<net::MockMDnsDatagramServerSocket>>(
  1221. net::ADDRESS_FAMILY_IPV4);
  1222. ON_CALL(*socket, SendToInternal(_, _, _)).WillByDefault(Return(0));
  1223. ON_CALL(*socket, RecvFrom(_, _, _, _))
  1224. .WillByDefault(Invoke(&failing_socket_factory_,
  1225. &MockFailingMdnsSocketFactory::FailToRecv));
  1226. sockets->push_back(std::move(socket));
  1227. };
  1228. EXPECT_CALL(failing_socket_factory_, CreateSockets(_))
  1229. .WillOnce(Invoke(create_read_failing_socket));
  1230. Reset(true /* use_failing_socket_factory */);
  1231. // Called when the manager restarts. The mocked CreateSockets() by default
  1232. // returns an empty vector of sockets, thus failing the restart again.
  1233. EXPECT_CALL(failing_socket_factory_, CreateSockets(_)).Times(1);
  1234. RunUntilNoTasksRemain();
  1235. tester.ExpectBucketCount(kServiceErrorHistogram,
  1236. ServiceError::kFatalSocketHandlerError, 1);
  1237. tester.ExpectBucketCount(kServiceErrorHistogram,
  1238. ServiceError::kFailToStartManager, 1);
  1239. tester.ExpectTotalCount(kServiceErrorHistogram, 2);
  1240. }
  1241. // Test that sending packets on an interface can be blocked by an incomplete
  1242. // send on the same interface. Blocked packets are later flushed when sending is
  1243. // unblocked.
  1244. TEST_F(MdnsResponderTest, IncompleteSendBlocksFollowingSends) {
  1245. auto create_send_blocking_socket =
  1246. [this](std::vector<std::unique_ptr<net::DatagramServerSocket>>* sockets) {
  1247. auto socket =
  1248. std::make_unique<NiceMock<net::MockMDnsDatagramServerSocket>>(
  1249. net::ADDRESS_FAMILY_IPV4);
  1250. ON_CALL(*socket, SendToInternal(_, _, _))
  1251. .WillByDefault(
  1252. Invoke(&failing_socket_factory_,
  1253. &MockFailingMdnsSocketFactory::MaybeBlockSend));
  1254. ON_CALL(*socket, RecvFrom(_, _, _, _)).WillByDefault(Return(-1));
  1255. sockets->push_back(std::move(socket));
  1256. };
  1257. EXPECT_CALL(failing_socket_factory_, CreateSockets(_))
  1258. .WillOnce(Invoke(create_send_blocking_socket));
  1259. Reset(true /* use_failing_socket_factory */);
  1260. const auto& addr1 = kPublicAddrs[0];
  1261. std::string expected_announcement1 =
  1262. CreateResolutionResponse(kDefaultTtl, {{"0.local", addr1}});
  1263. // Mocked CreateSockets above only creates one socket.
  1264. // We schedule to send the announcement for |kNumAnnouncementsPerInterface|
  1265. // times but the second announcement is blocked by the first one in this case.
  1266. EXPECT_CALL(failing_socket_factory_, OnSendTo(expected_announcement1))
  1267. .Times(1);
  1268. failing_socket_factory_.BlockSend();
  1269. const auto name1 = CreateNameForAddress(0, addr1);
  1270. RunUntilNoTasksRemain();
  1271. const auto& addr2 = kPublicAddrs[1];
  1272. std::string expected_announcement2 =
  1273. CreateResolutionResponse(kDefaultTtl, {{"1.local", addr2}});
  1274. // The announcement for the following name should also be blocked.
  1275. const auto name2 = CreateNameForAddress(0, addr2);
  1276. EXPECT_CALL(failing_socket_factory_, OnSendTo(expected_announcement2))
  1277. .Times(0);
  1278. RunUntilNoTasksRemain();
  1279. // We later unblock sending packets. Previously scheduled announcements should
  1280. // be flushed.
  1281. EXPECT_CALL(failing_socket_factory_, OnSendTo(expected_announcement1))
  1282. .Times(kNumAnnouncementsPerInterface - 1);
  1283. EXPECT_CALL(failing_socket_factory_, OnSendTo(expected_announcement2))
  1284. .Times(kNumAnnouncementsPerInterface);
  1285. failing_socket_factory_.ResumeSend();
  1286. RunUntilNoTasksRemain();
  1287. }
  1288. } // namespace network