File: udp_socket_unittest.cc

package info (click to toggle)
chromium 73.0.3683.75-1~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,792,156 kB
  • sloc: cpp: 13,473,466; ansic: 1,577,080; python: 898,539; javascript: 655,737; xml: 341,883; asm: 306,070; java: 289,969; perl: 80,911; objc: 67,198; sh: 43,184; cs: 27,853; makefile: 12,092; php: 11,064; yacc: 10,373; tcl: 8,875; ruby: 3,941; lex: 1,800; pascal: 1,473; lisp: 812; awk: 41; jsp: 39; sed: 19; sql: 3
file content (208 lines) | stat: -rw-r--r-- 7,679 bytes parent folder | download
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
// Copyright (c) 2012 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 <stddef.h>
#include <stdint.h>

#include <memory>
#include <string>

#include "base/location.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "content/public/browser/storage_partition.h"
#include "extensions/browser/api/socket/udp_socket.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_address.h"
#include "net/base/test_completion_callback.h"
#include "services/network/network_context.h"
#include "services/network/public/mojom/udp_socket.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

class UDPSocketUnitTest : public extensions::ExtensionServiceTestBase {
 protected:
  // extensions::ExtensionServiceTestBase:
  void SetUp() override { InitializeEmptyExtensionService(); }

  std::unique_ptr<UDPSocket> CreateSocket() {
    network::mojom::NetworkContext* network_context =
        content::BrowserContext::GetDefaultStoragePartition(profile())
            ->GetNetworkContext();
    network::mojom::UDPSocketPtrInfo socket;
    network::mojom::UDPSocketReceiverPtr receiver_ptr;
    network::mojom::UDPSocketReceiverRequest receiver_request =
        mojo::MakeRequest(&receiver_ptr);
    network_context->CreateUDPSocket(mojo::MakeRequest(&socket),
                                     std::move(receiver_ptr));
    return std::make_unique<UDPSocket>(
        std::move(socket), std::move(receiver_request), "abcdefghijklmnopqrst");
  }
};

static void OnConnected(int result) {
  EXPECT_EQ(0, result);
}

static void OnCompleted(int bytes_read,
                        scoped_refptr<net::IOBuffer> io_buffer,
                        bool socket_destroying,
                        const std::string& address,
                        uint16_t port) {
  // Do nothing; don't care.
}

static const char kTestMessage[] = "$$TESTMESSAGETESTMESSAGETESTMESSAGETEST$$";
static const int kTestMessageLength = base::size(kTestMessage);

net::AddressList CreateAddressList(const char* address_string, int port) {
  net::IPAddress ip;
  EXPECT_TRUE(ip.AssignFromIPLiteral(address_string));
  return net::AddressList::CreateFromIPAddress(ip, port);
}

static void OnSendCompleted(int result) {
  EXPECT_EQ(kTestMessageLength, result);
}

TEST_F(UDPSocketUnitTest, TestUDPSocketRecvFrom) {
  std::unique_ptr<UDPSocket> socket = CreateSocket();

  // Confirm that we can call two RecvFroms in quick succession without
  // triggering crbug.com/146606.
  socket->Connect(CreateAddressList("127.0.0.1", 40000),
                  base::BindRepeating(&OnConnected));
  socket->RecvFrom(4096, base::BindRepeating(&OnCompleted));
  socket->RecvFrom(4096, base::BindRepeating(&OnCompleted));
}

TEST_F(UDPSocketUnitTest, TestUDPMulticastJoinGroup) {
  const char kGroup[] = "237.132.100.17";
  std::unique_ptr<UDPSocket> src = CreateSocket();
  std::unique_ptr<UDPSocket> dest = CreateSocket();

  {
    net::TestCompletionCallback callback;
    dest->Bind("0.0.0.0", 13333, callback.callback());
    EXPECT_EQ(net::OK, callback.WaitForResult());
  }
  {
    net::TestCompletionCallback callback;
    dest->JoinGroup(kGroup, callback.callback());
    EXPECT_EQ(net::OK, callback.WaitForResult());
  }
  std::vector<std::string> groups = dest->GetJoinedGroups();
  EXPECT_EQ(static_cast<size_t>(1), groups.size());
  EXPECT_EQ(kGroup, *groups.begin());
  {
    net::TestCompletionCallback callback;
    dest->LeaveGroup("237.132.100.13", callback.callback());
    EXPECT_NE(net::OK, callback.WaitForResult());
  }
  {
    net::TestCompletionCallback callback;
    dest->LeaveGroup(kGroup, callback.callback());
    EXPECT_EQ(net::OK, callback.WaitForResult());
  }
  groups = dest->GetJoinedGroups();
  EXPECT_EQ(static_cast<size_t>(0), groups.size());
}

TEST_F(UDPSocketUnitTest, TestUDPMulticastTimeToLive) {
  const char kGroup[] = "237.132.100.17";
  std::unique_ptr<UDPSocket> socket = CreateSocket();

  EXPECT_NE(0, socket->SetMulticastTimeToLive(-1));  // Negative TTL shall fail.
  EXPECT_EQ(0, socket->SetMulticastTimeToLive(3));
  socket->Connect(CreateAddressList(kGroup, 13333),
                  base::BindRepeating(&OnConnected));
}

TEST_F(UDPSocketUnitTest, TestUDPMulticastLoopbackMode) {
  const char kGroup[] = "237.132.100.17";
  std::unique_ptr<UDPSocket> socket = CreateSocket();

  EXPECT_EQ(0, socket->SetMulticastLoopbackMode(false));
  socket->Connect(CreateAddressList(kGroup, 13333),
                  base::BindRepeating(&OnConnected));
}

// Send a test multicast packet every second.
// Once the target socket received the packet, the message loop will exit.
static void SendMulticastPacket(const base::Closure& quit_run_loop,
                                UDPSocket* src,
                                int result) {
  if (result == 0) {
    scoped_refptr<net::IOBuffer> data =
        base::MakeRefCounted<net::WrappedIOBuffer>(kTestMessage);
    src->Write(data, kTestMessageLength, base::BindRepeating(&OnSendCompleted));
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&SendMulticastPacket, quit_run_loop, src, result),
        base::TimeDelta::FromSeconds(1));
  } else {
    quit_run_loop.Run();
    FAIL() << "Failed to connect to multicast address. Error code: " << result;
  }
}

static void OnMulticastReadCompleted(const base::Closure& quit_run_loop,
                                     bool* packet_received,
                                     int count,
                                     scoped_refptr<net::IOBuffer> io_buffer,
                                     bool socket_destroying,
                                     const std::string& ip,
                                     uint16_t port) {
  EXPECT_EQ(kTestMessageLength, count);
  EXPECT_EQ(0, strncmp(io_buffer->data(), kTestMessage, kTestMessageLength));
  *packet_received = true;
  quit_run_loop.Run();
}

TEST_F(UDPSocketUnitTest, TestUDPMulticastRecv) {
  const int kPort = 9999;
  const char kGroup[] = "237.132.100.17";
  bool packet_received = false;
  std::unique_ptr<UDPSocket> src = CreateSocket();
  std::unique_ptr<UDPSocket> dest = CreateSocket();

  // Receiver
  {
    net::TestCompletionCallback callback;
    dest->Bind("0.0.0.0", kPort, callback.callback());
    EXPECT_EQ(net::OK, callback.WaitForResult());
  }
  {
    net::TestCompletionCallback callback;
    dest->JoinGroup(kGroup, callback.callback());
    EXPECT_EQ(net::OK, callback.WaitForResult());
  }
  base::RunLoop run_loop;
  // |dest| is used with Bind(), so use RecvFrom() instead of Read().
  dest->RecvFrom(1024,
                 base::BindRepeating(&OnMulticastReadCompleted,
                                     run_loop.QuitClosure(), &packet_received));

  // Sender
  EXPECT_EQ(0, src->SetMulticastTimeToLive(0));
  src->Connect(CreateAddressList(kGroup, kPort),
               base::BindRepeating(&SendMulticastPacket, run_loop.QuitClosure(),
                                   src.get()));

  // If not received within the test action timeout, quit the message loop.
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());

  run_loop.Run();

  EXPECT_TRUE(packet_received) << "Failed to receive from multicast address";
}

}  // namespace extensions