socket_test_util.h revision 731df977c0511bca2206b5f333555b1205ff1f43
1// Copyright (c) 2010 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#ifndef NET_SOCKET_SOCKET_TEST_UTIL_H_ 6#define NET_SOCKET_SOCKET_TEST_UTIL_H_ 7#pragma once 8 9#include <cstring> 10#include <deque> 11#include <string> 12#include <vector> 13 14#include "base/basictypes.h" 15#include "base/callback.h" 16#include "base/logging.h" 17#include "base/scoped_ptr.h" 18#include "base/scoped_vector.h" 19#include "base/string16.h" 20#include "base/weak_ptr.h" 21#include "net/base/address_list.h" 22#include "net/base/io_buffer.h" 23#include "net/base/net_errors.h" 24#include "net/base/net_log.h" 25#include "net/base/ssl_config_service.h" 26#include "net/base/test_completion_callback.h" 27#include "net/http/http_auth_controller.h" 28#include "net/http/http_proxy_client_socket_pool.h" 29#include "net/socket/client_socket_factory.h" 30#include "net/socket/client_socket_handle.h" 31#include "net/socket/socks_client_socket_pool.h" 32#include "net/socket/ssl_client_socket.h" 33#include "net/socket/ssl_client_socket_pool.h" 34#include "net/socket/tcp_client_socket_pool.h" 35#include "testing/gtest/include/gtest/gtest.h" 36 37namespace net { 38 39enum { 40 // A private network error code used by the socket test utility classes. 41 // If the |result| member of a MockRead is 42 // ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a 43 // marker that indicates the peer will close the connection after the next 44 // MockRead. The other members of that MockRead are ignored. 45 ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ = -10000, 46}; 47 48class ClientSocket; 49class MockClientSocket; 50class SSLClientSocket; 51class SSLHostInfo; 52 53struct MockConnect { 54 // Asynchronous connection success. 55 MockConnect() : async(true), result(OK) { } 56 MockConnect(bool a, int r) : async(a), result(r) { } 57 58 bool async; 59 int result; 60}; 61 62struct MockRead { 63 // Flag to indicate that the message loop should be terminated. 64 enum { 65 STOPLOOP = 1 << 31 66 }; 67 68 // Default 69 MockRead() : async(false), result(0), data(NULL), data_len(0), 70 sequence_number(0), time_stamp(base::Time::Now()) {} 71 72 // Read failure (no data). 73 MockRead(bool async, int result) : async(async) , result(result), data(NULL), 74 data_len(0), sequence_number(0), time_stamp(base::Time::Now()) { } 75 76 // Read failure (no data), with sequence information. 77 MockRead(bool async, int result, int seq) : async(async) , result(result), 78 data(NULL), data_len(0), sequence_number(seq), 79 time_stamp(base::Time::Now()) { } 80 81 // Asynchronous read success (inferred data length). 82 explicit MockRead(const char* data) : async(true), result(0), data(data), 83 data_len(strlen(data)), sequence_number(0), 84 time_stamp(base::Time::Now()) { } 85 86 // Read success (inferred data length). 87 MockRead(bool async, const char* data) : async(async), result(0), data(data), 88 data_len(strlen(data)), sequence_number(0), 89 time_stamp(base::Time::Now()) { } 90 91 // Read success. 92 MockRead(bool async, const char* data, int data_len) : async(async), 93 result(0), data(data), data_len(data_len), sequence_number(0), 94 time_stamp(base::Time::Now()) { } 95 96 // Read success (inferred data length) with sequence information. 97 MockRead(bool async, int seq, const char* data) : async(async), 98 result(0), data(data), data_len(strlen(data)), sequence_number(seq), 99 time_stamp(base::Time::Now()) { } 100 101 // Read success with sequence information. 102 MockRead(bool async, const char* data, int data_len, int seq) : async(async), 103 result(0), data(data), data_len(data_len), sequence_number(seq), 104 time_stamp(base::Time::Now()) { } 105 106 bool async; 107 int result; 108 const char* data; 109 int data_len; 110 111 // For OrderedSocketData, which only allows reads to occur in a particular 112 // sequence. If a read occurs before the given |sequence_number| is reached, 113 // an ERR_IO_PENDING is returned. 114 int sequence_number; // The sequence number at which a read is allowed 115 // to occur. 116 base::Time time_stamp; // The time stamp at which the operation occurred. 117}; 118 119// MockWrite uses the same member fields as MockRead, but with different 120// meanings. The expected input to MockTCPClientSocket::Write() is given 121// by {data, data_len}, and the return value of Write() is controlled by 122// {async, result}. 123typedef MockRead MockWrite; 124 125struct MockWriteResult { 126 MockWriteResult(bool async, int result) : async(async), result(result) {} 127 128 bool async; 129 int result; 130}; 131 132// The SocketDataProvider is an interface used by the MockClientSocket 133// for getting data about individual reads and writes on the socket. 134class SocketDataProvider { 135 public: 136 SocketDataProvider() : socket_(NULL) {} 137 138 virtual ~SocketDataProvider() {} 139 140 // Returns the buffer and result code for the next simulated read. 141 // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller 142 // that it will be called via the MockClientSocket::OnReadComplete() 143 // function at a later time. 144 virtual MockRead GetNextRead() = 0; 145 virtual MockWriteResult OnWrite(const std::string& data) = 0; 146 virtual void Reset() = 0; 147 148 // Accessor for the socket which is using the SocketDataProvider. 149 MockClientSocket* socket() { return socket_; } 150 void set_socket(MockClientSocket* socket) { socket_ = socket; } 151 152 MockConnect connect_data() const { return connect_; } 153 void set_connect_data(const MockConnect& connect) { connect_ = connect; } 154 155 private: 156 MockConnect connect_; 157 MockClientSocket* socket_; 158 159 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider); 160}; 161 162// SocketDataProvider which responds based on static tables of mock reads and 163// writes. 164class StaticSocketDataProvider : public SocketDataProvider { 165 public: 166 StaticSocketDataProvider(); 167 StaticSocketDataProvider(MockRead* reads, size_t reads_count, 168 MockWrite* writes, size_t writes_count); 169 virtual ~StaticSocketDataProvider(); 170 171 // SocketDataProvider methods: 172 virtual MockRead GetNextRead(); 173 virtual MockWriteResult OnWrite(const std::string& data); 174 virtual void Reset(); 175 176 // These functions get access to the next available read and write data. 177 const MockRead& PeekRead() const; 178 const MockWrite& PeekWrite() const; 179 // These functions get random access to the read and write data, for timing. 180 const MockRead& PeekRead(size_t index) const; 181 const MockWrite& PeekWrite(size_t index) const; 182 size_t read_index() const { return read_index_; } 183 size_t write_index() const { return write_index_; } 184 size_t read_count() const { return read_count_; } 185 size_t write_count() const { return write_count_; } 186 187 bool at_read_eof() const { return read_index_ >= read_count_; } 188 bool at_write_eof() const { return write_index_ >= write_count_; } 189 190 private: 191 MockRead* reads_; 192 size_t read_index_; 193 size_t read_count_; 194 MockWrite* writes_; 195 size_t write_index_; 196 size_t write_count_; 197 198 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider); 199}; 200 201// SocketDataProvider which can make decisions about next mock reads based on 202// received writes. It can also be used to enforce order of operations, for 203// example that tested code must send the "Hello!" message before receiving 204// response. This is useful for testing conversation-like protocols like FTP. 205class DynamicSocketDataProvider : public SocketDataProvider { 206 public: 207 DynamicSocketDataProvider(); 208 virtual ~DynamicSocketDataProvider(); 209 210 // SocketDataProvider methods: 211 virtual MockRead GetNextRead(); 212 virtual MockWriteResult OnWrite(const std::string& data) = 0; 213 virtual void Reset(); 214 215 int short_read_limit() const { return short_read_limit_; } 216 void set_short_read_limit(int limit) { short_read_limit_ = limit; } 217 218 void allow_unconsumed_reads(bool allow) { allow_unconsumed_reads_ = allow; } 219 220 protected: 221 // The next time there is a read from this socket, it will return |data|. 222 // Before calling SimulateRead next time, the previous data must be consumed. 223 void SimulateRead(const char* data, size_t length); 224 void SimulateRead(const char* data) { 225 SimulateRead(data, std::strlen(data)); 226 } 227 228 private: 229 std::deque<MockRead> reads_; 230 231 // Max number of bytes we will read at a time. 0 means no limit. 232 int short_read_limit_; 233 234 // If true, we'll not require the client to consume all data before we 235 // mock the next read. 236 bool allow_unconsumed_reads_; 237 238 DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider); 239}; 240 241// SSLSocketDataProviders only need to keep track of the return code from calls 242// to Connect(). 243struct SSLSocketDataProvider { 244 SSLSocketDataProvider(bool async, int result) 245 : connect(async, result), 246 next_proto_status(SSLClientSocket::kNextProtoUnsupported), 247 was_npn_negotiated(false) { } 248 249 MockConnect connect; 250 SSLClientSocket::NextProtoStatus next_proto_status; 251 std::string next_proto; 252 bool was_npn_negotiated; 253}; 254 255// A DataProvider where the client must write a request before the reads (e.g. 256// the response) will complete. 257class DelayedSocketData : public StaticSocketDataProvider, 258 public base::RefCounted<DelayedSocketData> { 259 public: 260 // |write_delay| the number of MockWrites to complete before allowing 261 // a MockRead to complete. 262 // |reads| the list of MockRead completions. 263 // |writes| the list of MockWrite completions. 264 // Note: All MockReads and MockWrites must be async. 265 // Note: The MockRead and MockWrite lists musts end with a EOF 266 // e.g. a MockRead(true, 0, 0); 267 DelayedSocketData(int write_delay, 268 MockRead* reads, size_t reads_count, 269 MockWrite* writes, size_t writes_count); 270 271 // |connect| the result for the connect phase. 272 // |reads| the list of MockRead completions. 273 // |write_delay| the number of MockWrites to complete before allowing 274 // a MockRead to complete. 275 // |writes| the list of MockWrite completions. 276 // Note: All MockReads and MockWrites must be async. 277 // Note: The MockRead and MockWrite lists musts end with a EOF 278 // e.g. a MockRead(true, 0, 0); 279 DelayedSocketData(const MockConnect& connect, int write_delay, 280 MockRead* reads, size_t reads_count, 281 MockWrite* writes, size_t writes_count); 282 ~DelayedSocketData(); 283 284 virtual MockRead GetNextRead(); 285 virtual MockWriteResult OnWrite(const std::string& data); 286 virtual void Reset(); 287 void CompleteRead(); 288 void ForceNextRead(); 289 290 private: 291 int write_delay_; 292 ScopedRunnableMethodFactory<DelayedSocketData> factory_; 293}; 294 295// A DataProvider where the reads are ordered. 296// If a read is requested before its sequence number is reached, we return an 297// ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to 298// wait). 299// The sequence number is incremented on every read and write operation. 300// The message loop may be interrupted by setting the high bit of the sequence 301// number in the MockRead's sequence number. When that MockRead is reached, 302// we post a Quit message to the loop. This allows us to interrupt the reading 303// of data before a complete message has arrived, and provides support for 304// testing server push when the request is issued while the response is in the 305// middle of being received. 306class OrderedSocketData : public StaticSocketDataProvider, 307 public base::RefCounted<OrderedSocketData> { 308 public: 309 // |reads| the list of MockRead completions. 310 // |writes| the list of MockWrite completions. 311 // Note: All MockReads and MockWrites must be async. 312 // Note: The MockRead and MockWrite lists musts end with a EOF 313 // e.g. a MockRead(true, 0, 0); 314 OrderedSocketData(MockRead* reads, size_t reads_count, 315 MockWrite* writes, size_t writes_count); 316 317 // |connect| the result for the connect phase. 318 // |reads| the list of MockRead completions. 319 // |writes| the list of MockWrite completions. 320 // Note: All MockReads and MockWrites must be async. 321 // Note: The MockRead and MockWrite lists musts end with a EOF 322 // e.g. a MockRead(true, 0, 0); 323 OrderedSocketData(const MockConnect& connect, 324 MockRead* reads, size_t reads_count, 325 MockWrite* writes, size_t writes_count); 326 327 virtual MockRead GetNextRead(); 328 virtual MockWriteResult OnWrite(const std::string& data); 329 virtual void Reset(); 330 void SetCompletionCallback(CompletionCallback* callback) { 331 callback_ = callback; 332 } 333 334 // Posts a quit message to the current message loop, if one is running. 335 void EndLoop(); 336 337 void CompleteRead(); 338 339 private: 340 friend class base::RefCounted<OrderedSocketData>; 341 virtual ~OrderedSocketData(); 342 343 int sequence_number_; 344 int loop_stop_stage_; 345 CompletionCallback* callback_; 346 bool blocked_; 347 ScopedRunnableMethodFactory<OrderedSocketData> factory_; 348}; 349 350class DeterministicMockTCPClientSocket; 351 352// This class gives the user full control over the network activity, 353// specifically the timing of the COMPLETION of I/O operations. Regardless of 354// the order in which I/O operations are initiated, this class ensures that they 355// complete in the correct order. 356// 357// Network activity is modeled as a sequence of numbered steps which is 358// incremented whenever an I/O operation completes. This can happen under two 359// different circumstances: 360// 361// 1) Performing a synchronous I/O operation. (Invoking Read() or Write() 362// when the corresponding MockRead or MockWrite is marked !async). 363// 2) Running the Run() method of this class. The run method will invoke 364// the current MessageLoop, running all pending events, and will then 365// invoke any pending IO callbacks. 366// 367// In addition, this class allows for I/O processing to "stop" at a specified 368// step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation 369// by calling Read() or Write() while stopped is permitted if the operation is 370// asynchronous. It is an error to perform synchronous I/O while stopped. 371// 372// When creating the MockReads and MockWrites, note that the sequence number 373// refers to the number of the step in which the I/O will complete. In the 374// case of synchronous I/O, this will be the same step as the I/O is initiated. 375// However, in the case of asynchronous I/O, this I/O may be initiated in 376// a much earlier step. Furthermore, when the a Read() or Write() is separated 377// from its completion by other Read() or Writes()'s, it can not be marked 378// synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a 379// synchronous Read() or Write() could not be completed synchronously because of 380// the specific ordering constraints. 381// 382// Sequence numbers are preserved across both reads and writes. There should be 383// no gaps in sequence numbers, and no repeated sequence numbers. i.e. 384// MockRead reads[] = { 385// MockRead(false, "first read", length, 0) // sync 386// MockRead(true, "second read", length, 2) // async 387// }; 388// MockWrite writes[] = { 389// MockWrite(true, "first write", length, 1), // async 390// MockWrite(false, "second write", length, 3), // sync 391// }; 392// 393// Example control flow: 394// Read() is called. The current step is 0. The first available read is 395// synchronous, so the call to Read() returns length. The current step is 396// now 1. Next, Read() is called again. The next available read can 397// not be completed until step 2, so Read() returns ERR_IO_PENDING. The current 398// step is still 1. Write is called(). The first available write is able to 399// complete in this step, but is marked asynchronous. Write() returns 400// ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is 401// called which will cause the write callback to be invoked, and will then 402// stop. The current state is now 2. RunFor(1) is called again, which 403// causes the read callback to be invoked, and will then stop. Then current 404// step is 2. Write() is called again. Then next available write is 405// synchronous so the call to Write() returns length. 406// 407// For examples of how to use this class, see: 408// deterministic_socket_data_unittests.cc 409class DeterministicSocketData : public StaticSocketDataProvider, 410 public base::RefCounted<DeterministicSocketData> { 411 public: 412 // |reads| the list of MockRead completions. 413 // |writes| the list of MockWrite completions. 414 DeterministicSocketData(MockRead* reads, size_t reads_count, 415 MockWrite* writes, size_t writes_count); 416 417 // When the socket calls Read(), that calls GetNextRead(), and expects either 418 // ERR_IO_PENDING or data. 419 virtual MockRead GetNextRead(); 420 421 // When the socket calls Write(), it always completes synchronously. OnWrite() 422 // checks to make sure the written data matches the expected data. The 423 // callback will not be invoked until its sequence number is reached. 424 virtual MockWriteResult OnWrite(const std::string& data); 425 426 virtual void Reset(); 427 428 // Consume all the data up to the give stop point (via SetStop()). 429 void Run(); 430 431 // Set the stop point to be |steps| from now, and then invoke Run(). 432 void RunFor(int steps); 433 434 // Stop at step |seq|, which must be in the future. 435 virtual void SetStop(int seq) { 436 DCHECK_LT(sequence_number_, seq); 437 stopping_sequence_number_ = seq; 438 stopped_ = false; 439 } 440 441 // Stop |seq| steps after the current step. 442 virtual void StopAfter(int seq) { 443 SetStop(sequence_number_ + seq); 444 } 445 void CompleteRead(); 446 bool stopped() const { return stopped_; } 447 void SetStopped(bool val) { stopped_ = val; } 448 MockRead& current_read() { return current_read_; } 449 MockRead& current_write() { return current_write_; } 450 int sequence_number() const { return sequence_number_; } 451 void set_socket(base::WeakPtr<DeterministicMockTCPClientSocket> socket) { 452 socket_ = socket; 453 } 454 455 private: 456 // Invoke the read and write callbacks, if the timing is appropriate. 457 void InvokeCallbacks(); 458 459 void NextStep(); 460 461 int sequence_number_; 462 MockRead current_read_; 463 MockWrite current_write_; 464 int stopping_sequence_number_; 465 bool stopped_; 466 base::WeakPtr<DeterministicMockTCPClientSocket> socket_; 467 bool print_debug_; 468}; 469 470 471// Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}ClientSocket 472// objects get instantiated, they take their data from the i'th element of this 473// array. 474template<typename T> 475class SocketDataProviderArray { 476 public: 477 SocketDataProviderArray() : next_index_(0) { 478 } 479 480 T* GetNext() { 481 DCHECK_LT(next_index_, data_providers_.size()); 482 return data_providers_[next_index_++]; 483 } 484 485 void Add(T* data_provider) { 486 DCHECK(data_provider); 487 data_providers_.push_back(data_provider); 488 } 489 490 void ResetNextIndex() { 491 next_index_ = 0; 492 } 493 494 private: 495 // Index of the next |data_providers_| element to use. Not an iterator 496 // because those are invalidated on vector reallocation. 497 size_t next_index_; 498 499 // SocketDataProviders to be returned. 500 std::vector<T*> data_providers_; 501}; 502 503class MockTCPClientSocket; 504class MockSSLClientSocket; 505 506// ClientSocketFactory which contains arrays of sockets of each type. 507// You should first fill the arrays using AddMock{SSL,}Socket. When the factory 508// is asked to create a socket, it takes next entry from appropriate array. 509// You can use ResetNextMockIndexes to reset that next entry index for all mock 510// socket types. 511class MockClientSocketFactory : public ClientSocketFactory { 512 public: 513 MockClientSocketFactory(); 514 virtual ~MockClientSocketFactory(); 515 516 void AddSocketDataProvider(SocketDataProvider* socket); 517 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket); 518 void ResetNextMockIndexes(); 519 520 // Return |index|-th MockTCPClientSocket (starting from 0) that the factory 521 // created. 522 MockTCPClientSocket* GetMockTCPClientSocket(size_t index) const; 523 524 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory 525 // created. 526 MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const; 527 528 // ClientSocketFactory 529 virtual ClientSocket* CreateTCPClientSocket( 530 const AddressList& addresses, 531 NetLog* net_log, 532 const NetLog::Source& source); 533 virtual SSLClientSocket* CreateSSLClientSocket( 534 ClientSocketHandle* transport_socket, 535 const std::string& hostname, 536 const SSLConfig& ssl_config, 537 SSLHostInfo* ssl_host_info); 538 SocketDataProviderArray<SocketDataProvider>& mock_data() { 539 return mock_data_; 540 } 541 std::vector<MockTCPClientSocket*>& tcp_client_sockets() { 542 return tcp_client_sockets_; 543 } 544 545 private: 546 SocketDataProviderArray<SocketDataProvider> mock_data_; 547 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_; 548 549 // Store pointers to handed out sockets in case the test wants to get them. 550 std::vector<MockTCPClientSocket*> tcp_client_sockets_; 551 std::vector<MockSSLClientSocket*> ssl_client_sockets_; 552}; 553 554class MockClientSocket : public net::SSLClientSocket { 555 public: 556 explicit MockClientSocket(net::NetLog* net_log); 557 // ClientSocket methods: 558 virtual int Connect(net::CompletionCallback* callback) = 0; 559 virtual void Disconnect(); 560 virtual bool IsConnected() const; 561 virtual bool IsConnectedAndIdle() const; 562 virtual int GetPeerAddress(AddressList* address) const; 563 virtual const BoundNetLog& NetLog() const { return net_log_;} 564 virtual void SetSubresourceSpeculation() {} 565 virtual void SetOmniboxSpeculation() {} 566 567 // SSLClientSocket methods: 568 virtual void GetSSLInfo(net::SSLInfo* ssl_info); 569 virtual void GetSSLCertRequestInfo( 570 net::SSLCertRequestInfo* cert_request_info); 571 virtual NextProtoStatus GetNextProto(std::string* proto); 572 573 // Socket methods: 574 virtual int Read(net::IOBuffer* buf, int buf_len, 575 net::CompletionCallback* callback) = 0; 576 virtual int Write(net::IOBuffer* buf, int buf_len, 577 net::CompletionCallback* callback) = 0; 578 virtual bool SetReceiveBufferSize(int32 size) { return true; } 579 virtual bool SetSendBufferSize(int32 size) { return true; } 580 581 // If an async IO is pending because the SocketDataProvider returned 582 // ERR_IO_PENDING, then the MockClientSocket waits until this OnReadComplete 583 // is called to complete the asynchronous read operation. 584 // data.async is ignored, and this read is completed synchronously as 585 // part of this call. 586 virtual void OnReadComplete(const MockRead& data) = 0; 587 588 protected: 589 virtual ~MockClientSocket() {} 590 void RunCallbackAsync(net::CompletionCallback* callback, int result); 591 void RunCallback(net::CompletionCallback*, int result); 592 593 ScopedRunnableMethodFactory<MockClientSocket> method_factory_; 594 595 // True if Connect completed successfully and Disconnect hasn't been called. 596 bool connected_; 597 598 net::BoundNetLog net_log_; 599}; 600 601class MockTCPClientSocket : public MockClientSocket { 602 public: 603 MockTCPClientSocket(const net::AddressList& addresses, net::NetLog* net_log, 604 net::SocketDataProvider* socket); 605 606 // ClientSocket methods: 607 virtual int Connect(net::CompletionCallback* callback); 608 virtual void Disconnect(); 609 virtual bool IsConnected() const; 610 virtual bool IsConnectedAndIdle() const { return IsConnected(); } 611 virtual bool WasEverUsed() const { return was_used_to_convey_data_; } 612 613 // Socket methods: 614 virtual int Read(net::IOBuffer* buf, int buf_len, 615 net::CompletionCallback* callback); 616 virtual int Write(net::IOBuffer* buf, int buf_len, 617 net::CompletionCallback* callback); 618 619 virtual void OnReadComplete(const MockRead& data); 620 621 net::AddressList addresses() const { return addresses_; } 622 623 private: 624 int CompleteRead(); 625 626 net::AddressList addresses_; 627 628 net::SocketDataProvider* data_; 629 int read_offset_; 630 net::MockRead read_data_; 631 bool need_read_data_; 632 633 // True if the peer has closed the connection. This allows us to simulate 634 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real 635 // TCPClientSocket. 636 bool peer_closed_connection_; 637 638 // While an asynchronous IO is pending, we save our user-buffer state. 639 net::IOBuffer* pending_buf_; 640 int pending_buf_len_; 641 net::CompletionCallback* pending_callback_; 642 bool was_used_to_convey_data_; 643}; 644 645class DeterministicMockTCPClientSocket : public MockClientSocket, 646 public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> { 647 public: 648 DeterministicMockTCPClientSocket(net::NetLog* net_log, 649 net::DeterministicSocketData* data); 650 651 // ClientSocket methods: 652 virtual int Connect(net::CompletionCallback* callback); 653 virtual void Disconnect(); 654 virtual bool IsConnected() const; 655 virtual bool IsConnectedAndIdle() const { return IsConnected(); } 656 virtual bool WasEverUsed() const { return was_used_to_convey_data_; } 657 658 // Socket methods: 659 virtual int Write(net::IOBuffer* buf, int buf_len, 660 net::CompletionCallback* callback); 661 virtual int Read(net::IOBuffer* buf, int buf_len, 662 net::CompletionCallback* callback); 663 664 bool write_pending() const { return write_pending_; } 665 bool read_pending() const { return read_pending_; } 666 667 void CompleteWrite(); 668 int CompleteRead(); 669 void OnReadComplete(const MockRead& data); 670 671 private: 672 bool write_pending_; 673 net::CompletionCallback* write_callback_; 674 int write_result_; 675 676 net::MockRead read_data_; 677 678 net::IOBuffer* read_buf_; 679 int read_buf_len_; 680 bool read_pending_; 681 net::CompletionCallback* read_callback_; 682 net::DeterministicSocketData* data_; 683 bool was_used_to_convey_data_; 684}; 685 686class MockSSLClientSocket : public MockClientSocket { 687 public: 688 MockSSLClientSocket( 689 net::ClientSocketHandle* transport_socket, 690 const std::string& hostname, 691 const net::SSLConfig& ssl_config, 692 SSLHostInfo* ssl_host_info, 693 net::SSLSocketDataProvider* socket); 694 ~MockSSLClientSocket(); 695 696 // ClientSocket methods: 697 virtual int Connect(net::CompletionCallback* callback); 698 virtual void Disconnect(); 699 virtual bool IsConnected() const; 700 virtual bool WasEverUsed() const; 701 702 // Socket methods: 703 virtual int Read(net::IOBuffer* buf, int buf_len, 704 net::CompletionCallback* callback); 705 virtual int Write(net::IOBuffer* buf, int buf_len, 706 net::CompletionCallback* callback); 707 708 // SSLClientSocket methods: 709 virtual void GetSSLInfo(net::SSLInfo* ssl_info); 710 virtual NextProtoStatus GetNextProto(std::string* proto); 711 virtual bool was_npn_negotiated() const; 712 virtual bool set_was_npn_negotiated(bool negotiated); 713 714 // This MockSocket does not implement the manual async IO feature. 715 virtual void OnReadComplete(const MockRead& data) { NOTIMPLEMENTED(); } 716 717 private: 718 class ConnectCallback; 719 720 scoped_ptr<ClientSocketHandle> transport_; 721 net::SSLSocketDataProvider* data_; 722 bool is_npn_state_set_; 723 bool new_npn_value_; 724 bool was_used_to_convey_data_; 725}; 726 727class TestSocketRequest : public CallbackRunner< Tuple1<int> > { 728 public: 729 TestSocketRequest( 730 std::vector<TestSocketRequest*>* request_order, 731 size_t* completion_count); 732 virtual ~TestSocketRequest(); 733 734 ClientSocketHandle* handle() { return &handle_; } 735 736 int WaitForResult(); 737 virtual void RunWithParams(const Tuple1<int>& params); 738 739 private: 740 ClientSocketHandle handle_; 741 std::vector<TestSocketRequest*>* request_order_; 742 size_t* completion_count_; 743 TestCompletionCallback callback_; 744}; 745 746class ClientSocketPoolTest { 747 public: 748 enum KeepAlive { 749 KEEP_ALIVE, 750 751 // A socket will be disconnected in addition to handle being reset. 752 NO_KEEP_ALIVE, 753 }; 754 755 static const int kIndexOutOfBounds; 756 static const int kRequestNotFound; 757 758 ClientSocketPoolTest(); 759 ~ClientSocketPoolTest(); 760 761 template <typename PoolType, typename SocketParams> 762 int StartRequestUsingPool(PoolType* socket_pool, 763 const std::string& group_name, 764 RequestPriority priority, 765 const scoped_refptr<SocketParams>& socket_params) { 766 DCHECK(socket_pool); 767 TestSocketRequest* request = new TestSocketRequest(&request_order_, 768 &completion_count_); 769 requests_.push_back(request); 770 int rv = request->handle()->Init( 771 group_name, socket_params, priority, request, 772 socket_pool, BoundNetLog()); 773 if (rv != ERR_IO_PENDING) 774 request_order_.push_back(request); 775 return rv; 776 } 777 778 // Provided there were n requests started, takes |index| in range 1..n 779 // and returns order in which that request completed, in range 1..n, 780 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound 781 // if that request did not complete (for example was canceled). 782 int GetOrderOfRequest(size_t index) const; 783 784 // Resets first initialized socket handle from |requests_|. If found such 785 // a handle, returns true. 786 bool ReleaseOneConnection(KeepAlive keep_alive); 787 788 // Releases connections until there is nothing to release. 789 void ReleaseAllConnections(KeepAlive keep_alive); 790 791 TestSocketRequest* request(int i) { return requests_[i]; } 792 size_t requests_size() const { return requests_.size(); } 793 ScopedVector<TestSocketRequest>* requests() { return &requests_; } 794 size_t completion_count() const { return completion_count_; } 795 796 private: 797 ScopedVector<TestSocketRequest> requests_; 798 std::vector<TestSocketRequest*> request_order_; 799 size_t completion_count_; 800}; 801 802class MockTCPClientSocketPool : public TCPClientSocketPool { 803 public: 804 class MockConnectJob { 805 public: 806 MockConnectJob(ClientSocket* socket, ClientSocketHandle* handle, 807 CompletionCallback* callback); 808 ~MockConnectJob(); 809 810 int Connect(); 811 bool CancelHandle(const ClientSocketHandle* handle); 812 813 private: 814 void OnConnect(int rv); 815 816 scoped_ptr<ClientSocket> socket_; 817 ClientSocketHandle* handle_; 818 CompletionCallback* user_callback_; 819 CompletionCallbackImpl<MockConnectJob> connect_callback_; 820 821 DISALLOW_COPY_AND_ASSIGN(MockConnectJob); 822 }; 823 824 MockTCPClientSocketPool( 825 int max_sockets, 826 int max_sockets_per_group, 827 ClientSocketPoolHistograms* histograms, 828 ClientSocketFactory* socket_factory); 829 830 virtual ~MockTCPClientSocketPool(); 831 832 int release_count() const { return release_count_; } 833 int cancel_count() const { return cancel_count_; } 834 835 // TCPClientSocketPool methods. 836 virtual int RequestSocket(const std::string& group_name, 837 const void* socket_params, 838 RequestPriority priority, 839 ClientSocketHandle* handle, 840 CompletionCallback* callback, 841 const BoundNetLog& net_log); 842 843 virtual void CancelRequest(const std::string& group_name, 844 ClientSocketHandle* handle); 845 virtual void ReleaseSocket(const std::string& group_name, 846 ClientSocket* socket, int id); 847 848 private: 849 ClientSocketFactory* client_socket_factory_; 850 ScopedVector<MockConnectJob> job_list_; 851 int release_count_; 852 int cancel_count_; 853 854 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocketPool); 855}; 856 857class DeterministicMockClientSocketFactory : public ClientSocketFactory { 858 public: 859 DeterministicMockClientSocketFactory(); 860 virtual ~DeterministicMockClientSocketFactory(); 861 862 void AddSocketDataProvider(DeterministicSocketData* socket); 863 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket); 864 void ResetNextMockIndexes(); 865 866 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory 867 // created. 868 MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const; 869 870 // ClientSocketFactory 871 virtual ClientSocket* CreateTCPClientSocket(const AddressList& addresses, 872 NetLog* net_log, 873 const NetLog::Source& source); 874 virtual SSLClientSocket* CreateSSLClientSocket( 875 ClientSocketHandle* transport_socket, 876 const std::string& hostname, 877 const SSLConfig& ssl_config, 878 SSLHostInfo* ssl_host_info); 879 880 SocketDataProviderArray<DeterministicSocketData>& mock_data() { 881 return mock_data_; 882 } 883 std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() { 884 return tcp_client_sockets_; 885 } 886 887 private: 888 SocketDataProviderArray<DeterministicSocketData> mock_data_; 889 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_; 890 891 // Store pointers to handed out sockets in case the test wants to get them. 892 std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_; 893 std::vector<MockSSLClientSocket*> ssl_client_sockets_; 894}; 895 896class MockSOCKSClientSocketPool : public SOCKSClientSocketPool { 897 public: 898 MockSOCKSClientSocketPool( 899 int max_sockets, 900 int max_sockets_per_group, 901 ClientSocketPoolHistograms* histograms, 902 TCPClientSocketPool* tcp_pool); 903 904 virtual ~MockSOCKSClientSocketPool(); 905 906 // SOCKSClientSocketPool methods. 907 virtual int RequestSocket(const std::string& group_name, 908 const void* socket_params, 909 RequestPriority priority, 910 ClientSocketHandle* handle, 911 CompletionCallback* callback, 912 const BoundNetLog& net_log); 913 914 virtual void CancelRequest(const std::string& group_name, 915 ClientSocketHandle* handle); 916 virtual void ReleaseSocket(const std::string& group_name, 917 ClientSocket* socket, int id); 918 919 private: 920 TCPClientSocketPool* const tcp_pool_; 921 922 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool); 923}; 924 925// Constants for a successful SOCKS v5 handshake. 926extern const char kSOCKS5GreetRequest[]; 927extern const int kSOCKS5GreetRequestLength; 928 929extern const char kSOCKS5GreetResponse[]; 930extern const int kSOCKS5GreetResponseLength; 931 932extern const char kSOCKS5OkRequest[]; 933extern const int kSOCKS5OkRequestLength; 934 935extern const char kSOCKS5OkResponse[]; 936extern const int kSOCKS5OkResponseLength; 937 938} // namespace net 939 940#endif // NET_SOCKET_SOCKET_TEST_UTIL_H_ 941