Fix crash in SpeechRecognizerImpl introduced in AudioParams refactor.
[chromium-blink-merge.git] / net / tools / quic / quic_time_wait_list_manager.cc
blob68d1b9ec39485276e5ef89ed91a5d94929d7575d
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_time_wait_list_manager.h"
7 #include <errno.h>
9 #include "base/logging.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_flags.h"
18 #include "net/quic/quic_framer.h"
19 #include "net/quic/quic_protocol.h"
20 #include "net/quic/quic_utils.h"
21 #include "net/tools/quic/quic_server_session.h"
23 using base::StringPiece;
25 namespace net {
26 namespace tools {
28 // A very simple alarm that just informs the QuicTimeWaitListManager to clean
29 // up old connection_ids. This alarm should be cancelled 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_;
48 DISALLOW_COPY_AND_ASSIGN(ConnectionIdCleanUpAlarm);
51 // This class stores pending public reset packets to be sent to clients.
52 // server_address - server address on which a packet what was received for
53 // a connection_id in time wait state.
54 // client_address - address of the client that sent that packet. Needed to send
55 // the public reset packet back to the client.
56 // packet - the pending public reset packet that is to be sent to the client.
57 // created instance takes the ownership of this packet.
58 class QuicTimeWaitListManager::QueuedPacket {
59 public:
60 QueuedPacket(const IPEndPoint& server_address,
61 const IPEndPoint& client_address,
62 QuicEncryptedPacket* packet)
63 : server_address_(server_address),
64 client_address_(client_address),
65 packet_(packet) {
68 const IPEndPoint& server_address() const { return server_address_; }
69 const IPEndPoint& client_address() const { return client_address_; }
70 QuicEncryptedPacket* packet() { return packet_.get(); }
72 private:
73 const IPEndPoint server_address_;
74 const IPEndPoint client_address_;
75 scoped_ptr<QuicEncryptedPacket> packet_;
77 DISALLOW_COPY_AND_ASSIGN(QueuedPacket);
80 QuicTimeWaitListManager::QuicTimeWaitListManager(
81 QuicPacketWriter* writer,
82 QuicServerSessionVisitor* visitor,
83 QuicConnectionHelperInterface* helper,
84 const QuicVersionVector& supported_versions)
85 : time_wait_period_(
86 QuicTime::Delta::FromSeconds(FLAGS_quic_time_wait_list_seconds)),
87 connection_id_clean_up_alarm_(
88 helper->CreateAlarm(new ConnectionIdCleanUpAlarm(this))),
89 clock_(helper->GetClock()),
90 writer_(writer),
91 visitor_(visitor) {
92 SetConnectionIdCleanUpAlarm();
95 QuicTimeWaitListManager::~QuicTimeWaitListManager() {
96 connection_id_clean_up_alarm_->Cancel();
97 STLDeleteElements(&pending_packets_queue_);
98 for (ConnectionIdMap::iterator it = connection_id_map_.begin();
99 it != connection_id_map_.end();
100 ++it) {
101 delete it->second.close_packet;
105 void QuicTimeWaitListManager::AddConnectionIdToTimeWait(
106 QuicConnectionId connection_id,
107 QuicVersion version,
108 bool connection_rejected_statelessly,
109 QuicEncryptedPacket* close_packet) {
110 DCHECK(!connection_rejected_statelessly || !close_packet)
111 << "Connections that were rejected statelessly should not "
112 << "have a close packet. connection_id = " << connection_id;
113 int num_packets = 0;
114 ConnectionIdMap::iterator it = connection_id_map_.find(connection_id);
115 const bool new_connection_id = it == connection_id_map_.end();
116 if (!new_connection_id) { // Replace record if it is reinserted.
117 num_packets = it->second.num_packets;
118 delete it->second.close_packet;
119 connection_id_map_.erase(it);
121 TrimTimeWaitListIfNeeded();
122 DCHECK_LT(num_connections(),
123 static_cast<size_t>(FLAGS_quic_time_wait_list_max_connections));
124 ConnectionIdData data(num_packets, version, clock_->ApproximateNow(),
125 close_packet, connection_rejected_statelessly);
126 connection_id_map_.insert(std::make_pair(connection_id, data));
127 if (new_connection_id) {
128 visitor_->OnConnectionAddedToTimeWaitList(connection_id);
132 bool QuicTimeWaitListManager::IsConnectionIdInTimeWait(
133 QuicConnectionId connection_id) const {
134 return ContainsKey(connection_id_map_, connection_id);
137 QuicVersion QuicTimeWaitListManager::GetQuicVersionFromConnectionId(
138 QuicConnectionId connection_id) {
139 ConnectionIdMap::iterator it = connection_id_map_.find(connection_id);
140 DCHECK(it != connection_id_map_.end());
141 return (it->second).version;
144 void QuicTimeWaitListManager::OnCanWrite() {
145 while (!pending_packets_queue_.empty()) {
146 QueuedPacket* queued_packet = pending_packets_queue_.front();
147 if (!WriteToWire(queued_packet)) {
148 return;
150 pending_packets_queue_.pop_front();
151 delete queued_packet;
155 void QuicTimeWaitListManager::ProcessPacket(
156 const IPEndPoint& server_address,
157 const IPEndPoint& client_address,
158 QuicConnectionId connection_id,
159 QuicPacketNumber packet_number,
160 const QuicEncryptedPacket& /*packet*/) {
161 DCHECK(IsConnectionIdInTimeWait(connection_id));
162 DVLOG(1) << "Processing " << connection_id << " in time wait state.";
163 // TODO(satyamshekhar): Think about handling packets from different client
164 // addresses.
165 ConnectionIdMap::iterator it = connection_id_map_.find(connection_id);
166 DCHECK(it != connection_id_map_.end());
167 // Increment the received packet count.
168 ConnectionIdData* connection_data = &it->second;
169 ++(connection_data->num_packets);
170 if (!ShouldSendResponse(connection_data->num_packets)) {
171 return;
173 if (connection_data->close_packet) {
174 QueuedPacket* queued_packet = new QueuedPacket(
175 server_address, client_address, connection_data->close_packet->Clone());
176 // Takes ownership of the packet.
177 SendOrQueuePacket(queued_packet);
178 } else if (!connection_data->connection_rejected_statelessly) {
179 SendPublicReset(server_address, client_address, connection_id,
180 packet_number);
181 } else {
182 DVLOG(3) << "Time wait list not sending response for connection "
183 << connection_id << " due to previous stateless reject.";
187 // Returns true if the number of packets received for this connection_id is a
188 // power of 2 to throttle the number of public reset packets we send to a
189 // client.
190 bool QuicTimeWaitListManager::ShouldSendResponse(int received_packet_count) {
191 return (received_packet_count & (received_packet_count - 1)) == 0;
194 void QuicTimeWaitListManager::SendPublicReset(
195 const IPEndPoint& server_address,
196 const IPEndPoint& client_address,
197 QuicConnectionId connection_id,
198 QuicPacketNumber rejected_packet_number) {
199 QuicPublicResetPacket packet;
200 packet.public_header.connection_id = connection_id;
201 packet.public_header.reset_flag = true;
202 packet.public_header.version_flag = false;
203 packet.rejected_packet_number = rejected_packet_number;
204 // TODO(satyamshekhar): generate a valid nonce for this connection_id.
205 packet.nonce_proof = 1010101;
206 packet.client_address = client_address;
207 QueuedPacket* queued_packet = new QueuedPacket(
208 server_address,
209 client_address,
210 BuildPublicReset(packet));
211 // Takes ownership of the packet.
212 SendOrQueuePacket(queued_packet);
215 QuicEncryptedPacket* QuicTimeWaitListManager::BuildPublicReset(
216 const QuicPublicResetPacket& packet) {
217 return QuicFramer::BuildPublicResetPacket(packet);
220 // Either sends the packet and deletes it or makes pending queue the
221 // owner of the packet.
222 void QuicTimeWaitListManager::SendOrQueuePacket(QueuedPacket* packet) {
223 if (WriteToWire(packet)) {
224 delete packet;
225 } else {
226 // pending_packets_queue takes the ownership of the queued packet.
227 pending_packets_queue_.push_back(packet);
231 bool QuicTimeWaitListManager::WriteToWire(QueuedPacket* queued_packet) {
232 if (writer_->IsWriteBlocked()) {
233 visitor_->OnWriteBlocked(this);
234 return false;
236 WriteResult result = writer_->WritePacket(
237 queued_packet->packet()->data(),
238 queued_packet->packet()->length(),
239 queued_packet->server_address().address(),
240 queued_packet->client_address());
241 if (result.status == WRITE_STATUS_BLOCKED) {
242 // If blocked and unbuffered, return false to retry sending.
243 DCHECK(writer_->IsWriteBlocked());
244 visitor_->OnWriteBlocked(this);
245 return writer_->IsWriteBlockedDataBuffered();
246 } else if (result.status == WRITE_STATUS_ERROR) {
247 LOG(WARNING) << "Received unknown error while sending reset packet to "
248 << queued_packet->client_address().ToString() << ": "
249 << strerror(result.error_code);
251 return true;
254 void QuicTimeWaitListManager::SetConnectionIdCleanUpAlarm() {
255 connection_id_clean_up_alarm_->Cancel();
256 QuicTime::Delta next_alarm_interval = QuicTime::Delta::Zero();
257 if (!connection_id_map_.empty()) {
258 QuicTime oldest_connection_id =
259 connection_id_map_.begin()->second.time_added;
260 QuicTime now = clock_->ApproximateNow();
261 if (now.Subtract(oldest_connection_id) < time_wait_period_) {
262 next_alarm_interval =
263 oldest_connection_id.Add(time_wait_period_).Subtract(now);
264 } else {
265 LOG(ERROR) << "ConnectionId lingered for longer than time_wait_period_";
267 } else {
268 // No connection_ids added so none will expire before time_wait_period_.
269 next_alarm_interval = time_wait_period_;
272 connection_id_clean_up_alarm_->Set(
273 clock_->ApproximateNow().Add(next_alarm_interval));
276 bool QuicTimeWaitListManager::MaybeExpireOldestConnection(
277 QuicTime expiration_time) {
278 if (connection_id_map_.empty()) {
279 return false;
281 ConnectionIdMap::iterator it = connection_id_map_.begin();
282 QuicTime oldest_connection_id_time = it->second.time_added;
283 if (oldest_connection_id_time > expiration_time) {
284 // Too recent, don't retire.
285 return false;
287 // This connection_id has lived its age, retire it now.
288 const QuicConnectionId connection_id = it->first;
289 delete it->second.close_packet;
290 connection_id_map_.erase(it);
291 visitor_->OnConnectionRemovedFromTimeWaitList(connection_id);
292 return true;
295 void QuicTimeWaitListManager::CleanUpOldConnectionIds() {
296 QuicTime now = clock_->ApproximateNow();
297 QuicTime expiration = now.Subtract(time_wait_period_);
299 while (MaybeExpireOldestConnection(expiration)) {
302 SetConnectionIdCleanUpAlarm();
305 void QuicTimeWaitListManager::TrimTimeWaitListIfNeeded() {
306 if (FLAGS_quic_time_wait_list_max_connections < 0) {
307 return;
309 while (num_connections() >=
310 static_cast<size_t>(FLAGS_quic_time_wait_list_max_connections)) {
311 MaybeExpireOldestConnection(QuicTime::Infinite());
315 } // namespace tools
316 } // namespace net