We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / tools / quic / test_tools / quic_test_client.cc
blob75c9a0190814e5f171130a325cc7933cedc584c5
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/tools/quic/test_tools/quic_test_client.h"
7 #include "base/time/time.h"
8 #include "net/base/completion_callback.h"
9 #include "net/base/net_errors.h"
10 #include "net/cert/cert_verify_result.h"
11 #include "net/cert/x509_certificate.h"
12 #include "net/quic/crypto/proof_verifier.h"
13 #include "net/quic/quic_server_id.h"
14 #include "net/quic/test_tools/quic_connection_peer.h"
15 #include "net/quic/test_tools/quic_session_peer.h"
16 #include "net/quic/test_tools/quic_test_utils.h"
17 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
18 #include "net/tools/balsa/balsa_headers.h"
19 #include "net/tools/quic/quic_epoll_connection_helper.h"
20 #include "net/tools/quic/quic_packet_writer_wrapper.h"
21 #include "net/tools/quic/quic_spdy_client_stream.h"
22 #include "net/tools/quic/spdy_utils.h"
23 #include "net/tools/quic/test_tools/http_message.h"
24 #include "net/tools/quic/test_tools/quic_client_peer.h"
25 #include "url/gurl.h"
27 using base::StringPiece;
28 using net::QuicServerId;
29 using net::test::QuicConnectionPeer;
30 using net::test::QuicSessionPeer;
31 using net::test::ReliableQuicStreamPeer;
32 using std::string;
33 using std::vector;
35 namespace net {
36 namespace tools {
37 namespace test {
38 namespace {
40 // RecordingProofVerifier accepts any certificate chain and records the common
41 // name of the leaf.
42 class RecordingProofVerifier : public ProofVerifier {
43 public:
44 // ProofVerifier interface.
45 QuicAsyncStatus VerifyProof(const string& hostname,
46 const string& server_config,
47 const vector<string>& certs,
48 const string& signature,
49 const ProofVerifyContext* context,
50 string* error_details,
51 scoped_ptr<ProofVerifyDetails>* details,
52 ProofVerifierCallback* callback) override {
53 common_name_.clear();
54 if (certs.empty()) {
55 return QUIC_FAILURE;
58 // Convert certs to X509Certificate.
59 vector<StringPiece> cert_pieces(certs.size());
60 for (unsigned i = 0; i < certs.size(); i++) {
61 cert_pieces[i] = StringPiece(certs[i]);
63 scoped_refptr<net::X509Certificate> cert =
64 net::X509Certificate::CreateFromDERCertChain(cert_pieces);
65 if (!cert.get()) {
66 return QUIC_FAILURE;
69 common_name_ = cert->subject().GetDisplayName();
70 return QUIC_SUCCESS;
73 const string& common_name() const { return common_name_; }
75 private:
76 string common_name_;
79 } // anonymous namespace
81 BalsaHeaders* MungeHeaders(const BalsaHeaders* const_headers,
82 bool secure) {
83 StringPiece uri = const_headers->request_uri();
84 if (uri.empty()) {
85 return nullptr;
87 if (const_headers->request_method() == "CONNECT") {
88 return nullptr;
90 BalsaHeaders* headers = new BalsaHeaders;
91 headers->CopyFrom(*const_headers);
92 if (!uri.starts_with("https://") &&
93 !uri.starts_with("http://")) {
94 // If we have a relative URL, set some defaults.
95 string full_uri = secure ? "https://www.google.com" :
96 "http://www.google.com";
97 full_uri.append(uri.as_string());
98 headers->SetRequestUri(full_uri);
100 return headers;
103 MockableQuicClient::MockableQuicClient(
104 IPEndPoint server_address,
105 const QuicServerId& server_id,
106 const QuicVersionVector& supported_versions,
107 EpollServer* epoll_server)
108 : QuicClient(server_address,
109 server_id,
110 supported_versions,
111 epoll_server),
112 override_connection_id_(0),
113 test_writer_(nullptr) {}
115 MockableQuicClient::MockableQuicClient(
116 IPEndPoint server_address,
117 const QuicServerId& server_id,
118 const QuicConfig& config,
119 const QuicVersionVector& supported_versions,
120 EpollServer* epoll_server)
121 : QuicClient(server_address,
122 server_id,
123 supported_versions,
124 config,
125 epoll_server),
126 override_connection_id_(0),
127 test_writer_(nullptr) {}
129 MockableQuicClient::~MockableQuicClient() {
130 if (connected()) {
131 Disconnect();
135 QuicPacketWriter* MockableQuicClient::CreateQuicPacketWriter() {
136 QuicPacketWriter* writer = QuicClient::CreateQuicPacketWriter();
137 if (!test_writer_) {
138 return writer;
140 test_writer_->set_writer(writer);
141 return test_writer_;
144 QuicConnectionId MockableQuicClient::GenerateConnectionId() {
145 return override_connection_id_ ? override_connection_id_
146 : QuicClient::GenerateConnectionId();
149 // Takes ownership of writer.
150 void MockableQuicClient::UseWriter(QuicPacketWriterWrapper* writer) {
151 CHECK(test_writer_ == nullptr);
152 test_writer_ = writer;
155 void MockableQuicClient::UseConnectionId(QuicConnectionId connection_id) {
156 override_connection_id_ = connection_id;
159 QuicTestClient::QuicTestClient(IPEndPoint server_address,
160 const string& server_hostname,
161 bool secure,
162 const QuicVersionVector& supported_versions)
163 : client_(new MockableQuicClient(server_address,
164 QuicServerId(server_hostname,
165 server_address.port(),
166 secure,
167 PRIVACY_MODE_DISABLED),
168 supported_versions,
169 &epoll_server_)) {
170 Initialize(secure);
173 QuicTestClient::QuicTestClient(
174 IPEndPoint server_address,
175 const string& server_hostname,
176 bool secure,
177 const QuicConfig& config,
178 const QuicVersionVector& supported_versions)
179 : client_(
180 new MockableQuicClient(server_address,
181 QuicServerId(server_hostname,
182 server_address.port(),
183 secure,
184 PRIVACY_MODE_DISABLED),
185 config,
186 supported_versions,
187 &epoll_server_)) {
188 Initialize(secure);
191 QuicTestClient::QuicTestClient() {
194 QuicTestClient::~QuicTestClient() {
195 if (stream_) {
196 stream_->set_visitor(nullptr);
200 void QuicTestClient::Initialize(bool secure) {
201 priority_ = 3;
202 connect_attempted_ = false;
203 secure_ = secure;
204 auto_reconnect_ = false;
205 buffer_body_ = true;
206 fec_policy_ = FEC_PROTECT_OPTIONAL;
207 proof_verifier_ = nullptr;
208 ClearPerRequestState();
209 ExpectCertificates(secure_);
210 // As chrome will generally do this, we want it to be the default when it's
211 // not overridden.
212 if (!client_->config()->HasSetBytesForConnectionIdToSend()) {
213 client_->config()->SetBytesForConnectionIdToSend(0);
217 void QuicTestClient::ExpectCertificates(bool on) {
218 if (on) {
219 proof_verifier_ = new RecordingProofVerifier;
220 client_->SetProofVerifier(proof_verifier_);
221 } else {
222 proof_verifier_ = nullptr;
223 client_->SetProofVerifier(nullptr);
227 void QuicTestClient::SetUserAgentID(const string& user_agent_id) {
228 client_->SetUserAgentID(user_agent_id);
231 ssize_t QuicTestClient::SendRequest(const string& uri) {
232 HTTPMessage message(HttpConstants::HTTP_1_1,
233 HttpConstants::GET,
234 uri);
235 return SendMessage(message);
238 ssize_t QuicTestClient::SendMessage(const HTTPMessage& message) {
239 stream_ = nullptr; // Always force creation of a stream for SendMessage.
241 // If we're not connected, try to find an sni hostname.
242 if (!connected()) {
243 GURL url(message.headers()->request_uri().as_string());
244 if (!url.host().empty()) {
245 client_->set_server_id(
246 QuicServerId(url.host(),
247 url.EffectiveIntPort(),
248 url.SchemeIs("https"),
249 PRIVACY_MODE_DISABLED));
253 QuicSpdyClientStream* stream = GetOrCreateStream();
254 if (!stream) { return 0; }
256 scoped_ptr<BalsaHeaders> munged_headers(MungeHeaders(message.headers(),
257 secure_));
258 ssize_t ret = GetOrCreateStream()->SendRequest(
259 SpdyUtils::RequestHeadersToSpdyHeaders(
260 munged_headers.get() ? *munged_headers : *message.headers()),
261 message.body(), message.has_complete_message());
262 WaitForWriteToFlush();
263 return ret;
266 ssize_t QuicTestClient::SendData(string data, bool last_data) {
267 return SendData(data, last_data, nullptr);
270 ssize_t QuicTestClient::SendData(string data,
271 bool last_data,
272 QuicAckNotifier::DelegateInterface* delegate) {
273 QuicSpdyClientStream* stream = GetOrCreateStream();
274 if (!stream) { return 0; }
275 GetOrCreateStream()->SendBody(data, last_data, delegate);
276 WaitForWriteToFlush();
277 return data.length();
280 bool QuicTestClient::response_complete() const {
281 return response_complete_;
284 int QuicTestClient::response_header_size() const {
285 return response_header_size_;
288 int64 QuicTestClient::response_body_size() const {
289 return response_body_size_;
292 bool QuicTestClient::buffer_body() const {
293 return buffer_body_;
296 void QuicTestClient::set_buffer_body(bool buffer_body) {
297 buffer_body_ = buffer_body;
300 bool QuicTestClient::ServerInLameDuckMode() const {
301 return false;
304 const string& QuicTestClient::response_body() {
305 return response_;
308 string QuicTestClient::SendCustomSynchronousRequest(
309 const HTTPMessage& message) {
310 SendMessage(message);
311 WaitForResponse();
312 return response_;
315 string QuicTestClient::SendSynchronousRequest(const string& uri) {
316 if (SendRequest(uri) == 0) {
317 DLOG(ERROR) << "Failed the request for uri:" << uri;
318 return "";
320 WaitForResponse();
321 return response_;
324 QuicSpdyClientStream* QuicTestClient::GetOrCreateStream() {
325 if (!connect_attempted_ || auto_reconnect_) {
326 if (!connected()) {
327 Connect();
329 if (!connected()) {
330 return nullptr;
333 if (!stream_) {
334 stream_ = client_->CreateReliableClientStream();
335 if (stream_ == nullptr) {
336 return nullptr;
338 stream_->set_visitor(this);
339 reinterpret_cast<QuicSpdyClientStream*>(stream_)->set_priority(priority_);
340 // Set FEC policy on stream.
341 ReliableQuicStreamPeer::SetFecPolicy(stream_, fec_policy_);
344 return stream_;
347 QuicErrorCode QuicTestClient::connection_error() {
348 return client()->session()->error();
351 MockableQuicClient* QuicTestClient::client() { return client_.get(); }
353 const string& QuicTestClient::cert_common_name() const {
354 return reinterpret_cast<RecordingProofVerifier*>(proof_verifier_)
355 ->common_name();
358 QuicTagValueMap QuicTestClient::GetServerConfig() const {
359 QuicCryptoClientConfig* config =
360 QuicClientPeer::GetCryptoConfig(client_.get());
361 QuicCryptoClientConfig::CachedState* state =
362 config->LookupOrCreate(client_->server_id());
363 const CryptoHandshakeMessage* handshake_msg = state->GetServerConfig();
364 if (handshake_msg != nullptr) {
365 return handshake_msg->tag_value_map();
366 } else {
367 return QuicTagValueMap();
371 bool QuicTestClient::connected() const {
372 return client_->connected();
375 void QuicTestClient::Connect() {
376 DCHECK(!connected());
377 if (!connect_attempted_) {
378 client_->Initialize();
380 client_->Connect();
381 connect_attempted_ = true;
384 void QuicTestClient::ResetConnection() {
385 Disconnect();
386 Connect();
389 void QuicTestClient::Disconnect() {
390 client_->Disconnect();
391 connect_attempted_ = false;
394 IPEndPoint QuicTestClient::LocalSocketAddress() const {
395 return client_->client_address();
398 void QuicTestClient::ClearPerRequestState() {
399 stream_error_ = QUIC_STREAM_NO_ERROR;
400 stream_ = nullptr;
401 response_ = "";
402 response_complete_ = false;
403 response_headers_complete_ = false;
404 headers_.Clear();
405 bytes_read_ = 0;
406 bytes_written_ = 0;
407 response_header_size_ = 0;
408 response_body_size_ = 0;
411 void QuicTestClient::WaitForResponseForMs(int timeout_ms) {
412 int64 timeout_us = timeout_ms * base::Time::kMicrosecondsPerMillisecond;
413 int64 old_timeout_us = epoll_server()->timeout_in_us();
414 if (timeout_us > 0) {
415 epoll_server()->set_timeout_in_us(timeout_us);
417 const QuicClock* clock =
418 QuicConnectionPeer::GetHelper(client()->session()->connection())->
419 GetClock();
420 QuicTime end_waiting_time = clock->Now().Add(
421 QuicTime::Delta::FromMicroseconds(timeout_us));
422 while (stream_ != nullptr &&
423 !client_->session()->IsClosedStream(stream_->id()) &&
424 (timeout_us < 0 || clock->Now() < end_waiting_time)) {
425 client_->WaitForEvents();
427 if (timeout_us > 0) {
428 epoll_server()->set_timeout_in_us(old_timeout_us);
432 void QuicTestClient::WaitForInitialResponseForMs(int timeout_ms) {
433 int64 timeout_us = timeout_ms * base::Time::kMicrosecondsPerMillisecond;
434 int64 old_timeout_us = epoll_server()->timeout_in_us();
435 if (timeout_us > 0) {
436 epoll_server()->set_timeout_in_us(timeout_us);
438 const QuicClock* clock =
439 QuicConnectionPeer::GetHelper(client()->session()->connection())->
440 GetClock();
441 QuicTime end_waiting_time = clock->Now().Add(
442 QuicTime::Delta::FromMicroseconds(timeout_us));
443 while (stream_ != nullptr &&
444 !client_->session()->IsClosedStream(stream_->id()) &&
445 stream_->stream_bytes_read() == 0 &&
446 (timeout_us < 0 || clock->Now() < end_waiting_time)) {
447 client_->WaitForEvents();
449 if (timeout_us > 0) {
450 epoll_server()->set_timeout_in_us(old_timeout_us);
454 ssize_t QuicTestClient::Send(const void *buffer, size_t size) {
455 return SendData(string(static_cast<const char*>(buffer), size), false);
458 bool QuicTestClient::response_headers_complete() const {
459 if (stream_ != nullptr) {
460 return stream_->headers_decompressed();
462 return response_headers_complete_;
465 const BalsaHeaders* QuicTestClient::response_headers() const {
466 if (stream_ != nullptr) {
467 SpdyUtils::SpdyHeadersToResponseHeaders(stream_->headers(), &headers_);
468 return &headers_;
469 } else {
470 return &headers_;
474 int64 QuicTestClient::response_size() const {
475 return bytes_read_;
478 size_t QuicTestClient::bytes_read() const {
479 return bytes_read_;
482 size_t QuicTestClient::bytes_written() const {
483 return bytes_written_;
486 void QuicTestClient::OnClose(QuicDataStream* stream) {
487 if (stream_ != stream) {
488 return;
490 if (buffer_body()) {
491 // TODO(fnk): The stream still buffers the whole thing. Fix that.
492 response_ = stream_->data();
494 response_complete_ = true;
495 response_headers_complete_ = stream_->headers_decompressed();
496 SpdyUtils::SpdyHeadersToResponseHeaders(stream_->headers(),
497 &headers_);
498 stream_error_ = stream_->stream_error();
499 bytes_read_ = stream_->stream_bytes_read() + stream_->header_bytes_read();
500 bytes_written_ =
501 stream_->stream_bytes_written() + stream_->header_bytes_written();
502 response_header_size_ = headers_.GetSizeForWriteBuffer();
503 response_body_size_ = stream_->data().size();
504 stream_ = nullptr;
507 void QuicTestClient::UseWriter(QuicPacketWriterWrapper* writer) {
508 client_->UseWriter(writer);
511 void QuicTestClient::UseConnectionId(QuicConnectionId connection_id) {
512 DCHECK(!connected());
513 client_->UseConnectionId(connection_id);
516 ssize_t QuicTestClient::SendAndWaitForResponse(const void *buffer,
517 size_t size) {
518 LOG(DFATAL) << "Not implemented";
519 return 0;
522 void QuicTestClient::Bind(IPEndPoint* local_address) {
523 DLOG(WARNING) << "Bind will be done during connect";
526 string QuicTestClient::SerializeMessage(const HTTPMessage& message) {
527 LOG(DFATAL) << "Not implemented";
528 return "";
531 IPAddressNumber QuicTestClient::bind_to_address() const {
532 return client_->bind_to_address();
535 void QuicTestClient::set_bind_to_address(IPAddressNumber address) {
536 client_->set_bind_to_address(address);
539 const IPEndPoint& QuicTestClient::address() const {
540 LOG(DFATAL) << "Not implemented";
541 return client_->server_address();
544 size_t QuicTestClient::requests_sent() const {
545 LOG(DFATAL) << "Not implemented";
546 return 0;
549 void QuicTestClient::WaitForWriteToFlush() {
550 while (connected() && client()->session()->HasDataToWrite()) {
551 client_->WaitForEvents();
555 void QuicTestClient::SetFecPolicy(FecPolicy fec_policy) {
556 fec_policy_ = fec_policy;
557 // Set policy for headers and crypto streams.
558 ReliableQuicStreamPeer::SetFecPolicy(
559 QuicSessionPeer::GetHeadersStream(client()->session()), fec_policy);
560 ReliableQuicStreamPeer::SetFecPolicy(client()->session()->GetCryptoStream(),
561 fec_policy);
564 } // namespace test
565 } // namespace tools
566 } // namespace net