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