[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / net / quic / quic_time_wait_list_manager.cc
blob0311913d44b1cf19d44c0d7e51df514864cd5456
1 // Copyright 2014 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/quic/quic_time_wait_list_manager.h"
7 #include <errno.h>
9 #include "base/containers/hash_tables.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/stl_util.h"
12 #include "net/base/ip_endpoint.h"
13 #include "net/quic/crypto/crypto_protocol.h"
14 #include "net/quic/crypto/quic_decrypter.h"
15 #include "net/quic/crypto/quic_encrypter.h"
16 #include "net/quic/quic_clock.h"
17 #include "net/quic/quic_connection_helper.h"
18 #include "net/quic/quic_flags.h"
19 #include "net/quic/quic_framer.h"
20 #include "net/quic/quic_protocol.h"
21 #include "net/quic/quic_server_session.h"
22 #include "net/quic/quic_utils.h"
24 using base::StringPiece;
26 namespace net {
28 // A very simple alarm that just informs the QuicTimeWaitListManager to clean
29 // up old connection_ids. This alarm should be unregistered and deleted before
30 // the QuicTimeWaitListManager is deleted.
31 class ConnectionIdCleanUpAlarm : public QuicAlarm::Delegate {
32 public:
33 explicit ConnectionIdCleanUpAlarm(
34 QuicTimeWaitListManager* time_wait_list_manager)
35 : time_wait_list_manager_(time_wait_list_manager) {
38 QuicTime OnAlarm() override {
39 time_wait_list_manager_->CleanUpOldConnectionIds();
40 // Let the time wait manager register the alarm at appropriate time.
41 return QuicTime::Zero();
44 private:
45 // Not owned.
46 QuicTimeWaitListManager* time_wait_list_manager_;
49 // This class stores pending public reset packets to be sent to clients.
50 // server_address - server address on which a packet what was received for
51 // a connection_id in time wait state.
52 // client_address - address of the client that sent that packet. Needed to send
53 // the public reset packet back to the client.
54 // packet - the pending public reset packet that is to be sent to the client.
55 // created instance takes the ownership of this packet.
56 class QuicTimeWaitListManager::QueuedPacket {
57 public:
58 QueuedPacket(const IPEndPoint& server_address,
59 const IPEndPoint& client_address,
60 QuicEncryptedPacket* packet)
61 : server_address_(server_address),
62 client_address_(client_address),
63 packet_(packet) {
66 const IPEndPoint& server_address() const { return server_address_; }
67 const IPEndPoint& client_address() const { return client_address_; }
68 QuicEncryptedPacket* packet() { return packet_.get(); }
70 private:
71 const IPEndPoint server_address_;
72 const IPEndPoint client_address_;
73 scoped_ptr<QuicEncryptedPacket> packet_;
75 DISALLOW_COPY_AND_ASSIGN(QueuedPacket);
78 QuicTimeWaitListManager::QuicTimeWaitListManager(
79 QuicPacketWriter* writer,
80 QuicServerSessionVisitor* visitor,
81 QuicConnectionHelperInterface* helper,
82 const QuicVersionVector& supported_versions)
83 : helper_(helper),
84 time_wait_period_(
85 QuicTime::Delta::FromSeconds(FLAGS_quic_time_wait_list_seconds)),
86 connection_id_clean_up_alarm_(
87 helper_->CreateAlarm(new ConnectionIdCleanUpAlarm(this))),
88 writer_(writer),
89 visitor_(visitor) {
90 SetConnectionIdCleanUpAlarm();
93 QuicTimeWaitListManager::~QuicTimeWaitListManager() {
94 connection_id_clean_up_alarm_->Cancel();
95 STLDeleteElements(&pending_packets_queue_);
96 for (ConnectionIdMap::iterator it = connection_id_map_.begin();
97 it != connection_id_map_.end();
98 ++it) {
99 delete it->second.close_packet;
103 void QuicTimeWaitListManager::AddConnectionIdToTimeWait(
104 QuicConnectionId connection_id,
105 QuicVersion version,
106 QuicEncryptedPacket* close_packet) {
107 int num_packets = 0;
108 ConnectionIdMap::iterator it = connection_id_map_.find(connection_id);
109 const bool new_connection_id = it == connection_id_map_.end();
110 if (!new_connection_id) { // Replace record if it is reinserted.
111 num_packets = it->second.num_packets;
112 delete it->second.close_packet;
113 connection_id_map_.erase(it);
115 TrimTimeWaitListIfNeeded();
116 DCHECK_LT(num_connections(),
117 static_cast<size_t>(FLAGS_quic_time_wait_list_max_connections));
118 ConnectionIdData data(num_packets,
119 version,
120 helper_->GetClock()->ApproximateNow(),
121 close_packet);
122 connection_id_map_.insert(std::make_pair(connection_id, data));
123 if (new_connection_id) {
124 visitor_->OnConnectionAddedToTimeWaitList(connection_id);
128 bool QuicTimeWaitListManager::IsConnectionIdInTimeWait(
129 QuicConnectionId connection_id) const {
130 return ContainsKey(connection_id_map_, connection_id);
133 QuicVersion QuicTimeWaitListManager::GetQuicVersionFromConnectionId(
134 QuicConnectionId connection_id) {
135 ConnectionIdMap::iterator it = connection_id_map_.find(connection_id);
136 DCHECK(it != connection_id_map_.end());
137 return (it->second).version;
140 void QuicTimeWaitListManager::OnCanWrite() {
141 while (!pending_packets_queue_.empty()) {
142 QueuedPacket* queued_packet = pending_packets_queue_.front();
143 if (!WriteToWire(queued_packet)) {
144 return;
146 pending_packets_queue_.pop_front();
147 delete queued_packet;
151 void QuicTimeWaitListManager::ProcessPacket(
152 const IPEndPoint& server_address,
153 const IPEndPoint& client_address,
154 QuicConnectionId connection_id,
155 QuicPacketSequenceNumber sequence_number,
156 const QuicEncryptedPacket& /*packet*/) {
157 DCHECK(IsConnectionIdInTimeWait(connection_id));
158 DVLOG(1) << "Processing " << connection_id << " in time wait state.";
159 // TODO(satyamshekhar): Think about handling packets from different client
160 // addresses.
161 ConnectionIdMap::iterator it = connection_id_map_.find(connection_id);
162 DCHECK(it != connection_id_map_.end());
163 // Increment the received packet count.
164 ++((it->second).num_packets);
165 if (!ShouldSendResponse((it->second).num_packets)) {
166 return;
168 if (it->second.close_packet) {
169 QueuedPacket* queued_packet =
170 new QueuedPacket(server_address,
171 client_address,
172 it->second.close_packet->Clone());
173 // Takes ownership of the packet.
174 SendOrQueuePacket(queued_packet);
175 } else {
176 SendPublicReset(server_address,
177 client_address,
178 connection_id,
179 sequence_number);
183 // Returns true if the number of packets received for this connection_id is a
184 // power of 2 to throttle the number of public reset packets we send to a
185 // client.
186 bool QuicTimeWaitListManager::ShouldSendResponse(int received_packet_count) {
187 return (received_packet_count & (received_packet_count - 1)) == 0;
190 void QuicTimeWaitListManager::SendPublicReset(
191 const IPEndPoint& server_address,
192 const IPEndPoint& client_address,
193 QuicConnectionId connection_id,
194 QuicPacketSequenceNumber rejected_sequence_number) {
195 QuicPublicResetPacket packet;
196 packet.public_header.connection_id = connection_id;
197 packet.public_header.reset_flag = true;
198 packet.public_header.version_flag = false;
199 packet.rejected_sequence_number = rejected_sequence_number;
200 // TODO(satyamshekhar): generate a valid nonce for this connection_id.
201 packet.nonce_proof = 1010101;
202 packet.client_address = client_address;
203 QueuedPacket* queued_packet = new QueuedPacket(
204 server_address,
205 client_address,
206 BuildPublicReset(packet));
207 // Takes ownership of the packet.
208 SendOrQueuePacket(queued_packet);
211 QuicEncryptedPacket* QuicTimeWaitListManager::BuildPublicReset(
212 const QuicPublicResetPacket& packet) {
213 return QuicFramer::BuildPublicResetPacket(packet);
216 // Either sends the packet and deletes it or makes pending queue the
217 // owner of the packet.
218 void QuicTimeWaitListManager::SendOrQueuePacket(QueuedPacket* packet) {
219 if (WriteToWire(packet)) {
220 delete packet;
221 } else {
222 // pending_packets_queue takes the ownership of the queued packet.
223 pending_packets_queue_.push_back(packet);
227 bool QuicTimeWaitListManager::WriteToWire(QueuedPacket* queued_packet) {
228 if (writer_->IsWriteBlocked()) {
229 visitor_->OnWriteBlocked(this);
230 return false;
232 WriteResult result = writer_->WritePacket(
233 queued_packet->packet()->data(),
234 queued_packet->packet()->length(),
235 queued_packet->server_address().address(),
236 queued_packet->client_address());
237 if (result.status == WRITE_STATUS_BLOCKED) {
238 // If blocked and unbuffered, return false to retry sending.
239 DCHECK(writer_->IsWriteBlocked());
240 visitor_->OnWriteBlocked(this);
241 return writer_->IsWriteBlockedDataBuffered();
242 } else if (result.status == WRITE_STATUS_ERROR) {
243 LOG(WARNING) << "Received unknown error while sending reset packet to "
244 << queued_packet->client_address().ToString() << ": "
245 << strerror(result.error_code);
247 return true;
250 void QuicTimeWaitListManager::SetConnectionIdCleanUpAlarm() {
251 connection_id_clean_up_alarm_->Cancel();
252 QuicTime now = helper_->GetClock()->ApproximateNow();
253 QuicTime next_alarm_time = now;
254 if (!connection_id_map_.empty()) {
255 QuicTime oldest_connection_id =
256 connection_id_map_.begin()->second.time_added;
257 if (now.Subtract(oldest_connection_id) < time_wait_period_) {
258 next_alarm_time = oldest_connection_id.Add(time_wait_period_);
259 } else {
260 LOG(ERROR) << "ConnectionId lingered for longer than kTimeWaitPeriod";
262 } else {
263 // No connection_ids added so none will expire before time_wait_period_.
264 next_alarm_time = now.Add(time_wait_period_);
267 connection_id_clean_up_alarm_->Set(next_alarm_time);
270 bool QuicTimeWaitListManager::MaybeExpireOldestConnection(
271 QuicTime expiration_time) {
272 if (connection_id_map_.empty()) {
273 return false;
275 ConnectionIdMap::iterator it = connection_id_map_.begin();
276 QuicTime oldest_connection_id_time = it->second.time_added;
277 if (oldest_connection_id_time > expiration_time) {
278 // Too recent, don't retire.
279 return false;
281 // This connection_id has lived its age, retire it now.
282 const QuicConnectionId connection_id = it->first;
283 delete it->second.close_packet;
284 connection_id_map_.erase(it);
285 visitor_->OnConnectionRemovedFromTimeWaitList(connection_id);
286 return true;
289 void QuicTimeWaitListManager::CleanUpOldConnectionIds() {
290 QuicTime now = helper_->GetClock()->ApproximateNow();
291 QuicTime expiration = now.Subtract(time_wait_period_);
293 while (MaybeExpireOldestConnection(expiration)) {
296 SetConnectionIdCleanUpAlarm();
299 void QuicTimeWaitListManager::TrimTimeWaitListIfNeeded() {
300 if (FLAGS_quic_time_wait_list_max_connections < 0) {
301 return;
303 while (num_connections() >=
304 static_cast<size_t>(FLAGS_quic_time_wait_list_max_connections)) {
305 MaybeExpireOldestConnection(QuicTime::Infinite());
309 } // namespace net