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/quic_client.h"
8 #include <netinet/in.h>
10 #include <sys/epoll.h>
11 #include <sys/socket.h>
14 #include "base/logging.h"
15 #include "net/quic/crypto/quic_random.h"
16 #include "net/quic/quic_connection.h"
17 #include "net/quic/quic_data_reader.h"
18 #include "net/quic/quic_protocol.h"
19 #include "net/quic/quic_server_id.h"
20 #include "net/tools/balsa/balsa_headers.h"
21 #include "net/tools/epoll_server/epoll_server.h"
22 #include "net/tools/quic/quic_epoll_connection_helper.h"
23 #include "net/tools/quic/quic_socket_utils.h"
24 #include "net/tools/quic/quic_spdy_client_stream.h"
27 #define SO_RXQ_OVFL 40
35 const int kEpollFlags
= EPOLLIN
| EPOLLOUT
| EPOLLET
;
37 QuicClient::QuicClient(IPEndPoint server_address
,
38 const QuicServerId
& server_id
,
39 const QuicVersionVector
& supported_versions
,
40 EpollServer
* epoll_server
)
41 : server_address_(server_address
),
42 server_id_(server_id
),
44 epoll_server_(epoll_server
),
46 helper_(CreateQuicConnectionHelper()),
49 overflow_supported_(false),
50 supported_versions_(supported_versions
),
51 store_response_(false),
52 latest_response_code_(-1) {
55 QuicClient::QuicClient(IPEndPoint server_address
,
56 const QuicServerId
& server_id
,
57 const QuicVersionVector
& supported_versions
,
58 const QuicConfig
& config
,
59 EpollServer
* epoll_server
)
60 : server_address_(server_address
),
61 server_id_(server_id
),
64 epoll_server_(epoll_server
),
66 helper_(CreateQuicConnectionHelper()),
69 overflow_supported_(false),
70 supported_versions_(supported_versions
),
71 store_response_(false),
72 latest_response_code_(-1) {
75 QuicClient::~QuicClient() {
77 session()->connection()->SendConnectionClosePacket(
78 QUIC_PEER_GOING_AWAY
, "");
84 bool QuicClient::Initialize() {
85 DCHECK(!initialized_
);
87 // If an initial flow control window has not explicitly been set, then use the
88 // same value that Chrome uses: 10 Mb.
89 const uint32 kInitialFlowControlWindow
= 10 * 1024 * 1024; // 10 Mb
90 if (config_
.GetInitialStreamFlowControlWindowToSend() ==
91 kMinimumFlowControlSendWindow
) {
92 config_
.SetInitialStreamFlowControlWindowToSend(kInitialFlowControlWindow
);
94 if (config_
.GetInitialSessionFlowControlWindowToSend() ==
95 kMinimumFlowControlSendWindow
) {
96 config_
.SetInitialSessionFlowControlWindowToSend(kInitialFlowControlWindow
);
99 epoll_server_
->set_timeout_in_us(50 * 1000);
101 if (!CreateUDPSocket()) {
105 epoll_server_
->RegisterFD(fd_
, this, kEpollFlags
);
110 QuicClient::DummyPacketWriterFactory::DummyPacketWriterFactory(
111 QuicPacketWriter
* writer
)
114 QuicClient::DummyPacketWriterFactory::~DummyPacketWriterFactory() {}
116 QuicPacketWriter
* QuicClient::DummyPacketWriterFactory::Create(
117 QuicConnection
* /*connection*/) const {
122 bool QuicClient::CreateUDPSocket() {
123 int address_family
= server_address_
.GetSockAddrFamily();
124 fd_
= socket(address_family
, SOCK_DGRAM
| SOCK_NONBLOCK
, IPPROTO_UDP
);
126 LOG(ERROR
) << "CreateSocket() failed: " << strerror(errno
);
130 int get_overflow
= 1;
131 int rc
= setsockopt(fd_
, SOL_SOCKET
, SO_RXQ_OVFL
, &get_overflow
,
132 sizeof(get_overflow
));
134 DLOG(WARNING
) << "Socket overflow detection not supported";
136 overflow_supported_
= true;
139 if (!QuicSocketUtils::SetReceiveBufferSize(fd_
,
140 kDefaultSocketReceiveBuffer
)) {
144 if (!QuicSocketUtils::SetSendBufferSize(fd_
, kDefaultSocketReceiveBuffer
)) {
148 rc
= QuicSocketUtils::SetGetAddressInfo(fd_
, address_family
);
150 LOG(ERROR
) << "IP detection not supported" << strerror(errno
);
154 if (bind_to_address_
.size() != 0) {
155 client_address_
= IPEndPoint(bind_to_address_
, local_port_
);
156 } else if (address_family
== AF_INET
) {
157 IPAddressNumber any4
;
158 CHECK(net::ParseIPLiteralToNumber("0.0.0.0", &any4
));
159 client_address_
= IPEndPoint(any4
, local_port_
);
161 IPAddressNumber any6
;
162 CHECK(net::ParseIPLiteralToNumber("::", &any6
));
163 client_address_
= IPEndPoint(any6
, local_port_
);
166 sockaddr_storage raw_addr
;
167 socklen_t raw_addr_len
= sizeof(raw_addr
);
168 CHECK(client_address_
.ToSockAddr(reinterpret_cast<sockaddr
*>(&raw_addr
),
171 reinterpret_cast<const sockaddr
*>(&raw_addr
),
174 LOG(ERROR
) << "Bind failed: " << strerror(errno
);
178 SockaddrStorage storage
;
179 if (getsockname(fd_
, storage
.addr
, &storage
.addr_len
) != 0 ||
180 !client_address_
.FromSockAddr(storage
.addr
, storage
.addr_len
)) {
181 LOG(ERROR
) << "Unable to get self address. Error: " << strerror(errno
);
187 bool QuicClient::Connect() {
189 while (EncryptionBeingEstablished()) {
192 return session_
->connection()->connected();
195 void QuicClient::StartConnect() {
196 DCHECK(initialized_
);
197 DCHECK(!connected());
199 QuicPacketWriter
* writer
= CreateQuicPacketWriter();
201 DummyPacketWriterFactory
factory(writer
);
203 session_
.reset(new QuicClientSession(
205 new QuicConnection(GenerateConnectionId(),
209 /* owns_writer= */ false,
210 /* is_server= */ false,
211 server_id_
.is_https(),
212 supported_versions_
)));
214 // Reset |writer_| after |session_| so that the old writer outlives the old
216 if (writer_
.get() != writer
) {
217 writer_
.reset(writer
);
219 session_
->InitializeSession(server_id_
, &crypto_config_
);
220 session_
->CryptoConnect();
223 bool QuicClient::EncryptionBeingEstablished() {
224 return !session_
->IsEncryptionEstablished() &&
225 session_
->connection()->connected();
228 void QuicClient::Disconnect() {
229 DCHECK(initialized_
);
232 session()->connection()->SendConnectionClose(QUIC_PEER_GOING_AWAY
);
237 initialized_
= false;
240 void QuicClient::CleanUpUDPSocket() {
242 epoll_server_
->UnregisterFD(fd_
);
248 void QuicClient::SendRequest(const BalsaHeaders
& headers
,
251 QuicSpdyClientStream
* stream
= CreateReliableClientStream();
252 if (stream
== nullptr) {
253 LOG(DFATAL
) << "stream creation failed!";
256 stream
->SendRequest(headers
, body
, fin
);
257 stream
->set_visitor(this);
260 void QuicClient::SendRequestAndWaitForResponse(const BalsaHeaders
& headers
,
263 SendRequest(headers
, "", true);
264 while (WaitForEvents()) {
268 void QuicClient::SendRequestsAndWaitForResponse(
269 const base::CommandLine::StringVector
& args
) {
270 for (size_t i
= 0; i
< args
.size(); ++i
) {
271 BalsaHeaders headers
;
272 headers
.SetRequestFirstlineFromStringPieces("GET", args
[i
], "HTTP/1.1");
273 SendRequest(headers
, "", true);
275 while (WaitForEvents()) {}
278 QuicSpdyClientStream
* QuicClient::CreateReliableClientStream() {
283 return session_
->CreateOutgoingDataStream();
286 void QuicClient::WaitForStreamToClose(QuicStreamId id
) {
289 while (connected() && !session_
->IsClosedStream(id
)) {
290 epoll_server_
->WaitForEventsAndExecuteCallbacks();
294 void QuicClient::WaitForCryptoHandshakeConfirmed() {
297 while (connected() && !session_
->IsCryptoHandshakeConfirmed()) {
298 epoll_server_
->WaitForEventsAndExecuteCallbacks();
302 bool QuicClient::WaitForEvents() {
305 epoll_server_
->WaitForEventsAndExecuteCallbacks();
306 return session_
->num_active_requests() != 0;
309 void QuicClient::OnEvent(int fd
, EpollEvent
* event
) {
312 if (event
->in_events
& EPOLLIN
) {
313 while (connected() && ReadAndProcessPacket()) {
316 if (connected() && (event
->in_events
& EPOLLOUT
)) {
317 writer_
->SetWritable();
318 session_
->connection()->OnCanWrite();
320 if (event
->in_events
& EPOLLERR
) {
321 DVLOG(1) << "Epollerr";
325 void QuicClient::OnClose(QuicDataStream
* stream
) {
326 QuicSpdyClientStream
* client_stream
=
327 static_cast<QuicSpdyClientStream
*>(stream
);
328 if (response_listener_
.get() != nullptr) {
329 response_listener_
->OnCompleteResponse(
330 stream
->id(), client_stream
->headers(), client_stream
->data());
333 // Store response headers and body.
334 if (store_response_
) {
335 latest_response_code_
= client_stream
->headers().parsed_response_code();
336 client_stream
->headers().DumpHeadersToString(&latest_response_headers_
);
337 latest_response_body_
= client_stream
->data();
341 bool QuicClient::connected() const {
342 return session_
.get() && session_
->connection() &&
343 session_
->connection()->connected();
346 bool QuicClient::goaway_received() const {
347 return session_
!= nullptr && session_
->goaway_received();
350 size_t QuicClient::latest_response_code() const {
351 LOG_IF(DFATAL
, !store_response_
) << "Response not stored!";
352 return latest_response_code_
;
355 const string
& QuicClient::latest_response_headers() const {
356 LOG_IF(DFATAL
, !store_response_
) << "Response not stored!";
357 return latest_response_headers_
;
360 const string
& QuicClient::latest_response_body() const {
361 LOG_IF(DFATAL
, !store_response_
) << "Response not stored!";
362 return latest_response_body_
;
365 QuicConnectionId
QuicClient::GenerateConnectionId() {
366 return QuicRandom::GetInstance()->RandUint64();
369 QuicEpollConnectionHelper
* QuicClient::CreateQuicConnectionHelper() {
370 return new QuicEpollConnectionHelper(epoll_server_
);
373 QuicPacketWriter
* QuicClient::CreateQuicPacketWriter() {
374 return new QuicDefaultPacketWriter(fd_
);
377 int QuicClient::ReadPacket(char* buffer
,
379 IPEndPoint
* server_address
,
380 IPAddressNumber
* client_ip
) {
381 return QuicSocketUtils::ReadPacket(
382 fd_
, buffer
, buffer_len
,
383 overflow_supported_
? &packets_dropped_
: nullptr, client_ip
,
387 bool QuicClient::ReadAndProcessPacket() {
388 // Allocate some extra space so we can send an error if the server goes over
390 char buf
[2 * kMaxPacketSize
];
392 IPEndPoint server_address
;
393 IPAddressNumber client_ip
;
395 int bytes_read
= ReadPacket(buf
, arraysize(buf
), &server_address
, &client_ip
);
397 if (bytes_read
< 0) {
401 QuicEncryptedPacket
packet(buf
, bytes_read
, false);
403 IPEndPoint
client_address(client_ip
, client_address_
.port());
404 session_
->connection()->ProcessUdpPacket(
405 client_address
, server_address
, packet
);