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