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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif
#include "google_apis/gcm/engine/connection_handler_impl.h"
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/wire_format_lite.h"
#include "google_apis/gcm/base/mcs_util.h"
#include "google_apis/gcm/base/socket_stream.h"
#include "google_apis/gcm/protocol/mcs.pb.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/ip_address.h"
#include "net/base/network_anonymization_key.h"
#include "net/base/test_completion_callback.h"
#include "net/log/net_log_source.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/stream_socket.h"
#include "net/test/gtest_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_test_util.h"
#include "services/network/network_context.h"
#include "services/network/network_service.h"
#include "services/network/public/mojom/proxy_resolving_socket.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/origin.h"
namespace gcm {
namespace {
typedef std::unique_ptr<google::protobuf::MessageLite> ScopedMessage;
typedef std::vector<net::MockRead> ReadList;
typedef std::vector<net::MockWrite> WriteList;
const uint64_t kAuthId = 54321;
const uint64_t kAuthToken = 12345;
const char kMCSVersion = 41; // The protocol version.
const int kMCSPort = 5228; // The server port.
const char kDataMsgFrom[] = "data_from";
const char kDataMsgCategory[] = "data_category";
const char kDataMsgFrom2[] = "data_from2";
const char kDataMsgCategory2[] = "data_category2";
const char kDataMsgFromLong[] =
"this is a long from that will result in a message > 128 bytes";
const char kDataMsgCategoryLong[] =
"this is a long category that will result in a message > 128 bytes";
const char kDataMsgFromLong2[] =
"this is a second long from that will result in a message > 128 bytes";
const char kDataMsgCategoryLong2[] =
"this is a second long category that will result in a message > 128 bytes";
const uint8_t kInvalidTag = 100; // An invalid tag.
// ---- Helpers for building messages. ----
// Encode a protobuf packet with protobuf type |tag| and serialized protobuf
// bytes |proto| into the MCS message form (tag + varint size + bytes).
std::string EncodePacket(uint8_t tag, const std::string& proto) {
std::string result;
google::protobuf::io::StringOutputStream string_output_stream(&result);
{
google::protobuf::io::CodedOutputStream coded_output_stream(
&string_output_stream);
const unsigned char tag_byte[1] = { tag };
coded_output_stream.WriteRaw(tag_byte, 1);
coded_output_stream.WriteVarint32(proto.size());
coded_output_stream.WriteRaw(proto.c_str(), proto.size());
// ~CodedOutputStream must run before the move constructor at the
// return statement. http://crbug.com/338962
}
return result;
}
// Encode a handshake request into the MCS message form.
std::string EncodeHandshakeRequest() {
std::string result;
const char version_byte[1] = {kMCSVersion};
result.append(version_byte, 1);
ScopedMessage login_request(
BuildLoginRequest(kAuthId, kAuthToken, ""));
result.append(EncodePacket(kLoginRequestTag,
login_request->SerializeAsString()));
return result;
}
// Build a serialized login response protobuf.
std::string BuildLoginResponse() {
std::string result;
mcs_proto::LoginResponse login_response;
login_response.set_id("id");
result.append(login_response.SerializeAsString());
return result;
}
// Encoode a handshake response into the MCS message form.
std::string EncodeHandshakeResponse() {
std::string result;
const char version_byte[1] = {kMCSVersion};
result.append(version_byte, 1);
result.append(EncodePacket(kLoginResponseTag, BuildLoginResponse()));
return result;
}
// Build a serialized data message stanza protobuf.
std::string BuildDataMessage(const std::string& from,
const std::string& category) {
mcs_proto::DataMessageStanza data_message;
data_message.set_from(from);
data_message.set_category(category);
return data_message.SerializeAsString();
}
// Build a corrupt data message that will force the protobuf parser to backup
// after completion (useful in testing memory corruption cases due to a
// CodedInputStream going out of scope).
std::string BuildCorruptDataMessage() {
// Manually construct the message with invalid data. We set field 2 (id) to
// be an invalid string.
const int kMsgTag =
(2 << google::protobuf::internal::WireFormatLite::kTagTypeBits) |
google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
const int kStringLength = -1; // Corrupted length.
const char kStringData[] = "id";
std::string data_message_proto;
google::protobuf::io::StringOutputStream string_output_stream(
&data_message_proto);
{
google::protobuf::io::CodedOutputStream coded_output_stream(
&string_output_stream);
coded_output_stream.WriteVarint32(kMsgTag);
coded_output_stream.WriteVarint32(
static_cast<google::protobuf::uint32>(kStringLength));
coded_output_stream.WriteRaw(&kStringData, sizeof(kStringData));
// ~CodedOutputStream must run before the move constructor at the
// return statement. http://crbug.com/338962
}
return data_message_proto;
}
class GCMConnectionHandlerImplTest : public testing::Test {
public:
GCMConnectionHandlerImplTest();
~GCMConnectionHandlerImplTest() override;
void BuildSocket(const ReadList& read_list, const WriteList& write_list);
// Pump |run_loop_|, and reset |run_loop_| after completion.
void PumpLoop();
ConnectionHandlerImpl* connection_handler() {
return connection_handler_.get();
}
int last_error() const { return last_error_; }
// Initialize the connection handler, setting |dst_proto| as the destination
// for any received messages.
void Connect(ScopedMessage* dst_proto);
// Runs the message loop until a message is received.
void WaitForMessage();
mojo::Remote<network::mojom::ProxyResolvingSocket> mojo_socket_remote_;
private:
void ReadContinuation(ScopedMessage* dst_proto, ScopedMessage new_proto);
void WriteContinuation();
void ConnectionContinuation(int error);
// SocketStreams and their data provider.
std::vector<std::unique_ptr<net::StaticSocketDataProvider>> data_providers_;
std::vector<std::unique_ptr<net::SSLSocketDataProvider>> ssl_data_providers_;
// The connection handler being tested.
std::unique_ptr<ConnectionHandlerImpl> connection_handler_;
// The last connection error received.
int last_error_;
net::AddressList address_list_;
base::test::TaskEnvironment task_environment_;
std::unique_ptr<base::RunLoop> run_loop_;
std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier_;
std::unique_ptr<network::NetworkService> network_service_;
mojo::Remote<network::mojom::NetworkContext> network_context_remote_;
net::MockClientSocketFactory socket_factory_;
std::unique_ptr<net::URLRequestContext> url_request_context_;
std::unique_ptr<network::NetworkContext> network_context_;
mojo::Remote<network::mojom::ProxyResolvingSocketFactory>
mojo_socket_factory_remote_;
mojo::ScopedDataPipeConsumerHandle receive_pipe_handle_;
mojo::ScopedDataPipeProducerHandle send_pipe_handle_;
};
GCMConnectionHandlerImplTest::GCMConnectionHandlerImplTest()
: last_error_(0),
task_environment_(base::test::TaskEnvironment::MainThreadType::IO),
network_change_notifier_(
net::NetworkChangeNotifier::CreateMockIfNeeded()),
network_service_(network::NetworkService::CreateForTesting()) {
address_list_ = net::AddressList::CreateFromIPAddress(
net::IPAddress::IPv4Localhost(), kMCSPort);
socket_factory_.set_enable_read_if_ready(true);
auto context_builder = net::CreateTestURLRequestContextBuilder();
context_builder->set_client_socket_factory_for_testing(&socket_factory_);
url_request_context_ = context_builder->Build();
network_context_ = std::make_unique<network::NetworkContext>(
network_service_.get(),
network_context_remote_.BindNewPipeAndPassReceiver(),
url_request_context_.get(),
/*cors_exempt_header_list=*/std::vector<std::string>());
}
GCMConnectionHandlerImplTest::~GCMConnectionHandlerImplTest() {
}
void GCMConnectionHandlerImplTest::BuildSocket(const ReadList& read_list,
const WriteList& write_list) {
data_providers_.push_back(
std::make_unique<net::StaticSocketDataProvider>(read_list, write_list));
socket_factory_.AddSocketDataProvider(data_providers_.back().get());
ssl_data_providers_.push_back(
std::make_unique<net::SSLSocketDataProvider>(net::SYNCHRONOUS, net::OK));
socket_factory_.AddSSLSocketDataProvider(ssl_data_providers_.back().get());
run_loop_ = std::make_unique<base::RunLoop>();
mojo_socket_factory_remote_.reset();
network_context_->CreateProxyResolvingSocketFactory(
mojo_socket_factory_remote_.BindNewPipeAndPassReceiver());
base::RunLoop run_loop;
int net_error = net::ERR_FAILED;
const GURL kDestination("https://example.com");
network::mojom::ProxyResolvingSocketOptionsPtr options =
network::mojom::ProxyResolvingSocketOptions::New();
options->use_tls = true;
mojo_socket_remote_.reset();
const url::Origin kOrigin = url::Origin::Create(kDestination);
mojo_socket_factory_remote_->CreateProxyResolvingSocket(
kDestination,
net::NetworkAnonymizationKey::CreateSameSite(net::SchemefulSite(kOrigin)),
std::move(options),
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
mojo_socket_remote_.BindNewPipeAndPassReceiver(),
mojo::NullRemote() /* observer */,
base::BindLambdaForTesting(
[&](int result, const std::optional<net::IPEndPoint>& local_addr,
const std::optional<net::IPEndPoint>& peer_addr,
mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
mojo::ScopedDataPipeProducerHandle send_pipe_handle) {
net_error = result;
receive_pipe_handle_ = std::move(receive_pipe_handle);
send_pipe_handle_ = std::move(send_pipe_handle);
run_loop.Quit();
}));
run_loop.Run();
ASSERT_EQ(net::OK, net_error);
}
void GCMConnectionHandlerImplTest::PumpLoop() {
run_loop_->RunUntilIdle();
run_loop_ = std::make_unique<base::RunLoop>();
}
void GCMConnectionHandlerImplTest::Connect(
ScopedMessage* dst_proto) {
connection_handler_ = std::make_unique<ConnectionHandlerImpl>(
base::SingleThreadTaskRunner::GetCurrentDefault(),
TestTimeouts::tiny_timeout(),
base::BindRepeating(&GCMConnectionHandlerImplTest::ReadContinuation,
base::Unretained(this), dst_proto),
base::BindRepeating(&GCMConnectionHandlerImplTest::WriteContinuation,
base::Unretained(this)),
base::BindRepeating(&GCMConnectionHandlerImplTest::ConnectionContinuation,
base::Unretained(this)));
EXPECT_FALSE(connection_handler()->CanSendMessage());
connection_handler_->Init(*BuildLoginRequest(kAuthId, kAuthToken, ""),
std::move(receive_pipe_handle_),
std::move(send_pipe_handle_));
}
void GCMConnectionHandlerImplTest::ReadContinuation(
ScopedMessage* dst_proto,
ScopedMessage new_proto) {
*dst_proto = std::move(new_proto);
run_loop_->Quit();
}
void GCMConnectionHandlerImplTest::WaitForMessage() {
run_loop_->Run();
run_loop_ = std::make_unique<base::RunLoop>();
}
void GCMConnectionHandlerImplTest::WriteContinuation() {
run_loop_->Quit();
}
void GCMConnectionHandlerImplTest::ConnectionContinuation(int error) {
last_error_ = error;
if (error != net::OK)
connection_handler_->Reset();
run_loop_->Quit();
}
// Initialize the connection handler and ensure the handshake completes
// successfully.
TEST_F(GCMConnectionHandlerImplTest, Init) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
EXPECT_FALSE(connection_handler()->CanSendMessage());
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(BuildLoginResponse(), received_message->SerializeAsString());
EXPECT_TRUE(connection_handler()->CanSendMessage());
}
// Simulate the handshake response returning an older version. Initialization
// should fail.
TEST_F(GCMConnectionHandlerImplTest, InitFailedVersionCheck) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
// Overwrite the version byte.
handshake_response[0] = 37;
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response. Should result in a connection error.
EXPECT_FALSE(received_message.get());
EXPECT_FALSE(connection_handler()->CanSendMessage());
EXPECT_EQ(net::ERR_FAILED, last_error());
}
// Attempt to initialize, but receive no server response, resulting in a time
// out.
TEST_F(GCMConnectionHandlerImplTest, InitTimeout) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
ReadList read_list(1, net::MockRead(net::SYNCHRONOUS,
net::ERR_IO_PENDING));
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response. Should result in a connection error.
EXPECT_FALSE(received_message.get());
EXPECT_FALSE(connection_handler()->CanSendMessage());
EXPECT_EQ(net::ERR_TIMED_OUT, last_error());
}
// Attempt to initialize, but receive an incomplete server response, resulting
// in a time out.
TEST_F(GCMConnectionHandlerImplTest, InitIncompleteTimeout) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size() / 2));
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
net::ERR_IO_PENDING));
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response. Should result in a connection error.
EXPECT_FALSE(received_message.get());
EXPECT_FALSE(connection_handler()->CanSendMessage());
EXPECT_EQ(net::ERR_TIMED_OUT, last_error());
}
// Reinitialize the connection handler after failing to initialize.
TEST_F(GCMConnectionHandlerImplTest, ReInit) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
ReadList read_list(1, net::MockRead(net::SYNCHRONOUS,
net::ERR_IO_PENDING));
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response. Should result in a connection error.
EXPECT_FALSE(received_message.get());
EXPECT_FALSE(connection_handler()->CanSendMessage());
EXPECT_EQ(net::ERR_TIMED_OUT, last_error());
// Build a new socket and reconnect, successfully this time.
std::string handshake_response = EncodeHandshakeResponse();
WriteList write_list2(1, net::MockWrite(net::ASYNC, handshake_request.c_str(),
handshake_request.size()));
ReadList read_list2;
read_list2.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(),
handshake_response.size()));
read_list2.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list2, write_list2);
Connect(&received_message);
EXPECT_FALSE(connection_handler()->CanSendMessage());
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(BuildLoginResponse(), received_message->SerializeAsString());
EXPECT_TRUE(connection_handler()->CanSendMessage());
}
// Verify that messages can be received after initialization.
// Flaky on Linux (crbug.com/906093)
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_RecvMsg DISABLED_RecvMsg
#else
#define MAYBE_RecvMsg RecvMsg
#endif
TEST_F(GCMConnectionHandlerImplTest, MAYBE_RecvMsg) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto = BuildDataMessage(kDataMsgFrom,
kDataMsgCategory);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Verify that if two messages arrive at once, they're treated appropriately.
TEST_F(GCMConnectionHandlerImplTest, Recv2Msgs) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto = BuildDataMessage(kDataMsgFrom,
kDataMsgCategory);
std::string data_message_proto2 = BuildDataMessage(kDataMsgFrom2,
kDataMsgCategory2);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
data_message_pkt += EncodePacket(kDataMessageStanzaTag, data_message_proto2);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The first data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
received_message.reset();
WaitForMessage(); // The second data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto2, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Receive a long (>128 bytes) message.
TEST_F(GCMConnectionHandlerImplTest, RecvLongMsg) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto =
BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
DCHECK_GT(data_message_pkt.size(), 128U);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Receive a long (>128 bytes) message in two synchronous parts.
TEST_F(GCMConnectionHandlerImplTest, RecvLongMsg2Parts) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto =
BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
DCHECK_GT(data_message_pkt.size(), 128U);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
int bytes_in_first_message = data_message_pkt.size() / 2;
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
data_message_pkt.c_str(),
bytes_in_first_message));
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
data_message_pkt.c_str() +
bytes_in_first_message,
data_message_pkt.size() -
bytes_in_first_message));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(net::OK, last_error());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
}
// Receive two long (>128 bytes) message.
TEST_F(GCMConnectionHandlerImplTest, Recv2LongMsgs) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto =
BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong);
std::string data_message_proto2 =
BuildDataMessage(kDataMsgFromLong2, kDataMsgCategoryLong2);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
data_message_pkt += EncodePacket(kDataMessageStanzaTag, data_message_proto2);
DCHECK_GT(data_message_pkt.size(), 256U);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The first data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
received_message.reset();
WaitForMessage(); // The second data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto2, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Simulate a message where the end of the data does not arrive in time and the
// read times out.
TEST_F(GCMConnectionHandlerImplTest, ReadTimeout) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto = BuildDataMessage(kDataMsgFrom,
kDataMsgCategory);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
int bytes_in_first_message = data_message_pkt.size() / 2;
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
bytes_in_first_message));
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
net::ERR_IO_PENDING));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str() +
bytes_in_first_message,
data_message_pkt.size() -
bytes_in_first_message));
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
received_message.reset();
WaitForMessage(); // Should time out.
EXPECT_FALSE(received_message.get());
EXPECT_EQ(net::ERR_TIMED_OUT, last_error());
EXPECT_FALSE(connection_handler()->CanSendMessage());
}
// Receive a message with zero data bytes.
TEST_F(GCMConnectionHandlerImplTest, RecvMsgNoData) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_pkt = EncodePacket(kHeartbeatPingTag, "");
ASSERT_EQ(data_message_pkt.size(), 2U);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
received_message.reset();
WaitForMessage(); // The heartbeat ping.
EXPECT_TRUE(received_message.get());
EXPECT_EQ(GetMCSProtoTag(*received_message), kHeartbeatPingTag);
EXPECT_EQ(net::OK, last_error());
EXPECT_TRUE(connection_handler()->CanSendMessage());
}
// Send a message after performing the handshake.
TEST_F(GCMConnectionHandlerImplTest, SendMsg) {
mcs_proto::DataMessageStanza data_message;
data_message.set_from(kDataMsgFrom);
data_message.set_category(kDataMsgCategory);
std::string handshake_request = EncodeHandshakeRequest();
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message.SerializeAsString());
WriteList write_list;
write_list.push_back(net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
write_list.push_back(net::MockWrite(net::ASYNC,
data_message_pkt.c_str(),
data_message_pkt.size()));
std::string handshake_response = EncodeHandshakeResponse();
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING));
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
EXPECT_TRUE(connection_handler()->CanSendMessage());
connection_handler()->SendMessage(data_message);
EXPECT_FALSE(connection_handler()->CanSendMessage());
WaitForMessage(); // The message send.
EXPECT_TRUE(connection_handler()->CanSendMessage());
}
// Attempt to send a message after the socket is disconnected due to a timeout.
TEST_F(GCMConnectionHandlerImplTest, SendMsgSocketDisconnected) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list;
write_list.push_back(net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING));
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
EXPECT_TRUE(connection_handler()->CanSendMessage());
mojo_socket_remote_.reset();
mcs_proto::DataMessageStanza data_message;
data_message.set_from(kDataMsgFrom);
data_message.set_category(kDataMsgCategory);
connection_handler()->SendMessage(data_message);
EXPECT_FALSE(connection_handler()->CanSendMessage());
WaitForMessage(); // The message send. Should result in an error
EXPECT_FALSE(connection_handler()->CanSendMessage());
EXPECT_EQ(net::ERR_FAILED, last_error());
}
// Receive a message with a custom data packet that is larger than the
// default data limit (and the socket buffer limit). Should successfully
// read the packet by using the in-memory buffer.
TEST_F(GCMConnectionHandlerImplTest, ExtraLargeDataPacket) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
const std::string kVeryLongFrom(20000, '0');
std::string data_message_proto = BuildDataMessage(kVeryLongFrom,
kDataMsgCategory);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Receive two messages with a custom data packet that is larger than the
// default data limit (and the socket buffer limit). Should successfully
// read the packet by using the in-memory buffer.
TEST_F(GCMConnectionHandlerImplTest, 2ExtraLargeDataPacketMsgs) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
const std::string kVeryLongFrom(20000, '0');
std::string data_message_proto = BuildDataMessage(kVeryLongFrom,
kDataMsgCategory);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS,
data_message_pkt.c_str(),
data_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
received_message.reset();
WaitForMessage(); // The second data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Make sure a message with an invalid tag is handled gracefully and resets
// the connection with an invalid argument error.
TEST_F(GCMConnectionHandlerImplTest, InvalidTag) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string invalid_message = "0";
std::string invalid_message_pkt =
EncodePacket(kInvalidTag, invalid_message);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC,
invalid_message_pkt.c_str(),
invalid_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
received_message.reset();
WaitForMessage(); // The invalid message.
EXPECT_FALSE(received_message.get());
EXPECT_EQ(net::ERR_INVALID_ARGUMENT, last_error());
}
// Receive a message where the size field spans two socket reads.
TEST_F(GCMConnectionHandlerImplTest, RecvMsgSplitSize) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC,
handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto =
BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong);
std::string data_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
DCHECK_GT(data_message_pkt.size(), 128U);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC,
handshake_response.c_str(),
handshake_response.size()));
// The first two bytes are the tag byte and the first byte of the size packet.
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str(),
2));
// Start from the second byte of the size packet.
read_list.push_back(net::MockRead(net::ASYNC,
data_message_pkt.c_str() + 2,
data_message_pkt.size() - 2));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
WaitForMessage(); // The data message.
ASSERT_TRUE(received_message.get());
EXPECT_EQ(data_message_proto, received_message->SerializeAsString());
EXPECT_EQ(net::OK, last_error());
}
// Make sure a message with invalid data is handled gracefully and resets
// the connection with a FAILED error.
TEST_F(GCMConnectionHandlerImplTest, InvalidData) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto = BuildCorruptDataMessage();
std::string invalid_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC, invalid_message_pkt.c_str(),
invalid_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
received_message.reset();
WaitForMessage(); // The invalid message.
EXPECT_FALSE(received_message.get());
EXPECT_EQ(net::ERR_FAILED, last_error());
}
// Make sure a long message with invalid data is handled gracefully and resets
// the connection with a FAILED error.
TEST_F(GCMConnectionHandlerImplTest, InvalidDataLong) {
std::string handshake_request = EncodeHandshakeRequest();
WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(),
handshake_request.size()));
std::string handshake_response = EncodeHandshakeResponse();
std::string data_message_proto = BuildCorruptDataMessage();
// Pad the corrupt data so it's beyond the normal single packet length.
data_message_proto.resize(1 << 12);
std::string invalid_message_pkt =
EncodePacket(kDataMessageStanzaTag, data_message_proto);
ReadList read_list;
read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(),
handshake_response.size()));
read_list.push_back(net::MockRead(net::ASYNC, invalid_message_pkt.c_str(),
invalid_message_pkt.size()));
read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::OK) /* EOF */);
BuildSocket(read_list, write_list);
ScopedMessage received_message;
Connect(&received_message);
WaitForMessage(); // The login send.
WaitForMessage(); // The login response.
received_message.reset();
WaitForMessage(); // The invalid message.
EXPECT_FALSE(received_message.get());
EXPECT_EQ(net::ERR_FAILED, last_error());
}
} // namespace
} // namespace gcm
|