1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/local_discovery/privet_traffic_detector.h"
7 #include "base/location.h"
8 #include "base/metrics/histogram.h"
9 #include "base/single_thread_task_runner.h"
10 #include "base/sys_byteorder.h"
11 #include "net/base/dns_util.h"
12 #include "net/base/net_errors.h"
13 #include "net/dns/dns_protocol.h"
14 #include "net/dns/dns_response.h"
15 #include "net/dns/mdns_client.h"
16 #include "net/log/net_log.h"
17 #include "net/udp/datagram_server_socket.h"
18 #include "net/udp/udp_server_socket.h"
22 const int kMaxRestartAttempts
= 10;
23 const char kPrivetDeviceTypeDnsString
[] = "\x07_privet";
25 void GetNetworkListOnFileThread(
26 const base::Callback
<void(const net::NetworkInterfaceList
&)> callback
) {
27 DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
28 net::NetworkInterfaceList networks
;
29 if (!GetNetworkList(&networks
, net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
))
32 net::NetworkInterfaceList ip4_networks
;
33 for (size_t i
= 0; i
< networks
.size(); ++i
) {
34 net::AddressFamily address_family
=
35 net::GetAddressFamily(networks
[i
].address
);
36 if (address_family
== net::ADDRESS_FAMILY_IPV4
&&
37 networks
[i
].prefix_length
>= 24) {
38 ip4_networks
.push_back(networks
[i
]);
42 net::IPAddressNumber
localhost_prefix(4, 0);
43 localhost_prefix
[0] = 127;
44 ip4_networks
.push_back(
45 net::NetworkInterface("lo",
48 net::NetworkChangeNotifier::CONNECTION_UNKNOWN
,
51 net::IP_ADDRESS_ATTRIBUTE_NONE
));
52 content::BrowserThread::PostTask(content::BrowserThread::IO
, FROM_HERE
,
53 base::Bind(callback
, ip4_networks
));
58 namespace local_discovery
{
60 PrivetTrafficDetector::PrivetTrafficDetector(
61 net::AddressFamily address_family
,
62 const base::Closure
& on_traffic_detected
)
63 : on_traffic_detected_(on_traffic_detected
),
64 callback_runner_(base::MessageLoop::current()->task_runner()),
65 address_family_(address_family
),
67 new net::IOBufferWithSize(net::dns_protocol::kMaxMulticastSize
)),
68 restart_attempts_(kMaxRestartAttempts
),
69 weak_ptr_factory_(this) {
72 void PrivetTrafficDetector::Start() {
73 content::BrowserThread::PostTask(
74 content::BrowserThread::IO
,
76 base::Bind(&PrivetTrafficDetector::StartOnIOThread
,
77 weak_ptr_factory_
.GetWeakPtr()));
80 PrivetTrafficDetector::~PrivetTrafficDetector() {
81 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
82 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
85 void PrivetTrafficDetector::StartOnIOThread() {
86 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
87 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
91 void PrivetTrafficDetector::OnNetworkChanged(
92 net::NetworkChangeNotifier::ConnectionType type
) {
93 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
94 restart_attempts_
= kMaxRestartAttempts
;
95 if (type
!= net::NetworkChangeNotifier::CONNECTION_NONE
)
99 void PrivetTrafficDetector::ScheduleRestart() {
100 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
102 weak_ptr_factory_
.InvalidateWeakPtrs();
103 content::BrowserThread::PostDelayedTask(
104 content::BrowserThread::FILE,
106 base::Bind(&GetNetworkListOnFileThread
,
107 base::Bind(&PrivetTrafficDetector::Restart
,
108 weak_ptr_factory_
.GetWeakPtr())),
109 base::TimeDelta::FromSeconds(3));
112 void PrivetTrafficDetector::Restart(const net::NetworkInterfaceList
& networks
) {
113 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
114 networks_
= networks
;
115 if (Bind() < net::OK
|| DoLoop(0) < net::OK
) {
116 if ((restart_attempts_
--) > 0)
120 restart_attempts_
= kMaxRestartAttempts
;
124 int PrivetTrafficDetector::Bind() {
125 if (!start_time_
.is_null()) {
126 base::TimeDelta time_delta
= base::Time::Now() - start_time_
;
127 UMA_HISTOGRAM_LONG_TIMES("LocalDiscovery.DetectorRestartTime", time_delta
);
129 start_time_
= base::Time::Now();
130 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
131 socket_
.reset(new net::UDPServerSocket(NULL
, net::NetLog::Source()));
132 net::IPEndPoint multicast_addr
= net::GetMDnsIPEndPoint(address_family_
);
133 net::IPAddressNumber
address_any(multicast_addr
.address().size());
134 net::IPEndPoint
bind_endpoint(address_any
, multicast_addr
.port());
135 socket_
->AllowAddressReuse();
136 int rv
= socket_
->Listen(bind_endpoint
);
139 socket_
->SetMulticastLoopbackMode(false);
140 return socket_
->JoinGroup(multicast_addr
.address());
143 bool PrivetTrafficDetector::IsSourceAcceptable() const {
144 for (size_t i
= 0; i
< networks_
.size(); ++i
) {
145 if (net::IPNumberMatchesPrefix(recv_addr_
.address(), networks_
[i
].address
,
146 networks_
[i
].prefix_length
)) {
153 bool PrivetTrafficDetector::IsPrivetPacket(int rv
) const {
154 if (rv
<= static_cast<int>(sizeof(net::dns_protocol::Header
)) ||
155 !IsSourceAcceptable()) {
159 const char* buffer_begin
= io_buffer_
->data();
160 const char* buffer_end
= buffer_begin
+ rv
;
161 const net::dns_protocol::Header
* header
=
162 reinterpret_cast<const net::dns_protocol::Header
*>(buffer_begin
);
163 // Check if response packet.
164 if (!(header
->flags
& base::HostToNet16(net::dns_protocol::kFlagResponse
)))
166 const char* substring_begin
= kPrivetDeviceTypeDnsString
;
167 const char* substring_end
= substring_begin
+
168 arraysize(kPrivetDeviceTypeDnsString
) - 1;
169 // Check for expected substring, any Privet device must include this.
170 return std::search(buffer_begin
, buffer_end
, substring_begin
,
171 substring_end
) != buffer_end
;
174 int PrivetTrafficDetector::DoLoop(int rv
) {
175 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
177 if (IsPrivetPacket(rv
)) {
179 callback_runner_
->PostTask(FROM_HERE
, on_traffic_detected_
);
180 base::TimeDelta time_delta
= base::Time::Now() - start_time_
;
181 UMA_HISTOGRAM_LONG_TIMES("LocalDiscovery.DetectorTriggerTime",
186 rv
= socket_
->RecvFrom(
190 base::Bind(base::IgnoreResult(&PrivetTrafficDetector::DoLoop
),
191 base::Unretained(this)));
194 if (rv
!= net::ERR_IO_PENDING
)
200 } // namespace local_discovery