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/metrics/histogram.h"
8 #include "base/sys_byteorder.h"
9 #include "net/base/dns_util.h"
10 #include "net/base/net_errors.h"
11 #include "net/base/net_log.h"
12 #include "net/dns/dns_protocol.h"
13 #include "net/dns/dns_response.h"
14 #include "net/dns/mdns_client.h"
15 #include "net/udp/datagram_server_socket.h"
16 #include "net/udp/udp_server_socket.h"
20 const int kMaxRestartAttempts
= 10;
21 const char kPrivetDeviceTypeDnsString
[] = "\x07_privet";
23 void GetNetworkListOnFileThread(
24 const base::Callback
<void(const net::NetworkInterfaceList
&)> callback
) {
25 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
26 net::NetworkInterfaceList networks
;
27 if (!GetNetworkList(&networks
, net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
))
30 net::NetworkInterfaceList ip4_networks
;
31 for (size_t i
= 0; i
< networks
.size(); ++i
) {
32 net::AddressFamily address_family
=
33 net::GetAddressFamily(networks
[i
].address
);
34 if (address_family
== net::ADDRESS_FAMILY_IPV4
&&
35 networks
[i
].network_prefix
>= 24) {
36 ip4_networks
.push_back(networks
[i
]);
40 net::IPAddressNumber
localhost_prefix(4, 0);
41 localhost_prefix
[0] = 127;
42 ip4_networks
.push_back(net::NetworkInterface("lo", 0, localhost_prefix
, 8));
43 content::BrowserThread::PostTask(content::BrowserThread::IO
, FROM_HERE
,
44 base::Bind(callback
, ip4_networks
));
49 namespace local_discovery
{
51 PrivetTrafficDetector::PrivetTrafficDetector(
52 net::AddressFamily address_family
,
53 const base::Closure
& on_traffic_detected
)
54 : on_traffic_detected_(on_traffic_detected
),
55 callback_runner_(base::MessageLoop::current()->message_loop_proxy()),
56 address_family_(address_family
),
58 new net::IOBufferWithSize(net::dns_protocol::kMaxMulticastSize
)),
59 restart_attempts_(kMaxRestartAttempts
),
60 weak_ptr_factory_(this) {
63 void PrivetTrafficDetector::Start() {
64 content::BrowserThread::PostTask(
65 content::BrowserThread::IO
,
67 base::Bind(&PrivetTrafficDetector::StartOnIOThread
,
68 weak_ptr_factory_
.GetWeakPtr()));
71 PrivetTrafficDetector::~PrivetTrafficDetector() {
72 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
73 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
76 void PrivetTrafficDetector::StartOnIOThread() {
77 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
78 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
82 void PrivetTrafficDetector::OnNetworkChanged(
83 net::NetworkChangeNotifier::ConnectionType type
) {
84 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
85 restart_attempts_
= kMaxRestartAttempts
;
86 if (type
!= net::NetworkChangeNotifier::CONNECTION_NONE
)
90 void PrivetTrafficDetector::ScheduleRestart() {
91 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
93 weak_ptr_factory_
.InvalidateWeakPtrs();
94 content::BrowserThread::PostDelayedTask(
95 content::BrowserThread::FILE,
97 base::Bind(&GetNetworkListOnFileThread
,
98 base::Bind(&PrivetTrafficDetector::Restart
,
99 weak_ptr_factory_
.GetWeakPtr())),
100 base::TimeDelta::FromSeconds(3));
103 void PrivetTrafficDetector::Restart(const net::NetworkInterfaceList
& networks
) {
104 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
105 networks_
= networks
;
106 if (Bind() < net::OK
|| DoLoop(0) < net::OK
) {
107 if ((restart_attempts_
--) > 0)
111 restart_attempts_
= kMaxRestartAttempts
;
115 int PrivetTrafficDetector::Bind() {
116 if (!start_time_
.is_null()) {
117 base::TimeDelta time_delta
= base::Time::Now() - start_time_
;
118 UMA_HISTOGRAM_LONG_TIMES("LocalDiscovery.DetectorRestartTime", time_delta
);
120 start_time_
= base::Time::Now();
121 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
122 socket_
.reset(new net::UDPServerSocket(NULL
, net::NetLog::Source()));
123 net::IPEndPoint multicast_addr
= net::GetMDnsIPEndPoint(address_family_
);
124 net::IPAddressNumber
address_any(multicast_addr
.address().size());
125 net::IPEndPoint
bind_endpoint(address_any
, multicast_addr
.port());
126 socket_
->AllowAddressReuse();
127 int rv
= socket_
->Listen(bind_endpoint
);
130 socket_
->SetMulticastLoopbackMode(false);
131 return socket_
->JoinGroup(multicast_addr
.address());
134 bool PrivetTrafficDetector::IsSourceAcceptable() const {
135 for (size_t i
= 0; i
< networks_
.size(); ++i
) {
136 if (net::IPNumberMatchesPrefix(recv_addr_
.address(), networks_
[i
].address
,
137 networks_
[i
].network_prefix
)) {
144 bool PrivetTrafficDetector::IsPrivetPacket(int rv
) const {
145 if (rv
<= static_cast<int>(sizeof(net::dns_protocol::Header
)) ||
146 !IsSourceAcceptable()) {
150 const char* buffer_begin
= io_buffer_
->data();
151 const char* buffer_end
= buffer_begin
+ rv
;
152 const net::dns_protocol::Header
* header
=
153 reinterpret_cast<const net::dns_protocol::Header
*>(buffer_begin
);
154 // Check if response packet.
155 if (!(header
->flags
& base::HostToNet16(net::dns_protocol::kFlagResponse
)))
157 const char* substring_begin
= kPrivetDeviceTypeDnsString
;
158 const char* substring_end
= substring_begin
+
159 arraysize(kPrivetDeviceTypeDnsString
) - 1;
160 // Check for expected substring, any Privet device must include this.
161 return std::search(buffer_begin
, buffer_end
, substring_begin
,
162 substring_end
) != buffer_end
;
165 int PrivetTrafficDetector::DoLoop(int rv
) {
166 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO
));
168 if (IsPrivetPacket(rv
)) {
170 callback_runner_
->PostTask(FROM_HERE
, on_traffic_detected_
);
171 base::TimeDelta time_delta
= base::Time::Now() - start_time_
;
172 UMA_HISTOGRAM_LONG_TIMES("LocalDiscovery.DetectorTriggerTime",
177 rv
= socket_
->RecvFrom(
181 base::Bind(base::IgnoreResult(&PrivetTrafficDetector::DoLoop
),
182 base::Unretained(this)));
185 if (rv
!= net::ERR_IO_PENDING
)
191 } // namespace local_discovery