address_sorter_posix_unittest.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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.
4
5#include "net/dns/address_sorter_posix.h"
6
7#include "base/bind.h"
8#include "base/logging.h"
9#include "net/base/net_errors.h"
10#include "net/base/net_util.h"
11#include "net/base/test_completion_callback.h"
12#include "net/socket/client_socket_factory.h"
13#include "net/udp/datagram_client_socket.h"
14#include "testing/gtest/include/gtest/gtest.h"
15
16namespace net {
17namespace {
18
19// Used to map destination address to source address.
20typedef std::map<IPAddressNumber, IPAddressNumber> AddressMapping;
21
22IPAddressNumber ParseIP(const std::string& str) {
23  IPAddressNumber addr;
24  CHECK(ParseIPLiteralToNumber(str, &addr));
25  return addr;
26}
27
28// A mock socket which binds to source address according to AddressMapping.
29class TestUDPClientSocket : public DatagramClientSocket {
30 public:
31  explicit TestUDPClientSocket(const AddressMapping* mapping)
32      : mapping_(mapping), connected_(false)  {}
33
34  virtual ~TestUDPClientSocket() {}
35
36  virtual int Read(IOBuffer*, int, const CompletionCallback&) OVERRIDE {
37    NOTIMPLEMENTED();
38    return OK;
39  }
40  virtual int Write(IOBuffer*, int, const CompletionCallback&) OVERRIDE {
41    NOTIMPLEMENTED();
42    return OK;
43  }
44  virtual bool SetReceiveBufferSize(int32) OVERRIDE {
45    return true;
46  }
47  virtual bool SetSendBufferSize(int32) OVERRIDE {
48    return true;
49  }
50
51  virtual void Close() OVERRIDE {}
52  virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
53    NOTIMPLEMENTED();
54    return OK;
55  }
56  virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
57    if (!connected_)
58      return ERR_UNEXPECTED;
59    *address = local_endpoint_;
60    return OK;
61  }
62
63  virtual int Connect(const IPEndPoint& remote) OVERRIDE {
64    if (connected_)
65      return ERR_UNEXPECTED;
66    AddressMapping::const_iterator it = mapping_->find(remote.address());
67    if (it == mapping_->end())
68      return ERR_FAILED;
69    connected_ = true;
70    local_endpoint_ = IPEndPoint(it->second, 39874 /* arbitrary port */);
71    return OK;
72  }
73
74  virtual const BoundNetLog& NetLog() const OVERRIDE {
75    return net_log_;
76  }
77
78 private:
79  BoundNetLog net_log_;
80  const AddressMapping* mapping_;
81  bool connected_;
82  IPEndPoint local_endpoint_;
83
84  DISALLOW_COPY_AND_ASSIGN(TestUDPClientSocket);
85};
86
87// Creates TestUDPClientSockets and maintains an AddressMapping.
88class TestSocketFactory : public ClientSocketFactory {
89 public:
90  TestSocketFactory() {}
91  virtual ~TestSocketFactory() {}
92
93  virtual DatagramClientSocket* CreateDatagramClientSocket(
94      DatagramSocket::BindType,
95      const RandIntCallback&,
96      NetLog*,
97      const NetLog::Source&) OVERRIDE {
98    return new TestUDPClientSocket(&mapping_);
99  }
100  virtual StreamSocket* CreateTransportClientSocket(
101      const AddressList&,
102      NetLog*,
103      const NetLog::Source&) OVERRIDE {
104    NOTIMPLEMENTED();
105    return NULL;
106  }
107  virtual SSLClientSocket* CreateSSLClientSocket(
108      ClientSocketHandle*,
109      const HostPortPair&,
110      const SSLConfig&,
111      const SSLClientSocketContext&) OVERRIDE {
112    NOTIMPLEMENTED();
113    return NULL;
114  }
115  virtual void ClearSSLSessionCache() OVERRIDE {
116    NOTIMPLEMENTED();
117  }
118
119  void AddMapping(const IPAddressNumber& dst, const IPAddressNumber& src) {
120    mapping_[dst] = src;
121  }
122
123 private:
124  AddressMapping mapping_;
125
126  DISALLOW_COPY_AND_ASSIGN(TestSocketFactory);
127};
128
129void OnSortComplete(AddressList* result_buf,
130                    const CompletionCallback& callback,
131                    bool success,
132                    const AddressList& result) {
133  EXPECT_TRUE(success);
134  if (success)
135    *result_buf = result;
136  callback.Run(OK);
137}
138
139}  // namespace
140
141class AddressSorterPosixTest : public testing::Test {
142 protected:
143  AddressSorterPosixTest() : sorter_(&socket_factory_) {}
144
145  void AddMapping(const std::string& dst, const std::string& src) {
146    socket_factory_.AddMapping(ParseIP(dst), ParseIP(src));
147  }
148
149  AddressSorterPosix::SourceAddressInfo* GetSourceInfo(
150      const std::string& addr) {
151    IPAddressNumber address = ParseIP(addr);
152    AddressSorterPosix::SourceAddressInfo* info = &sorter_.source_map_[address];
153    if (info->scope == AddressSorterPosix::SCOPE_UNDEFINED)
154      sorter_.FillPolicy(address, info);
155    return info;
156  }
157
158  // Verify that NULL-terminated |addresses| matches (-1)-terminated |order|
159  // after sorting.
160  void Verify(const char* addresses[], const int order[]) {
161    AddressList list;
162    for (const char** addr = addresses; *addr != NULL; ++addr)
163      list.push_back(IPEndPoint(ParseIP(*addr), 80));
164    for (size_t i = 0; order[i] >= 0; ++i)
165      CHECK_LT(order[i], static_cast<int>(list.size()));
166
167    AddressList result;
168    TestCompletionCallback callback;
169    sorter_.Sort(list, base::Bind(&OnSortComplete, &result,
170                                  callback.callback()));
171    callback.WaitForResult();
172
173    for (size_t i = 0; (i < result.size()) || (order[i] >= 0); ++i) {
174      IPEndPoint expected = order[i] >= 0 ? list[order[i]] : IPEndPoint();
175      IPEndPoint actual = i < result.size() ? result[i] : IPEndPoint();
176      EXPECT_TRUE(expected.address() == actual.address()) <<
177          "Address out of order at position " << i << "\n" <<
178          "  Actual: " << actual.ToStringWithoutPort() << "\n" <<
179          "Expected: " << expected.ToStringWithoutPort();
180    }
181  }
182
183  TestSocketFactory socket_factory_;
184  AddressSorterPosix sorter_;
185};
186
187// Rule 1: Avoid unusable destinations.
188TEST_F(AddressSorterPosixTest, Rule1) {
189  AddMapping("10.0.0.231", "10.0.0.1");
190  const char* addresses[] = { "::1", "10.0.0.231", "127.0.0.1", NULL };
191  const int order[] = { 1, -1 };
192  Verify(addresses, order);
193}
194
195// Rule 2: Prefer matching scope.
196TEST_F(AddressSorterPosixTest, Rule2) {
197  AddMapping("3002::1", "4000::10");      // matching global
198  AddMapping("ff32::1", "fe81::10");      // matching link-local
199  AddMapping("fec1::1", "fec1::10");      // matching node-local
200  AddMapping("3002::2", "::1");           // global vs. link-local
201  AddMapping("fec1::2", "fe81::10");      // site-local vs. link-local
202  AddMapping("8.0.0.1", "169.254.0.10");  // global vs. link-local
203  // In all three cases, matching scope is preferred.
204  const int order[] = { 1, 0, -1 };
205  const char* addresses1[] = { "3002::2", "3002::1", NULL };
206  Verify(addresses1, order);
207  const char* addresses2[] = { "fec1::2", "ff32::1", NULL };
208  Verify(addresses2, order);
209  const char* addresses3[] = { "8.0.0.1", "fec1::1", NULL };
210  Verify(addresses3, order);
211}
212
213// Rule 3: Avoid deprecated addresses.
214TEST_F(AddressSorterPosixTest, Rule3) {
215  // Matching scope.
216  AddMapping("3002::1", "4000::10");
217  GetSourceInfo("4000::10")->deprecated = true;
218  AddMapping("3002::2", "4000::20");
219  const char* addresses[] = { "3002::1", "3002::2", NULL };
220  const int order[] = { 1, 0, -1 };
221  Verify(addresses, order);
222}
223
224// Rule 4: Prefer home addresses.
225TEST_F(AddressSorterPosixTest, Rule4) {
226  AddMapping("3002::1", "4000::10");
227  AddMapping("3002::2", "4000::20");
228  GetSourceInfo("4000::20")->home = true;
229  const char* addresses[] = { "3002::1", "3002::2", NULL };
230  const int order[] = { 1, 0, -1 };
231  Verify(addresses, order);
232}
233
234// Rule 5: Prefer matching label.
235TEST_F(AddressSorterPosixTest, Rule5) {
236  AddMapping("::1", "::1");                       // matching loopback
237  AddMapping("::ffff:1234:1", "::ffff:1234:10");  // matching IPv4-mapped
238  AddMapping("2001::1", "::ffff:1234:10");        // Teredo vs. IPv4-mapped
239  AddMapping("2002::1", "2001::10");              // 6to4 vs. Teredo
240  const int order[] = { 1, 0, -1 };
241  {
242    const char* addresses[] = { "2001::1", "::1", NULL };
243    Verify(addresses, order);
244  }
245  {
246    const char* addresses[] = { "2002::1", "::ffff:1234:1", NULL };
247    Verify(addresses, order);
248  }
249}
250
251// Rule 6: Prefer higher precedence.
252TEST_F(AddressSorterPosixTest, Rule6) {
253  AddMapping("::1", "::1");                       // loopback
254  AddMapping("ff32::1", "fe81::10");              // multicast
255  AddMapping("::ffff:1234:1", "::ffff:1234:10");  // IPv4-mapped
256  AddMapping("2001::1", "2001::10");              // Teredo
257  const char* addresses[] = { "2001::1", "::ffff:1234:1", "ff32::1", "::1",
258                              NULL };
259  const int order[] = { 3, 2, 1, 0, -1 };
260  Verify(addresses, order);
261}
262
263// Rule 7: Prefer native transport.
264TEST_F(AddressSorterPosixTest, Rule7) {
265  AddMapping("3002::1", "4000::10");
266  AddMapping("3002::2", "4000::20");
267  GetSourceInfo("4000::20")->native = true;
268  const char* addresses[] = { "3002::1", "3002::2", NULL };
269  const int order[] = { 1, 0, -1 };
270  Verify(addresses, order);
271}
272
273// Rule 8: Prefer smaller scope.
274TEST_F(AddressSorterPosixTest, Rule8) {
275  // Matching scope. Should precede the others by Rule 2.
276  AddMapping("fe81::1", "fe81::10");  // link-local
277  AddMapping("3000::1", "4000::10");  // global
278  // Mismatched scope.
279  AddMapping("ff32::1", "4000::10");  // link-local
280  AddMapping("ff35::1", "4000::10");  // site-local
281  AddMapping("ff38::1", "4000::10");  // org-local
282  const char* addresses[] = { "ff38::1", "3000::1", "ff35::1", "ff32::1",
283                              "fe81::1", NULL };
284  const int order[] = { 4, 1, 3, 2, 0, -1 };
285  Verify(addresses, order);
286}
287
288// Rule 9: Use longest matching prefix.
289TEST_F(AddressSorterPosixTest, Rule9) {
290  AddMapping("3000::1", "3000:ffff::10");  // 16 bit match
291  GetSourceInfo("3000:ffff::10")->prefix_length = 16;
292  AddMapping("4000::1", "4000::10");       // 123 bit match, limited to 15
293  GetSourceInfo("4000::10")->prefix_length = 15;
294  AddMapping("4002::1", "4000::10");       // 14 bit match
295  AddMapping("4080::1", "4000::10");       // 8 bit match
296  const char* addresses[] = { "4080::1", "4002::1", "4000::1", "3000::1",
297                              NULL };
298  const int order[] = { 3, 2, 1, 0, -1 };
299  Verify(addresses, order);
300}
301
302// Rule 10: Leave the order unchanged.
303TEST_F(AddressSorterPosixTest, Rule10) {
304  AddMapping("4000::1", "4000::10");
305  AddMapping("4000::2", "4000::10");
306  AddMapping("4000::3", "4000::10");
307  const char* addresses[] = { "4000::1", "4000::2", "4000::3", NULL };
308  const int order[] = { 0, 1, 2, -1 };
309  Verify(addresses, order);
310}
311
312TEST_F(AddressSorterPosixTest, MultipleRules) {
313  AddMapping("::1", "::1");           // loopback
314  AddMapping("ff32::1", "fe81::10");  // link-local multicast
315  AddMapping("ff3e::1", "4000::10");  // global multicast
316  AddMapping("4000::1", "4000::10");  // global unicast
317  AddMapping("ff32::2", "fe81::20");  // deprecated link-local multicast
318  GetSourceInfo("fe81::20")->deprecated = true;
319  const char* addresses[] = { "ff3e::1", "ff32::2", "4000::1", "ff32::1", "::1",
320                              "8.0.0.1", NULL };
321  const int order[] = { 4, 3, 0, 2, 1, -1 };
322  Verify(addresses, order);
323}
324
325}  // namespace net
326