1 // Copyright 2013 The Chromium Authors
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 "net/dns/mdns_client.h"
6
7 #include "net/base/address_family.h"
8 #include "net/base/net_errors.h"
9 #include "net/base/network_interfaces.h"
10 #include "net/dns/mdns_client_impl.h"
11 #include "net/dns/public/util.h"
12 #include "net/log/net_log.h"
13 #include "net/log/net_log_source.h"
14
15 namespace net {
16
17 namespace {
18
Bind(AddressFamily address_family,uint32_t interface_index,DatagramServerSocket * socket)19 int Bind(AddressFamily address_family,
20 uint32_t interface_index,
21 DatagramServerSocket* socket) {
22 socket->AllowAddressSharingForMulticast();
23 socket->SetMulticastInterface(interface_index);
24
25 int rv = socket->Listen(dns_util::GetMdnsReceiveEndPoint(address_family));
26 if (rv < OK)
27 return rv;
28
29 return socket->JoinGroup(
30 dns_util::GetMdnsGroupEndPoint(address_family).address());
31 }
32
33 } // namespace
34
35 const base::TimeDelta MDnsTransaction::kTransactionTimeout = base::Seconds(3);
36
37 // static
CreateDefault()38 std::unique_ptr<MDnsSocketFactory> MDnsSocketFactory::CreateDefault() {
39 return std::make_unique<MDnsSocketFactoryImpl>();
40 }
41
42 // static
CreateDefault()43 std::unique_ptr<MDnsClient> MDnsClient::CreateDefault() {
44 return std::make_unique<MDnsClientImpl>();
45 }
46
GetMDnsInterfacesToBind()47 InterfaceIndexFamilyList GetMDnsInterfacesToBind() {
48 NetworkInterfaceList network_list;
49 InterfaceIndexFamilyList interfaces;
50 if (!GetNetworkList(&network_list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES))
51 return interfaces;
52 for (const auto& network_interface : network_list) {
53 AddressFamily family = GetAddressFamily(network_interface.address);
54 if (family == ADDRESS_FAMILY_IPV4 || family == ADDRESS_FAMILY_IPV6) {
55 interfaces.emplace_back(network_interface.interface_index, family);
56 }
57 }
58 std::sort(interfaces.begin(), interfaces.end());
59 // Interfaces could have multiple addresses. Filter out duplicate entries.
60 interfaces.erase(std::unique(interfaces.begin(), interfaces.end()),
61 interfaces.end());
62 return interfaces;
63 }
64
CreateAndBindMDnsSocket(AddressFamily address_family,uint32_t interface_index,NetLog * net_log)65 std::unique_ptr<DatagramServerSocket> CreateAndBindMDnsSocket(
66 AddressFamily address_family,
67 uint32_t interface_index,
68 NetLog* net_log) {
69 auto socket = std::make_unique<UDPServerSocket>(net_log, NetLogSource());
70
71 int rv = Bind(address_family, interface_index, socket.get());
72 if (rv != OK) {
73 socket.reset();
74 VLOG(1) << "MDNS bind failed, address_family=" << address_family
75 << ", error=" << rv;
76 }
77 return socket;
78 }
79
80 } // namespace net
81