1 /*
2 * Copyright 2006 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include <math.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <time.h>
16 #if defined(WEBRTC_POSIX)
17 #include <netinet/in.h>
18 #endif
19
20 #include <algorithm>
21 #include <memory>
22 #include <utility>
23
24 #include "absl/memory/memory.h"
25 #include "rtc_base/arraysize.h"
26 #include "rtc_base/async_packet_socket.h"
27 #include "rtc_base/async_socket.h"
28 #include "rtc_base/async_udp_socket.h"
29 #include "rtc_base/fake_clock.h"
30 #include "rtc_base/gunit.h"
31 #include "rtc_base/ip_address.h"
32 #include "rtc_base/location.h"
33 #include "rtc_base/logging.h"
34 #include "rtc_base/message_handler.h"
35 #include "rtc_base/socket.h"
36 #include "rtc_base/socket_address.h"
37 #include "rtc_base/test_client.h"
38 #include "rtc_base/test_utils.h"
39 #include "rtc_base/third_party/sigslot/sigslot.h"
40 #include "rtc_base/thread.h"
41 #include "rtc_base/time_utils.h"
42 #include "rtc_base/virtual_socket_server.h"
43 #include "test/gtest.h"
44
45 namespace rtc {
46 namespace {
47
48 using webrtc::testing::SSE_CLOSE;
49 using webrtc::testing::SSE_ERROR;
50 using webrtc::testing::SSE_OPEN;
51 using webrtc::testing::SSE_READ;
52 using webrtc::testing::SSE_WRITE;
53 using webrtc::testing::StreamSink;
54
55 // Sends at a constant rate but with random packet sizes.
56 struct Sender : public MessageHandler {
Senderrtc::__anon2d16ee820111::Sender57 Sender(Thread* th, AsyncSocket* s, uint32_t rt)
58 : thread(th),
59 socket(std::make_unique<AsyncUDPSocket>(s)),
60 done(false),
61 rate(rt),
62 count(0) {
63 last_send = rtc::TimeMillis();
64 thread->PostDelayed(RTC_FROM_HERE, NextDelay(), this, 1);
65 }
66
NextDelayrtc::__anon2d16ee820111::Sender67 uint32_t NextDelay() {
68 uint32_t size = (rand() % 4096) + 1;
69 return 1000 * size / rate;
70 }
71
OnMessagertc::__anon2d16ee820111::Sender72 void OnMessage(Message* pmsg) override {
73 ASSERT_EQ(1u, pmsg->message_id);
74
75 if (done)
76 return;
77
78 int64_t cur_time = rtc::TimeMillis();
79 int64_t delay = cur_time - last_send;
80 uint32_t size = static_cast<uint32_t>(rate * delay / 1000);
81 size = std::min<uint32_t>(size, 4096);
82 size = std::max<uint32_t>(size, sizeof(uint32_t));
83
84 count += size;
85 memcpy(dummy, &cur_time, sizeof(cur_time));
86 socket->Send(dummy, size, options);
87
88 last_send = cur_time;
89 thread->PostDelayed(RTC_FROM_HERE, NextDelay(), this, 1);
90 }
91
92 Thread* thread;
93 std::unique_ptr<AsyncUDPSocket> socket;
94 rtc::PacketOptions options;
95 bool done;
96 uint32_t rate; // bytes per second
97 uint32_t count;
98 int64_t last_send;
99 char dummy[4096];
100 };
101
102 struct Receiver : public MessageHandler, public sigslot::has_slots<> {
Receiverrtc::__anon2d16ee820111::Receiver103 Receiver(Thread* th, AsyncSocket* s, uint32_t bw)
104 : thread(th),
105 socket(std::make_unique<AsyncUDPSocket>(s)),
106 bandwidth(bw),
107 done(false),
108 count(0),
109 sec_count(0),
110 sum(0),
111 sum_sq(0),
112 samples(0) {
113 socket->SignalReadPacket.connect(this, &Receiver::OnReadPacket);
114 thread->PostDelayed(RTC_FROM_HERE, 1000, this, 1);
115 }
116
~Receiverrtc::__anon2d16ee820111::Receiver117 ~Receiver() override { thread->Clear(this); }
118
OnReadPacketrtc::__anon2d16ee820111::Receiver119 void OnReadPacket(AsyncPacketSocket* s,
120 const char* data,
121 size_t size,
122 const SocketAddress& remote_addr,
123 const int64_t& /* packet_time_us */) {
124 ASSERT_EQ(socket.get(), s);
125 ASSERT_GE(size, 4U);
126
127 count += size;
128 sec_count += size;
129
130 uint32_t send_time = *reinterpret_cast<const uint32_t*>(data);
131 uint32_t recv_time = rtc::TimeMillis();
132 uint32_t delay = recv_time - send_time;
133 sum += delay;
134 sum_sq += delay * delay;
135 samples += 1;
136 }
137
OnMessagertc::__anon2d16ee820111::Receiver138 void OnMessage(Message* pmsg) override {
139 ASSERT_EQ(1u, pmsg->message_id);
140
141 if (done)
142 return;
143
144 // It is always possible for us to receive more than expected because
145 // packets can be further delayed in delivery.
146 if (bandwidth > 0)
147 ASSERT_TRUE(sec_count <= 5 * bandwidth / 4);
148 sec_count = 0;
149 thread->PostDelayed(RTC_FROM_HERE, 1000, this, 1);
150 }
151
152 Thread* thread;
153 std::unique_ptr<AsyncUDPSocket> socket;
154 uint32_t bandwidth;
155 bool done;
156 size_t count;
157 size_t sec_count;
158 double sum;
159 double sum_sq;
160 uint32_t samples;
161 };
162
163 // Note: This test uses a fake clock in addition to a virtual network.
164 class VirtualSocketServerTest : public ::testing::Test {
165 public:
VirtualSocketServerTest()166 VirtualSocketServerTest()
167 : ss_(&fake_clock_),
168 thread_(&ss_),
169 kIPv4AnyAddress(IPAddress(INADDR_ANY), 0),
170 kIPv6AnyAddress(IPAddress(in6addr_any), 0) {}
171
CheckPortIncrementalization(const SocketAddress & post,const SocketAddress & pre)172 void CheckPortIncrementalization(const SocketAddress& post,
173 const SocketAddress& pre) {
174 EXPECT_EQ(post.port(), pre.port() + 1);
175 IPAddress post_ip = post.ipaddr();
176 IPAddress pre_ip = pre.ipaddr();
177 EXPECT_EQ(pre_ip.family(), post_ip.family());
178 if (post_ip.family() == AF_INET) {
179 in_addr pre_ipv4 = pre_ip.ipv4_address();
180 in_addr post_ipv4 = post_ip.ipv4_address();
181 EXPECT_EQ(post_ipv4.s_addr, pre_ipv4.s_addr);
182 } else if (post_ip.family() == AF_INET6) {
183 in6_addr post_ip6 = post_ip.ipv6_address();
184 in6_addr pre_ip6 = pre_ip.ipv6_address();
185 uint32_t* post_as_ints = reinterpret_cast<uint32_t*>(&post_ip6.s6_addr);
186 uint32_t* pre_as_ints = reinterpret_cast<uint32_t*>(&pre_ip6.s6_addr);
187 EXPECT_EQ(post_as_ints[3], pre_as_ints[3]);
188 }
189 }
190
191 // Test a client can bind to the any address, and all sent packets will have
192 // the default route as the source address. Also, it can receive packets sent
193 // to the default route.
TestDefaultRoute(const IPAddress & default_route)194 void TestDefaultRoute(const IPAddress& default_route) {
195 ss_.SetDefaultRoute(default_route);
196
197 // Create client1 bound to the any address.
198 AsyncSocket* socket =
199 ss_.CreateAsyncSocket(default_route.family(), SOCK_DGRAM);
200 socket->Bind(EmptySocketAddressWithFamily(default_route.family()));
201 SocketAddress client1_any_addr = socket->GetLocalAddress();
202 EXPECT_TRUE(client1_any_addr.IsAnyIP());
203 auto client1 = std::make_unique<TestClient>(
204 std::make_unique<AsyncUDPSocket>(socket), &fake_clock_);
205
206 // Create client2 bound to the default route.
207 AsyncSocket* socket2 =
208 ss_.CreateAsyncSocket(default_route.family(), SOCK_DGRAM);
209 socket2->Bind(SocketAddress(default_route, 0));
210 SocketAddress client2_addr = socket2->GetLocalAddress();
211 EXPECT_FALSE(client2_addr.IsAnyIP());
212 auto client2 = std::make_unique<TestClient>(
213 std::make_unique<AsyncUDPSocket>(socket2), &fake_clock_);
214
215 // Client1 sends to client2, client2 should see the default route as
216 // client1's address.
217 SocketAddress client1_addr;
218 EXPECT_EQ(6, client1->SendTo("bizbaz", 6, client2_addr));
219 EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &client1_addr));
220 EXPECT_EQ(client1_addr,
221 SocketAddress(default_route, client1_any_addr.port()));
222
223 // Client2 can send back to client1's default route address.
224 EXPECT_EQ(3, client2->SendTo("foo", 3, client1_addr));
225 EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &client2_addr));
226 }
227
BasicTest(const SocketAddress & initial_addr)228 void BasicTest(const SocketAddress& initial_addr) {
229 AsyncSocket* socket =
230 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
231 socket->Bind(initial_addr);
232 SocketAddress server_addr = socket->GetLocalAddress();
233 // Make sure VSS didn't switch families on us.
234 EXPECT_EQ(server_addr.family(), initial_addr.family());
235
236 auto client1 = std::make_unique<TestClient>(
237 std::make_unique<AsyncUDPSocket>(socket), &fake_clock_);
238 AsyncSocket* socket2 =
239 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
240 auto client2 = std::make_unique<TestClient>(
241 std::make_unique<AsyncUDPSocket>(socket2), &fake_clock_);
242
243 SocketAddress client2_addr;
244 EXPECT_EQ(3, client2->SendTo("foo", 3, server_addr));
245 EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &client2_addr));
246
247 SocketAddress client1_addr;
248 EXPECT_EQ(6, client1->SendTo("bizbaz", 6, client2_addr));
249 EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &client1_addr));
250 EXPECT_EQ(client1_addr, server_addr);
251
252 SocketAddress empty = EmptySocketAddressWithFamily(initial_addr.family());
253 for (int i = 0; i < 10; i++) {
254 client2 = std::make_unique<TestClient>(
255 absl::WrapUnique(AsyncUDPSocket::Create(&ss_, empty)), &fake_clock_);
256
257 SocketAddress next_client2_addr;
258 EXPECT_EQ(3, client2->SendTo("foo", 3, server_addr));
259 EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &next_client2_addr));
260 CheckPortIncrementalization(next_client2_addr, client2_addr);
261 // EXPECT_EQ(next_client2_addr.port(), client2_addr.port() + 1);
262
263 SocketAddress server_addr2;
264 EXPECT_EQ(6, client1->SendTo("bizbaz", 6, next_client2_addr));
265 EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &server_addr2));
266 EXPECT_EQ(server_addr2, server_addr);
267
268 client2_addr = next_client2_addr;
269 }
270 }
271
272 // initial_addr should be made from either INADDR_ANY or in6addr_any.
ConnectTest(const SocketAddress & initial_addr)273 void ConnectTest(const SocketAddress& initial_addr) {
274 StreamSink sink;
275 SocketAddress accept_addr;
276 const SocketAddress kEmptyAddr =
277 EmptySocketAddressWithFamily(initial_addr.family());
278
279 // Create client
280 std::unique_ptr<AsyncSocket> client = absl::WrapUnique(
281 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
282 sink.Monitor(client.get());
283 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
284 EXPECT_TRUE(client->GetLocalAddress().IsNil());
285
286 // Create server
287 std::unique_ptr<AsyncSocket> server = absl::WrapUnique(
288 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
289 sink.Monitor(server.get());
290 EXPECT_NE(0, server->Listen(5)); // Bind required
291 EXPECT_EQ(0, server->Bind(initial_addr));
292 EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
293 EXPECT_EQ(0, server->Listen(5));
294 EXPECT_EQ(server->GetState(), AsyncSocket::CS_CONNECTING);
295
296 // No pending server connections
297 EXPECT_FALSE(sink.Check(server.get(), SSE_READ));
298 EXPECT_TRUE(nullptr == server->Accept(&accept_addr));
299 EXPECT_EQ(AF_UNSPEC, accept_addr.family());
300
301 // Attempt connect to listening socket
302 EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
303 EXPECT_NE(client->GetLocalAddress(), kEmptyAddr); // Implicit Bind
304 EXPECT_NE(AF_UNSPEC, client->GetLocalAddress().family()); // Implicit Bind
305 EXPECT_NE(client->GetLocalAddress(), server->GetLocalAddress());
306
307 // Client is connecting
308 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTING);
309 EXPECT_FALSE(sink.Check(client.get(), SSE_OPEN));
310 EXPECT_FALSE(sink.Check(client.get(), SSE_CLOSE));
311
312 ss_.ProcessMessagesUntilIdle();
313
314 // Client still connecting
315 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTING);
316 EXPECT_FALSE(sink.Check(client.get(), SSE_OPEN));
317 EXPECT_FALSE(sink.Check(client.get(), SSE_CLOSE));
318
319 // Server has pending connection
320 EXPECT_TRUE(sink.Check(server.get(), SSE_READ));
321 std::unique_ptr<Socket> accepted =
322 absl::WrapUnique(server->Accept(&accept_addr));
323 EXPECT_TRUE(nullptr != accepted);
324 EXPECT_NE(accept_addr, kEmptyAddr);
325 EXPECT_EQ(accepted->GetRemoteAddress(), accept_addr);
326
327 EXPECT_EQ(accepted->GetState(), AsyncSocket::CS_CONNECTED);
328 EXPECT_EQ(accepted->GetLocalAddress(), server->GetLocalAddress());
329 EXPECT_EQ(accepted->GetRemoteAddress(), client->GetLocalAddress());
330
331 ss_.ProcessMessagesUntilIdle();
332
333 // Client has connected
334 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTED);
335 EXPECT_TRUE(sink.Check(client.get(), SSE_OPEN));
336 EXPECT_FALSE(sink.Check(client.get(), SSE_CLOSE));
337 EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
338 EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
339 }
340
ConnectToNonListenerTest(const SocketAddress & initial_addr)341 void ConnectToNonListenerTest(const SocketAddress& initial_addr) {
342 StreamSink sink;
343 SocketAddress accept_addr;
344 const SocketAddress nil_addr;
345 const SocketAddress empty_addr =
346 EmptySocketAddressWithFamily(initial_addr.family());
347
348 // Create client
349 std::unique_ptr<AsyncSocket> client = absl::WrapUnique(
350 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
351 sink.Monitor(client.get());
352
353 // Create server
354 std::unique_ptr<AsyncSocket> server = absl::WrapUnique(
355 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
356 sink.Monitor(server.get());
357 EXPECT_EQ(0, server->Bind(initial_addr));
358 EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
359 // Attempt connect to non-listening socket
360 EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
361
362 ss_.ProcessMessagesUntilIdle();
363
364 // No pending server connections
365 EXPECT_FALSE(sink.Check(server.get(), SSE_READ));
366 EXPECT_TRUE(nullptr == server->Accept(&accept_addr));
367 EXPECT_EQ(accept_addr, nil_addr);
368
369 // Connection failed
370 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
371 EXPECT_FALSE(sink.Check(client.get(), SSE_OPEN));
372 EXPECT_TRUE(sink.Check(client.get(), SSE_ERROR));
373 EXPECT_EQ(client->GetRemoteAddress(), nil_addr);
374 }
375
CloseDuringConnectTest(const SocketAddress & initial_addr)376 void CloseDuringConnectTest(const SocketAddress& initial_addr) {
377 StreamSink sink;
378 SocketAddress accept_addr;
379 const SocketAddress empty_addr =
380 EmptySocketAddressWithFamily(initial_addr.family());
381
382 // Create client and server
383 std::unique_ptr<AsyncSocket> client(
384 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
385 sink.Monitor(client.get());
386 std::unique_ptr<AsyncSocket> server(
387 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
388 sink.Monitor(server.get());
389
390 // Initiate connect
391 EXPECT_EQ(0, server->Bind(initial_addr));
392 EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
393
394 EXPECT_EQ(0, server->Listen(5));
395 EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
396
397 // Server close before socket enters accept queue
398 EXPECT_FALSE(sink.Check(server.get(), SSE_READ));
399 server->Close();
400
401 ss_.ProcessMessagesUntilIdle();
402
403 // Result: connection failed
404 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
405 EXPECT_TRUE(sink.Check(client.get(), SSE_ERROR));
406
407 server.reset(ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
408 sink.Monitor(server.get());
409
410 // Initiate connect
411 EXPECT_EQ(0, server->Bind(initial_addr));
412 EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
413
414 EXPECT_EQ(0, server->Listen(5));
415 EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
416
417 ss_.ProcessMessagesUntilIdle();
418
419 // Server close while socket is in accept queue
420 EXPECT_TRUE(sink.Check(server.get(), SSE_READ));
421 server->Close();
422
423 ss_.ProcessMessagesUntilIdle();
424
425 // Result: connection failed
426 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
427 EXPECT_TRUE(sink.Check(client.get(), SSE_ERROR));
428
429 // New server
430 server.reset(ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
431 sink.Monitor(server.get());
432
433 // Initiate connect
434 EXPECT_EQ(0, server->Bind(initial_addr));
435 EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
436
437 EXPECT_EQ(0, server->Listen(5));
438 EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
439
440 ss_.ProcessMessagesUntilIdle();
441
442 // Server accepts connection
443 EXPECT_TRUE(sink.Check(server.get(), SSE_READ));
444 std::unique_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
445 ASSERT_TRUE(nullptr != accepted.get());
446 sink.Monitor(accepted.get());
447
448 // Client closes before connection complets
449 EXPECT_EQ(accepted->GetState(), AsyncSocket::CS_CONNECTED);
450
451 // Connected message has not been processed yet.
452 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTING);
453 client->Close();
454
455 ss_.ProcessMessagesUntilIdle();
456
457 // Result: accepted socket closes
458 EXPECT_EQ(accepted->GetState(), AsyncSocket::CS_CLOSED);
459 EXPECT_TRUE(sink.Check(accepted.get(), SSE_CLOSE));
460 EXPECT_FALSE(sink.Check(client.get(), SSE_CLOSE));
461 }
462
CloseTest(const SocketAddress & initial_addr)463 void CloseTest(const SocketAddress& initial_addr) {
464 StreamSink sink;
465 const SocketAddress kEmptyAddr;
466
467 // Create clients
468 std::unique_ptr<AsyncSocket> a = absl::WrapUnique(
469 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
470 sink.Monitor(a.get());
471 a->Bind(initial_addr);
472 EXPECT_EQ(a->GetLocalAddress().family(), initial_addr.family());
473
474 std::unique_ptr<AsyncSocket> b = absl::WrapUnique(
475 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
476 sink.Monitor(b.get());
477 b->Bind(initial_addr);
478 EXPECT_EQ(b->GetLocalAddress().family(), initial_addr.family());
479
480 EXPECT_EQ(0, a->Connect(b->GetLocalAddress()));
481 EXPECT_EQ(0, b->Connect(a->GetLocalAddress()));
482
483 ss_.ProcessMessagesUntilIdle();
484
485 EXPECT_TRUE(sink.Check(a.get(), SSE_OPEN));
486 EXPECT_EQ(a->GetState(), AsyncSocket::CS_CONNECTED);
487 EXPECT_EQ(a->GetRemoteAddress(), b->GetLocalAddress());
488
489 EXPECT_TRUE(sink.Check(b.get(), SSE_OPEN));
490 EXPECT_EQ(b->GetState(), AsyncSocket::CS_CONNECTED);
491 EXPECT_EQ(b->GetRemoteAddress(), a->GetLocalAddress());
492
493 EXPECT_EQ(1, a->Send("a", 1));
494 b->Close();
495 EXPECT_EQ(1, a->Send("b", 1));
496
497 ss_.ProcessMessagesUntilIdle();
498
499 char buffer[10];
500 EXPECT_FALSE(sink.Check(b.get(), SSE_READ));
501 EXPECT_EQ(-1, b->Recv(buffer, 10, nullptr));
502
503 EXPECT_TRUE(sink.Check(a.get(), SSE_CLOSE));
504 EXPECT_EQ(a->GetState(), AsyncSocket::CS_CLOSED);
505 EXPECT_EQ(a->GetRemoteAddress(), kEmptyAddr);
506
507 // No signal for Closer
508 EXPECT_FALSE(sink.Check(b.get(), SSE_CLOSE));
509 EXPECT_EQ(b->GetState(), AsyncSocket::CS_CLOSED);
510 EXPECT_EQ(b->GetRemoteAddress(), kEmptyAddr);
511 }
512
TcpSendTest(const SocketAddress & initial_addr)513 void TcpSendTest(const SocketAddress& initial_addr) {
514 StreamSink sink;
515 const SocketAddress kEmptyAddr;
516
517 // Connect two sockets
518 std::unique_ptr<AsyncSocket> a = absl::WrapUnique(
519 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
520 sink.Monitor(a.get());
521 a->Bind(initial_addr);
522 EXPECT_EQ(a->GetLocalAddress().family(), initial_addr.family());
523
524 std::unique_ptr<AsyncSocket> b = absl::WrapUnique(
525 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
526 sink.Monitor(b.get());
527 b->Bind(initial_addr);
528 EXPECT_EQ(b->GetLocalAddress().family(), initial_addr.family());
529
530 EXPECT_EQ(0, a->Connect(b->GetLocalAddress()));
531 EXPECT_EQ(0, b->Connect(a->GetLocalAddress()));
532
533 ss_.ProcessMessagesUntilIdle();
534
535 const size_t kBufferSize = 2000;
536 ss_.set_send_buffer_capacity(kBufferSize);
537 ss_.set_recv_buffer_capacity(kBufferSize);
538
539 const size_t kDataSize = 5000;
540 char send_buffer[kDataSize], recv_buffer[kDataSize];
541 for (size_t i = 0; i < kDataSize; ++i)
542 send_buffer[i] = static_cast<char>(i % 256);
543 memset(recv_buffer, 0, sizeof(recv_buffer));
544 size_t send_pos = 0, recv_pos = 0;
545
546 // Can't send more than send buffer in one write
547 int result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
548 EXPECT_EQ(static_cast<int>(kBufferSize), result);
549 send_pos += result;
550
551 ss_.ProcessMessagesUntilIdle();
552 EXPECT_FALSE(sink.Check(a.get(), SSE_WRITE));
553 EXPECT_TRUE(sink.Check(b.get(), SSE_READ));
554
555 // Receive buffer is already filled, fill send buffer again
556 result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
557 EXPECT_EQ(static_cast<int>(kBufferSize), result);
558 send_pos += result;
559
560 ss_.ProcessMessagesUntilIdle();
561 EXPECT_FALSE(sink.Check(a.get(), SSE_WRITE));
562 EXPECT_FALSE(sink.Check(b.get(), SSE_READ));
563
564 // No more room in send or receive buffer
565 result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
566 EXPECT_EQ(-1, result);
567 EXPECT_TRUE(a->IsBlocking());
568
569 // Read a subset of the data
570 result = b->Recv(recv_buffer + recv_pos, 500, nullptr);
571 EXPECT_EQ(500, result);
572 recv_pos += result;
573
574 ss_.ProcessMessagesUntilIdle();
575 EXPECT_TRUE(sink.Check(a.get(), SSE_WRITE));
576 EXPECT_TRUE(sink.Check(b.get(), SSE_READ));
577
578 // Room for more on the sending side
579 result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
580 EXPECT_EQ(500, result);
581 send_pos += result;
582
583 // Empty the recv buffer
584 while (true) {
585 result = b->Recv(recv_buffer + recv_pos, kDataSize - recv_pos, nullptr);
586 if (result < 0) {
587 EXPECT_EQ(-1, result);
588 EXPECT_TRUE(b->IsBlocking());
589 break;
590 }
591 recv_pos += result;
592 }
593
594 ss_.ProcessMessagesUntilIdle();
595 EXPECT_TRUE(sink.Check(b.get(), SSE_READ));
596
597 // Continue to empty the recv buffer
598 while (true) {
599 result = b->Recv(recv_buffer + recv_pos, kDataSize - recv_pos, nullptr);
600 if (result < 0) {
601 EXPECT_EQ(-1, result);
602 EXPECT_TRUE(b->IsBlocking());
603 break;
604 }
605 recv_pos += result;
606 }
607
608 // Send last of the data
609 result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
610 EXPECT_EQ(500, result);
611 send_pos += result;
612
613 ss_.ProcessMessagesUntilIdle();
614 EXPECT_TRUE(sink.Check(b.get(), SSE_READ));
615
616 // Receive the last of the data
617 while (true) {
618 result = b->Recv(recv_buffer + recv_pos, kDataSize - recv_pos, nullptr);
619 if (result < 0) {
620 EXPECT_EQ(-1, result);
621 EXPECT_TRUE(b->IsBlocking());
622 break;
623 }
624 recv_pos += result;
625 }
626
627 ss_.ProcessMessagesUntilIdle();
628 EXPECT_FALSE(sink.Check(b.get(), SSE_READ));
629
630 // The received data matches the sent data
631 EXPECT_EQ(kDataSize, send_pos);
632 EXPECT_EQ(kDataSize, recv_pos);
633 EXPECT_EQ(0, memcmp(recv_buffer, send_buffer, kDataSize));
634 }
635
TcpSendsPacketsInOrderTest(const SocketAddress & initial_addr)636 void TcpSendsPacketsInOrderTest(const SocketAddress& initial_addr) {
637 const SocketAddress kEmptyAddr;
638
639 // Connect two sockets
640 std::unique_ptr<AsyncSocket> a = absl::WrapUnique(
641 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
642 std::unique_ptr<AsyncSocket> b = absl::WrapUnique(
643 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
644 a->Bind(initial_addr);
645 EXPECT_EQ(a->GetLocalAddress().family(), initial_addr.family());
646
647 b->Bind(initial_addr);
648 EXPECT_EQ(b->GetLocalAddress().family(), initial_addr.family());
649
650 EXPECT_EQ(0, a->Connect(b->GetLocalAddress()));
651 EXPECT_EQ(0, b->Connect(a->GetLocalAddress()));
652 ss_.ProcessMessagesUntilIdle();
653
654 // First, deliver all packets in 0 ms.
655 char buffer[2] = {0, 0};
656 const char cNumPackets = 10;
657 for (char i = 0; i < cNumPackets; ++i) {
658 buffer[0] = '0' + i;
659 EXPECT_EQ(1, a->Send(buffer, 1));
660 }
661
662 ss_.ProcessMessagesUntilIdle();
663
664 for (char i = 0; i < cNumPackets; ++i) {
665 EXPECT_EQ(1, b->Recv(buffer, sizeof(buffer), nullptr));
666 EXPECT_EQ(static_cast<char>('0' + i), buffer[0]);
667 }
668
669 // Next, deliver packets at random intervals
670 const uint32_t mean = 50;
671 const uint32_t stddev = 50;
672
673 ss_.set_delay_mean(mean);
674 ss_.set_delay_stddev(stddev);
675 ss_.UpdateDelayDistribution();
676
677 for (char i = 0; i < cNumPackets; ++i) {
678 buffer[0] = 'A' + i;
679 EXPECT_EQ(1, a->Send(buffer, 1));
680 }
681
682 ss_.ProcessMessagesUntilIdle();
683
684 for (char i = 0; i < cNumPackets; ++i) {
685 EXPECT_EQ(1, b->Recv(buffer, sizeof(buffer), nullptr));
686 EXPECT_EQ(static_cast<char>('A' + i), buffer[0]);
687 }
688 }
689
690 // It is important that initial_addr's port has to be 0 such that the
691 // incremental port behavior could ensure the 2 Binds result in different
692 // address.
BandwidthTest(const SocketAddress & initial_addr)693 void BandwidthTest(const SocketAddress& initial_addr) {
694 AsyncSocket* send_socket =
695 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
696 AsyncSocket* recv_socket =
697 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
698 ASSERT_EQ(0, send_socket->Bind(initial_addr));
699 ASSERT_EQ(0, recv_socket->Bind(initial_addr));
700 EXPECT_EQ(send_socket->GetLocalAddress().family(), initial_addr.family());
701 EXPECT_EQ(recv_socket->GetLocalAddress().family(), initial_addr.family());
702 ASSERT_EQ(0, send_socket->Connect(recv_socket->GetLocalAddress()));
703
704 uint32_t bandwidth = 64 * 1024;
705 ss_.set_bandwidth(bandwidth);
706
707 Thread* pthMain = Thread::Current();
708 Sender sender(pthMain, send_socket, 80 * 1024);
709 Receiver receiver(pthMain, recv_socket, bandwidth);
710
711 // Allow the sender to run for 5 (simulated) seconds, then be stopped for 5
712 // seconds.
713 SIMULATED_WAIT(false, 5000, fake_clock_);
714 sender.done = true;
715 SIMULATED_WAIT(false, 5000, fake_clock_);
716
717 // Ensure the observed bandwidth fell within a reasonable margin of error.
718 EXPECT_TRUE(receiver.count >= 5 * 3 * bandwidth / 4);
719 EXPECT_TRUE(receiver.count <= 6 * bandwidth); // queue could drain for 1s
720
721 ss_.set_bandwidth(0);
722 }
723
724 // It is important that initial_addr's port has to be 0 such that the
725 // incremental port behavior could ensure the 2 Binds result in different
726 // address.
DelayTest(const SocketAddress & initial_addr)727 void DelayTest(const SocketAddress& initial_addr) {
728 time_t seed = ::time(nullptr);
729 RTC_LOG(LS_VERBOSE) << "seed = " << seed;
730 srand(static_cast<unsigned int>(seed));
731
732 const uint32_t mean = 2000;
733 const uint32_t stddev = 500;
734
735 ss_.set_delay_mean(mean);
736 ss_.set_delay_stddev(stddev);
737 ss_.UpdateDelayDistribution();
738
739 AsyncSocket* send_socket =
740 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
741 AsyncSocket* recv_socket =
742 ss_.CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
743 ASSERT_EQ(0, send_socket->Bind(initial_addr));
744 ASSERT_EQ(0, recv_socket->Bind(initial_addr));
745 EXPECT_EQ(send_socket->GetLocalAddress().family(), initial_addr.family());
746 EXPECT_EQ(recv_socket->GetLocalAddress().family(), initial_addr.family());
747 ASSERT_EQ(0, send_socket->Connect(recv_socket->GetLocalAddress()));
748
749 Thread* pthMain = Thread::Current();
750 // Avg packet size is 2K, so at 200KB/s for 10s, we should see about
751 // 1000 packets, which is necessary to get a good distribution.
752 Sender sender(pthMain, send_socket, 100 * 2 * 1024);
753 Receiver receiver(pthMain, recv_socket, 0);
754
755 // Simulate 10 seconds of packets being sent, then check the observed delay
756 // distribution.
757 SIMULATED_WAIT(false, 10000, fake_clock_);
758 sender.done = receiver.done = true;
759 ss_.ProcessMessagesUntilIdle();
760
761 const double sample_mean = receiver.sum / receiver.samples;
762 double num =
763 receiver.samples * receiver.sum_sq - receiver.sum * receiver.sum;
764 double den = receiver.samples * (receiver.samples - 1);
765 const double sample_stddev = sqrt(num / den);
766 RTC_LOG(LS_VERBOSE) << "mean=" << sample_mean
767 << " stddev=" << sample_stddev;
768
769 EXPECT_LE(500u, receiver.samples);
770 // We initially used a 0.1 fudge factor, but on the build machine, we
771 // have seen the value differ by as much as 0.13.
772 EXPECT_NEAR(mean, sample_mean, 0.15 * mean);
773 EXPECT_NEAR(stddev, sample_stddev, 0.15 * stddev);
774
775 ss_.set_delay_mean(0);
776 ss_.set_delay_stddev(0);
777 ss_.UpdateDelayDistribution();
778 }
779
780 // Test cross-family communication between a client bound to client_addr and a
781 // server bound to server_addr. shouldSucceed indicates if communication is
782 // expected to work or not.
CrossFamilyConnectionTest(const SocketAddress & client_addr,const SocketAddress & server_addr,bool shouldSucceed)783 void CrossFamilyConnectionTest(const SocketAddress& client_addr,
784 const SocketAddress& server_addr,
785 bool shouldSucceed) {
786 StreamSink sink;
787 SocketAddress accept_address;
788 const SocketAddress kEmptyAddr;
789
790 // Client gets a IPv4 address
791 std::unique_ptr<AsyncSocket> client = absl::WrapUnique(
792 ss_.CreateAsyncSocket(client_addr.family(), SOCK_STREAM));
793 sink.Monitor(client.get());
794 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
795 EXPECT_EQ(client->GetLocalAddress(), kEmptyAddr);
796 client->Bind(client_addr);
797
798 // Server gets a non-mapped non-any IPv6 address.
799 // IPv4 sockets should not be able to connect to this.
800 std::unique_ptr<AsyncSocket> server = absl::WrapUnique(
801 ss_.CreateAsyncSocket(server_addr.family(), SOCK_STREAM));
802 sink.Monitor(server.get());
803 server->Bind(server_addr);
804 server->Listen(5);
805
806 if (shouldSucceed) {
807 EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
808 ss_.ProcessMessagesUntilIdle();
809 EXPECT_TRUE(sink.Check(server.get(), SSE_READ));
810 std::unique_ptr<Socket> accepted =
811 absl::WrapUnique(server->Accept(&accept_address));
812 EXPECT_TRUE(nullptr != accepted);
813 EXPECT_NE(kEmptyAddr, accept_address);
814 ss_.ProcessMessagesUntilIdle();
815 EXPECT_TRUE(sink.Check(client.get(), SSE_OPEN));
816 EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
817 } else {
818 // Check that the connection failed.
819 EXPECT_EQ(-1, client->Connect(server->GetLocalAddress()));
820 ss_.ProcessMessagesUntilIdle();
821
822 EXPECT_FALSE(sink.Check(server.get(), SSE_READ));
823 EXPECT_TRUE(nullptr == server->Accept(&accept_address));
824 EXPECT_EQ(accept_address, kEmptyAddr);
825 EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
826 EXPECT_FALSE(sink.Check(client.get(), SSE_OPEN));
827 EXPECT_EQ(client->GetRemoteAddress(), kEmptyAddr);
828 }
829 }
830
831 // Test cross-family datagram sending between a client bound to client_addr
832 // and a server bound to server_addr. shouldSucceed indicates if sending is
833 // expected to succeed or not.
CrossFamilyDatagramTest(const SocketAddress & client_addr,const SocketAddress & server_addr,bool shouldSucceed)834 void CrossFamilyDatagramTest(const SocketAddress& client_addr,
835 const SocketAddress& server_addr,
836 bool shouldSucceed) {
837 AsyncSocket* socket = ss_.CreateAsyncSocket(AF_INET, SOCK_DGRAM);
838 socket->Bind(server_addr);
839 SocketAddress bound_server_addr = socket->GetLocalAddress();
840 auto client1 = std::make_unique<TestClient>(
841 std::make_unique<AsyncUDPSocket>(socket), &fake_clock_);
842
843 AsyncSocket* socket2 = ss_.CreateAsyncSocket(AF_INET, SOCK_DGRAM);
844 socket2->Bind(client_addr);
845 auto client2 = std::make_unique<TestClient>(
846 std::make_unique<AsyncUDPSocket>(socket2), &fake_clock_);
847 SocketAddress client2_addr;
848
849 if (shouldSucceed) {
850 EXPECT_EQ(3, client2->SendTo("foo", 3, bound_server_addr));
851 EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &client2_addr));
852 SocketAddress client1_addr;
853 EXPECT_EQ(6, client1->SendTo("bizbaz", 6, client2_addr));
854 EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &client1_addr));
855 EXPECT_EQ(client1_addr, bound_server_addr);
856 } else {
857 EXPECT_EQ(-1, client2->SendTo("foo", 3, bound_server_addr));
858 EXPECT_TRUE(client1->CheckNoPacket());
859 }
860 }
861
862 protected:
863 rtc::ScopedFakeClock fake_clock_;
864 VirtualSocketServer ss_;
865 AutoSocketServerThread thread_;
866 const SocketAddress kIPv4AnyAddress;
867 const SocketAddress kIPv6AnyAddress;
868 };
869
TEST_F(VirtualSocketServerTest,basic_v4)870 TEST_F(VirtualSocketServerTest, basic_v4) {
871 SocketAddress ipv4_test_addr(IPAddress(INADDR_ANY), 5000);
872 BasicTest(ipv4_test_addr);
873 }
874
TEST_F(VirtualSocketServerTest,basic_v6)875 TEST_F(VirtualSocketServerTest, basic_v6) {
876 SocketAddress ipv6_test_addr(IPAddress(in6addr_any), 5000);
877 BasicTest(ipv6_test_addr);
878 }
879
TEST_F(VirtualSocketServerTest,TestDefaultRoute_v4)880 TEST_F(VirtualSocketServerTest, TestDefaultRoute_v4) {
881 IPAddress ipv4_default_addr(0x01020304);
882 TestDefaultRoute(ipv4_default_addr);
883 }
884
TEST_F(VirtualSocketServerTest,TestDefaultRoute_v6)885 TEST_F(VirtualSocketServerTest, TestDefaultRoute_v6) {
886 IPAddress ipv6_default_addr;
887 EXPECT_TRUE(
888 IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &ipv6_default_addr));
889 TestDefaultRoute(ipv6_default_addr);
890 }
891
TEST_F(VirtualSocketServerTest,connect_v4)892 TEST_F(VirtualSocketServerTest, connect_v4) {
893 ConnectTest(kIPv4AnyAddress);
894 }
895
TEST_F(VirtualSocketServerTest,connect_v6)896 TEST_F(VirtualSocketServerTest, connect_v6) {
897 ConnectTest(kIPv6AnyAddress);
898 }
899
TEST_F(VirtualSocketServerTest,connect_to_non_listener_v4)900 TEST_F(VirtualSocketServerTest, connect_to_non_listener_v4) {
901 ConnectToNonListenerTest(kIPv4AnyAddress);
902 }
903
TEST_F(VirtualSocketServerTest,connect_to_non_listener_v6)904 TEST_F(VirtualSocketServerTest, connect_to_non_listener_v6) {
905 ConnectToNonListenerTest(kIPv6AnyAddress);
906 }
907
TEST_F(VirtualSocketServerTest,close_during_connect_v4)908 TEST_F(VirtualSocketServerTest, close_during_connect_v4) {
909 CloseDuringConnectTest(kIPv4AnyAddress);
910 }
911
TEST_F(VirtualSocketServerTest,close_during_connect_v6)912 TEST_F(VirtualSocketServerTest, close_during_connect_v6) {
913 CloseDuringConnectTest(kIPv6AnyAddress);
914 }
915
TEST_F(VirtualSocketServerTest,close_v4)916 TEST_F(VirtualSocketServerTest, close_v4) {
917 CloseTest(kIPv4AnyAddress);
918 }
919
TEST_F(VirtualSocketServerTest,close_v6)920 TEST_F(VirtualSocketServerTest, close_v6) {
921 CloseTest(kIPv6AnyAddress);
922 }
923
TEST_F(VirtualSocketServerTest,tcp_send_v4)924 TEST_F(VirtualSocketServerTest, tcp_send_v4) {
925 TcpSendTest(kIPv4AnyAddress);
926 }
927
TEST_F(VirtualSocketServerTest,tcp_send_v6)928 TEST_F(VirtualSocketServerTest, tcp_send_v6) {
929 TcpSendTest(kIPv6AnyAddress);
930 }
931
TEST_F(VirtualSocketServerTest,TcpSendsPacketsInOrder_v4)932 TEST_F(VirtualSocketServerTest, TcpSendsPacketsInOrder_v4) {
933 TcpSendsPacketsInOrderTest(kIPv4AnyAddress);
934 }
935
TEST_F(VirtualSocketServerTest,TcpSendsPacketsInOrder_v6)936 TEST_F(VirtualSocketServerTest, TcpSendsPacketsInOrder_v6) {
937 TcpSendsPacketsInOrderTest(kIPv6AnyAddress);
938 }
939
TEST_F(VirtualSocketServerTest,bandwidth_v4)940 TEST_F(VirtualSocketServerTest, bandwidth_v4) {
941 BandwidthTest(kIPv4AnyAddress);
942 }
943
TEST_F(VirtualSocketServerTest,bandwidth_v6)944 TEST_F(VirtualSocketServerTest, bandwidth_v6) {
945 BandwidthTest(kIPv6AnyAddress);
946 }
947
TEST_F(VirtualSocketServerTest,delay_v4)948 TEST_F(VirtualSocketServerTest, delay_v4) {
949 DelayTest(kIPv4AnyAddress);
950 }
951
TEST_F(VirtualSocketServerTest,delay_v6)952 TEST_F(VirtualSocketServerTest, delay_v6) {
953 DelayTest(kIPv6AnyAddress);
954 }
955
956 // Works, receiving socket sees 127.0.0.2.
TEST_F(VirtualSocketServerTest,CanConnectFromMappedIPv6ToIPv4Any)957 TEST_F(VirtualSocketServerTest, CanConnectFromMappedIPv6ToIPv4Any) {
958 CrossFamilyConnectionTest(SocketAddress("::ffff:127.0.0.2", 0),
959 SocketAddress("0.0.0.0", 5000), true);
960 }
961
962 // Fails.
TEST_F(VirtualSocketServerTest,CantConnectFromUnMappedIPv6ToIPv4Any)963 TEST_F(VirtualSocketServerTest, CantConnectFromUnMappedIPv6ToIPv4Any) {
964 CrossFamilyConnectionTest(SocketAddress("::2", 0),
965 SocketAddress("0.0.0.0", 5000), false);
966 }
967
968 // Fails.
TEST_F(VirtualSocketServerTest,CantConnectFromUnMappedIPv6ToMappedIPv6)969 TEST_F(VirtualSocketServerTest, CantConnectFromUnMappedIPv6ToMappedIPv6) {
970 CrossFamilyConnectionTest(SocketAddress("::2", 0),
971 SocketAddress("::ffff:127.0.0.1", 5000), false);
972 }
973
974 // Works. receiving socket sees ::ffff:127.0.0.2.
TEST_F(VirtualSocketServerTest,CanConnectFromIPv4ToIPv6Any)975 TEST_F(VirtualSocketServerTest, CanConnectFromIPv4ToIPv6Any) {
976 CrossFamilyConnectionTest(SocketAddress("127.0.0.2", 0),
977 SocketAddress("::", 5000), true);
978 }
979
980 // Fails.
TEST_F(VirtualSocketServerTest,CantConnectFromIPv4ToUnMappedIPv6)981 TEST_F(VirtualSocketServerTest, CantConnectFromIPv4ToUnMappedIPv6) {
982 CrossFamilyConnectionTest(SocketAddress("127.0.0.2", 0),
983 SocketAddress("::1", 5000), false);
984 }
985
986 // Works. Receiving socket sees ::ffff:127.0.0.1.
TEST_F(VirtualSocketServerTest,CanConnectFromIPv4ToMappedIPv6)987 TEST_F(VirtualSocketServerTest, CanConnectFromIPv4ToMappedIPv6) {
988 CrossFamilyConnectionTest(SocketAddress("127.0.0.1", 0),
989 SocketAddress("::ffff:127.0.0.2", 5000), true);
990 }
991
992 // Works, receiving socket sees a result from GetNextIP.
TEST_F(VirtualSocketServerTest,CanConnectFromUnboundIPv6ToIPv4Any)993 TEST_F(VirtualSocketServerTest, CanConnectFromUnboundIPv6ToIPv4Any) {
994 CrossFamilyConnectionTest(SocketAddress("::", 0),
995 SocketAddress("0.0.0.0", 5000), true);
996 }
997
998 // Works, receiving socket sees whatever GetNextIP gave the client.
TEST_F(VirtualSocketServerTest,CanConnectFromUnboundIPv4ToIPv6Any)999 TEST_F(VirtualSocketServerTest, CanConnectFromUnboundIPv4ToIPv6Any) {
1000 CrossFamilyConnectionTest(SocketAddress("0.0.0.0", 0),
1001 SocketAddress("::", 5000), true);
1002 }
1003
TEST_F(VirtualSocketServerTest,CanSendDatagramFromUnboundIPv4ToIPv6Any)1004 TEST_F(VirtualSocketServerTest, CanSendDatagramFromUnboundIPv4ToIPv6Any) {
1005 CrossFamilyDatagramTest(SocketAddress("0.0.0.0", 0),
1006 SocketAddress("::", 5000), true);
1007 }
1008
TEST_F(VirtualSocketServerTest,CanSendDatagramFromMappedIPv6ToIPv4Any)1009 TEST_F(VirtualSocketServerTest, CanSendDatagramFromMappedIPv6ToIPv4Any) {
1010 CrossFamilyDatagramTest(SocketAddress("::ffff:127.0.0.1", 0),
1011 SocketAddress("0.0.0.0", 5000), true);
1012 }
1013
TEST_F(VirtualSocketServerTest,CantSendDatagramFromUnMappedIPv6ToIPv4Any)1014 TEST_F(VirtualSocketServerTest, CantSendDatagramFromUnMappedIPv6ToIPv4Any) {
1015 CrossFamilyDatagramTest(SocketAddress("::2", 0),
1016 SocketAddress("0.0.0.0", 5000), false);
1017 }
1018
TEST_F(VirtualSocketServerTest,CantSendDatagramFromUnMappedIPv6ToMappedIPv6)1019 TEST_F(VirtualSocketServerTest, CantSendDatagramFromUnMappedIPv6ToMappedIPv6) {
1020 CrossFamilyDatagramTest(SocketAddress("::2", 0),
1021 SocketAddress("::ffff:127.0.0.1", 5000), false);
1022 }
1023
TEST_F(VirtualSocketServerTest,CanSendDatagramFromIPv4ToIPv6Any)1024 TEST_F(VirtualSocketServerTest, CanSendDatagramFromIPv4ToIPv6Any) {
1025 CrossFamilyDatagramTest(SocketAddress("127.0.0.2", 0),
1026 SocketAddress("::", 5000), true);
1027 }
1028
TEST_F(VirtualSocketServerTest,CantSendDatagramFromIPv4ToUnMappedIPv6)1029 TEST_F(VirtualSocketServerTest, CantSendDatagramFromIPv4ToUnMappedIPv6) {
1030 CrossFamilyDatagramTest(SocketAddress("127.0.0.2", 0),
1031 SocketAddress("::1", 5000), false);
1032 }
1033
TEST_F(VirtualSocketServerTest,CanSendDatagramFromIPv4ToMappedIPv6)1034 TEST_F(VirtualSocketServerTest, CanSendDatagramFromIPv4ToMappedIPv6) {
1035 CrossFamilyDatagramTest(SocketAddress("127.0.0.1", 0),
1036 SocketAddress("::ffff:127.0.0.2", 5000), true);
1037 }
1038
TEST_F(VirtualSocketServerTest,CanSendDatagramFromUnboundIPv6ToIPv4Any)1039 TEST_F(VirtualSocketServerTest, CanSendDatagramFromUnboundIPv6ToIPv4Any) {
1040 CrossFamilyDatagramTest(SocketAddress("::", 0),
1041 SocketAddress("0.0.0.0", 5000), true);
1042 }
1043
TEST_F(VirtualSocketServerTest,SetSendingBlockedWithUdpSocket)1044 TEST_F(VirtualSocketServerTest, SetSendingBlockedWithUdpSocket) {
1045 AsyncSocket* socket1 =
1046 ss_.CreateAsyncSocket(kIPv4AnyAddress.family(), SOCK_DGRAM);
1047 std::unique_ptr<AsyncSocket> socket2 = absl::WrapUnique(
1048 ss_.CreateAsyncSocket(kIPv4AnyAddress.family(), SOCK_DGRAM));
1049 socket1->Bind(kIPv4AnyAddress);
1050 socket2->Bind(kIPv4AnyAddress);
1051 auto client1 = std::make_unique<TestClient>(
1052 std::make_unique<AsyncUDPSocket>(socket1), &fake_clock_);
1053
1054 ss_.SetSendingBlocked(true);
1055 EXPECT_EQ(-1, client1->SendTo("foo", 3, socket2->GetLocalAddress()));
1056 EXPECT_TRUE(socket1->IsBlocking());
1057 EXPECT_EQ(0, client1->ready_to_send_count());
1058
1059 ss_.SetSendingBlocked(false);
1060 EXPECT_EQ(1, client1->ready_to_send_count());
1061 EXPECT_EQ(3, client1->SendTo("foo", 3, socket2->GetLocalAddress()));
1062 }
1063
TEST_F(VirtualSocketServerTest,SetSendingBlockedWithTcpSocket)1064 TEST_F(VirtualSocketServerTest, SetSendingBlockedWithTcpSocket) {
1065 constexpr size_t kBufferSize = 1024;
1066 ss_.set_send_buffer_capacity(kBufferSize);
1067 ss_.set_recv_buffer_capacity(kBufferSize);
1068
1069 StreamSink sink;
1070 std::unique_ptr<AsyncSocket> socket1 = absl::WrapUnique(
1071 ss_.CreateAsyncSocket(kIPv4AnyAddress.family(), SOCK_STREAM));
1072 std::unique_ptr<AsyncSocket> socket2 = absl::WrapUnique(
1073 ss_.CreateAsyncSocket(kIPv4AnyAddress.family(), SOCK_STREAM));
1074 sink.Monitor(socket1.get());
1075 sink.Monitor(socket2.get());
1076 socket1->Bind(kIPv4AnyAddress);
1077 socket2->Bind(kIPv4AnyAddress);
1078
1079 // Connect sockets.
1080 EXPECT_EQ(0, socket1->Connect(socket2->GetLocalAddress()));
1081 EXPECT_EQ(0, socket2->Connect(socket1->GetLocalAddress()));
1082 ss_.ProcessMessagesUntilIdle();
1083
1084 char data[kBufferSize] = {};
1085
1086 // First Send call will fill the send buffer but not send anything.
1087 ss_.SetSendingBlocked(true);
1088 EXPECT_EQ(static_cast<int>(kBufferSize), socket1->Send(data, kBufferSize));
1089 ss_.ProcessMessagesUntilIdle();
1090 EXPECT_FALSE(sink.Check(socket1.get(), SSE_WRITE));
1091 EXPECT_FALSE(sink.Check(socket2.get(), SSE_READ));
1092 EXPECT_FALSE(socket1->IsBlocking());
1093
1094 // Since the send buffer is full, next Send will result in EWOULDBLOCK.
1095 EXPECT_EQ(-1, socket1->Send(data, kBufferSize));
1096 EXPECT_FALSE(sink.Check(socket1.get(), SSE_WRITE));
1097 EXPECT_FALSE(sink.Check(socket2.get(), SSE_READ));
1098 EXPECT_TRUE(socket1->IsBlocking());
1099
1100 // When sending is unblocked, the buffered data should be sent and
1101 // SignalWriteEvent should fire.
1102 ss_.SetSendingBlocked(false);
1103 ss_.ProcessMessagesUntilIdle();
1104 EXPECT_TRUE(sink.Check(socket1.get(), SSE_WRITE));
1105 EXPECT_TRUE(sink.Check(socket2.get(), SSE_READ));
1106 }
1107
TEST_F(VirtualSocketServerTest,CreatesStandardDistribution)1108 TEST_F(VirtualSocketServerTest, CreatesStandardDistribution) {
1109 const uint32_t kTestMean[] = {10, 100, 333, 1000};
1110 const double kTestDev[] = {0.25, 0.1, 0.01};
1111 // TODO(deadbeef): The current code only works for 1000 data points or more.
1112 const uint32_t kTestSamples[] = {/*10, 100,*/ 1000};
1113 for (size_t midx = 0; midx < arraysize(kTestMean); ++midx) {
1114 for (size_t didx = 0; didx < arraysize(kTestDev); ++didx) {
1115 for (size_t sidx = 0; sidx < arraysize(kTestSamples); ++sidx) {
1116 ASSERT_LT(0u, kTestSamples[sidx]);
1117 const uint32_t kStdDev =
1118 static_cast<uint32_t>(kTestDev[didx] * kTestMean[midx]);
1119 VirtualSocketServer::Function* f =
1120 VirtualSocketServer::CreateDistribution(kTestMean[midx], kStdDev,
1121 kTestSamples[sidx]);
1122 ASSERT_TRUE(nullptr != f);
1123 ASSERT_EQ(kTestSamples[sidx], f->size());
1124 double sum = 0;
1125 for (uint32_t i = 0; i < f->size(); ++i) {
1126 sum += (*f)[i].second;
1127 }
1128 const double mean = sum / f->size();
1129 double sum_sq_dev = 0;
1130 for (uint32_t i = 0; i < f->size(); ++i) {
1131 double dev = (*f)[i].second - mean;
1132 sum_sq_dev += dev * dev;
1133 }
1134 const double stddev = sqrt(sum_sq_dev / f->size());
1135 EXPECT_NEAR(kTestMean[midx], mean, 0.1 * kTestMean[midx])
1136 << "M=" << kTestMean[midx] << " SD=" << kStdDev
1137 << " N=" << kTestSamples[sidx];
1138 EXPECT_NEAR(kStdDev, stddev, 0.1 * kStdDev)
1139 << "M=" << kTestMean[midx] << " SD=" << kStdDev
1140 << " N=" << kTestSamples[sidx];
1141 delete f;
1142 }
1143 }
1144 }
1145 }
1146
1147 } // namespace
1148 } // namespace rtc
1149