[content shell] implement testRunner.overridePreference
[chromium-blink-merge.git] / net / dns / dns_session.cc
blobbd4abb44ef1efffa19c6510526e69848da24561f
1 // Copyright (c) 2012 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 "net/dns/dns_session.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/rand_util.h"
10 #include "base/stl_util.h"
11 #include "base/time.h"
12 #include "net/base/ip_endpoint.h"
13 #include "net/base/net_errors.h"
14 #include "net/dns/dns_config_service.h"
15 #include "net/dns/dns_socket_pool.h"
17 namespace net {
19 DnsSession::SocketLease::SocketLease(scoped_refptr<DnsSession> session,
20 unsigned server_index,
21 scoped_ptr<DatagramClientSocket> socket)
22 : session_(session), server_index_(server_index), socket_(socket.Pass()) {}
24 DnsSession::SocketLease::~SocketLease() {
25 session_->FreeSocket(server_index_, socket_.Pass());
28 DnsSession::DnsSession(const DnsConfig& config,
29 scoped_ptr<DnsSocketPool> socket_pool,
30 const RandIntCallback& rand_int_callback,
31 NetLog* net_log)
32 : config_(config),
33 socket_pool_(socket_pool.Pass()),
34 rand_callback_(base::Bind(rand_int_callback, 0, kuint16max)),
35 net_log_(net_log),
36 server_index_(0) {
37 socket_pool_->Initialize(&config_.nameservers, net_log);
40 DnsSession::~DnsSession() {
43 int DnsSession::NextQueryId() const {
44 return rand_callback_.Run();
47 int DnsSession::NextFirstServerIndex() {
48 int index = server_index_;
49 if (config_.rotate)
50 server_index_ = (server_index_ + 1) % config_.nameservers.size();
51 return index;
54 base::TimeDelta DnsSession::NextTimeout(int attempt) {
55 // The timeout doubles every full round (each nameserver once).
56 // TODO(szym): Adapt timeout to observed RTT. http://crbug.com/110197
57 return config_.timeout * (1 << (attempt / config_.nameservers.size()));
60 // Allocate a socket, already connected to the server address.
61 scoped_ptr<DnsSession::SocketLease> DnsSession::AllocateSocket(
62 unsigned server_index,
63 const NetLog::Source& source) {
64 scoped_ptr<DatagramClientSocket> socket;
66 socket = socket_pool_->AllocateSocket(server_index);
67 if (!socket.get())
68 return scoped_ptr<SocketLease>(NULL);
70 socket->NetLog().BeginEvent(
71 NetLog::TYPE_SOCKET_IN_USE,
72 source.ToEventParametersCallback());
74 SocketLease* lease = new SocketLease(this, server_index, socket.Pass());
75 return scoped_ptr<SocketLease>(lease);
78 // Release a socket.
79 void DnsSession::FreeSocket(
80 unsigned server_index,
81 scoped_ptr<DatagramClientSocket> socket) {
82 DCHECK(socket.get());
84 socket->NetLog().EndEvent(NetLog::TYPE_SOCKET_IN_USE);
86 socket_pool_->FreeSocket(server_index, socket.Pass());
89 } // namespace net