1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/local_discovery/service_discovery_client_mdns.h"
#include "base/memory/scoped_vector.h"
#include "base/metrics/histogram.h"
#include "chrome/common/local_discovery/service_discovery_client_impl.h"
#include "content/public/browser/browser_thread.h"
#include "net/dns/mdns_client.h"
#include "net/udp/datagram_server_socket.h"
namespace local_discovery {
using content::BrowserThread;
// Base class for objects returned by ServiceDiscoveryClient implementation.
// Handles interaction of client code on UI thread end net code on mdns thread.
class ServiceDiscoveryClientMdns::Proxy {
public:
typedef base::WeakPtr<Proxy> WeakPtr;
explicit Proxy(ServiceDiscoveryClientMdns* client)
: client_(client),
weak_ptr_factory_(this) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
client_->proxies_.AddObserver(this);
}
virtual ~Proxy() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
client_->proxies_.RemoveObserver(this);
}
// Returns true if object is not yet shutdown.
virtual bool IsValid() = 0;
// Notifies proxies that mDNS layer is going to be destroyed.
virtual void OnMdnsDestroy() = 0;
// Notifies proxies that new mDNS instance is ready.
virtual void OnNewMdnsReady() {
DCHECK(!client_->need_dalay_mdns_tasks_);
if (IsValid()) {
for (size_t i = 0; i < delayed_tasks_.size(); ++i)
client_->mdns_runner_->PostTask(FROM_HERE, delayed_tasks_[i]);
}
delayed_tasks_.clear();
}
// Runs callback using this method to abort callback if instance of |Proxy|
// is deleted.
void RunCallback(const base::Closure& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
callback.Run();
}
protected:
void PostToMdnsThread(const base::Closure& task) {
DCHECK(IsValid());
// The first task on IO thread for each |mdns_| instance must be |InitMdns|.
// |OnInterfaceListReady| could be delayed by |GetMDnsInterfacesToBind|
// running on FILE thread, so |PostToMdnsThread| could be called to post
// task for |mdns_| that is not initialized yet.
if (!client_->need_dalay_mdns_tasks_) {
client_->mdns_runner_->PostTask(FROM_HERE, task);
return;
}
delayed_tasks_.push_back(task);
}
static bool PostToUIThread(const base::Closure& task) {
return BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task);
}
ServiceDiscoveryClient* client() {
return client_->client_.get();
}
WeakPtr GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
template<class T>
void DeleteOnMdnsThread(T* t) {
if (!t)
return;
if (!client_->mdns_runner_->DeleteSoon(FROM_HERE, t))
delete t;
}
private:
scoped_refptr<ServiceDiscoveryClientMdns> client_;
// Delayed |mdns_runner_| tasks.
std::vector<base::Closure> delayed_tasks_;
base::WeakPtrFactory<Proxy> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(Proxy);
};
namespace {
const int kMaxRestartAttempts = 10;
const int kRestartDelayOnNetworkChangeSeconds = 3;
typedef base::Callback<void(bool)> MdnsInitCallback;
class SocketFactory : public net::MDnsSocketFactory {
public:
explicit SocketFactory(const net::InterfaceIndexFamilyList& interfaces)
: interfaces_(interfaces) {}
// net::MDnsSocketFactory implementation:
void CreateSockets(
ScopedVector<net::DatagramServerSocket>* sockets) override {
for (size_t i = 0; i < interfaces_.size(); ++i) {
DCHECK(interfaces_[i].second == net::ADDRESS_FAMILY_IPV4 ||
interfaces_[i].second == net::ADDRESS_FAMILY_IPV6);
scoped_ptr<net::DatagramServerSocket> socket(
CreateAndBindMDnsSocket(interfaces_[i].second, interfaces_[i].first));
if (socket)
sockets->push_back(socket.release());
}
}
private:
net::InterfaceIndexFamilyList interfaces_;
};
void InitMdns(const MdnsInitCallback& on_initialized,
const net::InterfaceIndexFamilyList& interfaces,
net::MDnsClient* mdns) {
SocketFactory socket_factory(interfaces);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(on_initialized,
mdns->StartListening(&socket_factory)));
}
template<class T>
class ProxyBase : public ServiceDiscoveryClientMdns::Proxy, public T {
public:
typedef ProxyBase<T> Base;
explicit ProxyBase(ServiceDiscoveryClientMdns* client)
: Proxy(client) {
}
virtual ~ProxyBase() {
DeleteOnMdnsThread(implementation_.release());
}
virtual bool IsValid() override {
return !!implementation();
}
virtual void OnMdnsDestroy() override {
DeleteOnMdnsThread(implementation_.release());
};
protected:
void set_implementation(scoped_ptr<T> implementation) {
implementation_ = implementation.Pass();
}
T* implementation() const {
return implementation_.get();
}
private:
scoped_ptr<T> implementation_;
DISALLOW_COPY_AND_ASSIGN(ProxyBase);
};
class ServiceWatcherProxy : public ProxyBase<ServiceWatcher> {
public:
ServiceWatcherProxy(ServiceDiscoveryClientMdns* client_mdns,
const std::string& service_type,
const ServiceWatcher::UpdatedCallback& callback)
: ProxyBase(client_mdns),
service_type_(service_type),
callback_(callback) {
// It's safe to call |CreateServiceWatcher| on UI thread, because
// |MDnsClient| is not used there. It's simplify implementation.
set_implementation(client()->CreateServiceWatcher(
service_type,
base::Bind(&ServiceWatcherProxy::OnCallback, GetWeakPtr(), callback)));
}
// ServiceWatcher methods.
void Start() override {
if (implementation()) {
PostToMdnsThread(base::Bind(&ServiceWatcher::Start,
base::Unretained(implementation())));
}
}
void DiscoverNewServices(bool force_update) override {
if (implementation()) {
PostToMdnsThread(base::Bind(&ServiceWatcher::DiscoverNewServices,
base::Unretained(implementation()),
force_update));
}
}
void SetActivelyRefreshServices(bool actively_refresh_services) override {
if (implementation()) {
PostToMdnsThread(base::Bind(&ServiceWatcher::SetActivelyRefreshServices,
base::Unretained(implementation()),
actively_refresh_services));
}
}
std::string GetServiceType() const override { return service_type_; }
void OnNewMdnsReady() override {
ProxyBase<ServiceWatcher>::OnNewMdnsReady();
if (!implementation())
callback_.Run(ServiceWatcher::UPDATE_INVALIDATED, "");
}
private:
static void OnCallback(const WeakPtr& proxy,
const ServiceWatcher::UpdatedCallback& callback,
UpdateType a1,
const std::string& a2) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
PostToUIThread(base::Bind(&Base::RunCallback, proxy,
base::Bind(callback, a1, a2)));
}
std::string service_type_;
ServiceWatcher::UpdatedCallback callback_;
DISALLOW_COPY_AND_ASSIGN(ServiceWatcherProxy);
};
class ServiceResolverProxy : public ProxyBase<ServiceResolver> {
public:
ServiceResolverProxy(ServiceDiscoveryClientMdns* client_mdns,
const std::string& service_name,
const ServiceResolver::ResolveCompleteCallback& callback)
: ProxyBase(client_mdns),
service_name_(service_name) {
// It's safe to call |CreateServiceResolver| on UI thread, because
// |MDnsClient| is not used there. It's simplify implementation.
set_implementation(client()->CreateServiceResolver(
service_name,
base::Bind(&ServiceResolverProxy::OnCallback, GetWeakPtr(), callback)));
}
// ServiceResolver methods.
void StartResolving() override {
if (implementation()) {
PostToMdnsThread(base::Bind(&ServiceResolver::StartResolving,
base::Unretained(implementation())));
}
};
std::string GetName() const override { return service_name_; }
private:
static void OnCallback(
const WeakPtr& proxy,
const ServiceResolver::ResolveCompleteCallback& callback,
RequestStatus a1,
const ServiceDescription& a2) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
PostToUIThread(base::Bind(&Base::RunCallback, proxy,
base::Bind(callback, a1, a2)));
}
std::string service_name_;
DISALLOW_COPY_AND_ASSIGN(ServiceResolverProxy);
};
class LocalDomainResolverProxy : public ProxyBase<LocalDomainResolver> {
public:
LocalDomainResolverProxy(
ServiceDiscoveryClientMdns* client_mdns,
const std::string& domain,
net::AddressFamily address_family,
const LocalDomainResolver::IPAddressCallback& callback)
: ProxyBase(client_mdns) {
// It's safe to call |CreateLocalDomainResolver| on UI thread, because
// |MDnsClient| is not used there. It's simplify implementation.
set_implementation(client()->CreateLocalDomainResolver(
domain,
address_family,
base::Bind(
&LocalDomainResolverProxy::OnCallback, GetWeakPtr(), callback)));
}
// LocalDomainResolver methods.
void Start() override {
if (implementation()) {
PostToMdnsThread(base::Bind(&LocalDomainResolver::Start,
base::Unretained(implementation())));
}
};
private:
static void OnCallback(const WeakPtr& proxy,
const LocalDomainResolver::IPAddressCallback& callback,
bool a1,
const net::IPAddressNumber& a2,
const net::IPAddressNumber& a3) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
PostToUIThread(base::Bind(&Base::RunCallback, proxy,
base::Bind(callback, a1, a2, a3)));
}
DISALLOW_COPY_AND_ASSIGN(LocalDomainResolverProxy);
};
} // namespace
ServiceDiscoveryClientMdns::ServiceDiscoveryClientMdns()
: mdns_runner_(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)),
restart_attempts_(0),
need_dalay_mdns_tasks_(true),
weak_ptr_factory_(this) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
StartNewClient();
}
scoped_ptr<ServiceWatcher> ServiceDiscoveryClientMdns::CreateServiceWatcher(
const std::string& service_type,
const ServiceWatcher::UpdatedCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return scoped_ptr<ServiceWatcher>(
new ServiceWatcherProxy(this, service_type, callback));
}
scoped_ptr<ServiceResolver> ServiceDiscoveryClientMdns::CreateServiceResolver(
const std::string& service_name,
const ServiceResolver::ResolveCompleteCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return scoped_ptr<ServiceResolver>(
new ServiceResolverProxy(this, service_name, callback));
}
scoped_ptr<LocalDomainResolver>
ServiceDiscoveryClientMdns::CreateLocalDomainResolver(
const std::string& domain,
net::AddressFamily address_family,
const LocalDomainResolver::IPAddressCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return scoped_ptr<LocalDomainResolver>(
new LocalDomainResolverProxy(this, domain, address_family, callback));
}
ServiceDiscoveryClientMdns::~ServiceDiscoveryClientMdns() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
DestroyMdns();
}
void ServiceDiscoveryClientMdns::OnNetworkChanged(
net::NetworkChangeNotifier::ConnectionType type) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Only network changes resets counter.
restart_attempts_ = 0;
ScheduleStartNewClient();
}
void ServiceDiscoveryClientMdns::ScheduleStartNewClient() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
OnBeforeMdnsDestroy();
if (restart_attempts_ < kMaxRestartAttempts) {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ServiceDiscoveryClientMdns::StartNewClient,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(
kRestartDelayOnNetworkChangeSeconds * (1 << restart_attempts_)));
} else {
ReportSuccess();
}
}
void ServiceDiscoveryClientMdns::StartNewClient() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
++restart_attempts_;
DestroyMdns();
mdns_.reset(net::MDnsClient::CreateDefault().release());
client_.reset(new ServiceDiscoveryClientImpl(mdns_.get()));
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&net::GetMDnsInterfacesToBind),
base::Bind(&ServiceDiscoveryClientMdns::OnInterfaceListReady,
weak_ptr_factory_.GetWeakPtr()));
}
void ServiceDiscoveryClientMdns::OnInterfaceListReady(
const net::InterfaceIndexFamilyList& interfaces) {
mdns_runner_->PostTask(
FROM_HERE,
base::Bind(&InitMdns,
base::Bind(&ServiceDiscoveryClientMdns::OnMdnsInitialized,
weak_ptr_factory_.GetWeakPtr()),
interfaces,
base::Unretained(mdns_.get())));
}
void ServiceDiscoveryClientMdns::OnMdnsInitialized(bool success) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!success) {
ScheduleStartNewClient();
return;
}
ReportSuccess();
// Initialization is done, no need to delay tasks.
need_dalay_mdns_tasks_ = false;
FOR_EACH_OBSERVER(Proxy, proxies_, OnNewMdnsReady());
}
void ServiceDiscoveryClientMdns::ReportSuccess() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
UMA_HISTOGRAM_COUNTS_100("LocalDiscovery.ClientRestartAttempts",
restart_attempts_);
}
void ServiceDiscoveryClientMdns::OnBeforeMdnsDestroy() {
need_dalay_mdns_tasks_ = true;
weak_ptr_factory_.InvalidateWeakPtrs();
FOR_EACH_OBSERVER(Proxy, proxies_, OnMdnsDestroy());
}
void ServiceDiscoveryClientMdns::DestroyMdns() {
OnBeforeMdnsDestroy();
// After calling |Proxy::OnMdnsDestroy| all references to client_ and mdns_
// should be destroyed.
if (client_)
mdns_runner_->DeleteSoon(FROM_HERE, client_.release());
if (mdns_)
mdns_runner_->DeleteSoon(FROM_HERE, mdns_.release());
}
} // namespace local_discovery
|