1 // Copyright (c) 2013 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/crypto/strike_register.h"
9 #include "base/logging.h"
19 uint32
GetInitialHorizon(uint32 current_time_internal
,
21 StrikeRegister::StartupType startup
) {
22 if (startup
== StrikeRegister::DENY_REQUESTS_AT_STARTUP
) {
23 // The horizon is initially set |window_secs| into the future because, if
24 // we just crashed, then we may have accepted nonces in the span
25 // [current_time...current_time+window_secs] and so we conservatively
26 // reject the whole timespan unless |startup| tells us otherwise.
27 return current_time_internal
+ window_secs
+ 1;
28 } else { // startup == StrikeRegister::NO_STARTUP_PERIOD_NEEDED
29 // The orbit can be assumed to be globally unique. Use a horizon
38 const uint32
StrikeRegister::kExternalNodeSize
= 24;
40 const uint32
StrikeRegister::kNil
= (1u << 31) | 1;
42 const uint32
StrikeRegister::kExternalFlag
= 1 << 23;
44 // InternalNode represents a non-leaf node in the critbit tree. See the comment
45 // in the .h file for details.
46 class StrikeRegister::InternalNode
{
48 void SetChild(unsigned direction
, uint32 child
) {
49 data_
[direction
] = (data_
[direction
] & 0xff) | (child
<< 8);
52 void SetCritByte(uint8 critbyte
) {
53 data_
[0] = (data_
[0] & 0xffffff00) | critbyte
;
56 void SetOtherBits(uint8 otherbits
) {
57 data_
[1] = (data_
[1] & 0xffffff00) | otherbits
;
60 void SetNextPtr(uint32 next
) { data_
[0] = next
; }
62 uint32
next() const { return data_
[0]; }
64 uint32
child(unsigned n
) const { return data_
[n
] >> 8; }
66 uint8
critbyte() const { return static_cast<uint8
>(data_
[0]); }
68 uint8
otherbits() const { return static_cast<uint8
>(data_
[1]); }
70 // These bytes are organised thus:
71 // <24 bits> left child
73 // <24 bits> right child
74 // <8 bits> other-bits
78 // kCreationTimeFromInternalEpoch contains the number of seconds between the
79 // start of the internal epoch and the creation time. This allows us
80 // to consider times that are before the creation time.
81 static const uint32 kCreationTimeFromInternalEpoch
= 63115200; // 2 years.
83 void StrikeRegister::ValidateStrikeRegisterConfig(unsigned max_entries
) {
84 // We only have 23 bits of index available.
85 CHECK_LT(max_entries
, 1u << 23);
86 CHECK_GT(max_entries
, 1u); // There must be at least two entries.
87 CHECK_EQ(sizeof(InternalNode
), 8u); // in case of compiler changes.
90 StrikeRegister::StrikeRegister(unsigned max_entries
,
95 : max_entries_(max_entries
),
96 window_secs_(window_secs
),
97 internal_epoch_(current_time
> kCreationTimeFromInternalEpoch
98 ? current_time
- kCreationTimeFromInternalEpoch
100 horizon_(GetInitialHorizon(
101 ExternalTimeToInternal(current_time
), window_secs
, startup
)) {
102 memcpy(orbit_
, orbit
, sizeof(orbit_
));
104 ValidateStrikeRegisterConfig(max_entries
);
105 internal_nodes_
= new InternalNode
[max_entries
];
106 external_nodes_
.reset(new uint8
[kExternalNodeSize
* max_entries
]);
111 StrikeRegister::~StrikeRegister() { delete[] internal_nodes_
; }
113 void StrikeRegister::Reset() {
114 // Thread a free list through all of the internal nodes.
115 internal_node_free_head_
= 0;
116 for (unsigned i
= 0; i
< max_entries_
- 1; i
++) {
117 internal_nodes_
[i
].SetNextPtr(i
+ 1);
119 internal_nodes_
[max_entries_
- 1].SetNextPtr(kNil
);
121 // Also thread a free list through the external nodes.
122 external_node_free_head_
= 0;
123 for (unsigned i
= 0; i
< max_entries_
- 1; i
++) {
124 external_node_next_ptr(i
) = i
+ 1;
126 external_node_next_ptr(max_entries_
- 1) = kNil
;
128 // This is the root of the tree.
129 internal_node_head_
= kNil
;
132 InsertStatus
StrikeRegister::Insert(const uint8 nonce
[32],
133 uint32 current_time_external
) {
134 // Make space for the insertion if the strike register is full.
135 while (external_node_free_head_
== kNil
||
136 internal_node_free_head_
== kNil
) {
140 const uint32 current_time
= ExternalTimeToInternal(current_time_external
);
142 // Check to see if the orbit is correct.
143 if (memcmp(nonce
+ sizeof(current_time
), orbit_
, sizeof(orbit_
))) {
144 return NONCE_INVALID_ORBIT_FAILURE
;
147 const uint32 nonce_time
= ExternalTimeToInternal(TimeFromBytes(nonce
));
149 // Check that the timestamp is in the valid range.
150 pair
<uint32
, uint32
> valid_range
=
151 StrikeRegister::GetValidRange(current_time
);
152 if (nonce_time
< valid_range
.first
|| nonce_time
> valid_range
.second
) {
153 return NONCE_INVALID_TIME_FAILURE
;
156 // We strip the orbit out of the nonce.
158 memcpy(value
, nonce
, sizeof(nonce_time
));
159 memcpy(value
+ sizeof(nonce_time
),
160 nonce
+ sizeof(nonce_time
) + sizeof(orbit_
),
161 sizeof(value
) - sizeof(nonce_time
));
163 // Find the best match to |value| in the crit-bit tree. The best match is
164 // simply the value which /could/ match |value|, if any does, so we still
165 // need a memcmp to check.
166 uint32 best_match_index
= BestMatch(value
);
167 if (best_match_index
== kNil
) {
168 // Empty tree. Just insert the new value at the root.
169 uint32 index
= GetFreeExternalNode();
170 memcpy(external_node(index
), value
, sizeof(value
));
171 internal_node_head_
= (index
| kExternalFlag
) << 8;
172 DCHECK_LE(horizon_
, nonce_time
);
176 const uint8
* best_match
= external_node(best_match_index
);
177 if (memcmp(best_match
, value
, sizeof(value
)) == 0) {
178 // We found the value in the tree.
179 return NONCE_NOT_UNIQUE_FAILURE
;
182 // We are going to insert a new entry into the tree, so get the nodes now.
183 uint32 internal_node_index
= GetFreeInternalNode();
184 uint32 external_node_index
= GetFreeExternalNode();
186 // If we just evicted the best match, then we have to try and match again.
187 // We know that we didn't just empty the tree because we require that
188 // max_entries_ >= 2. Also, we know that it doesn't match because, if it
189 // did, it would have been returned previously.
190 if (external_node_index
== best_match_index
) {
191 best_match_index
= BestMatch(value
);
192 best_match
= external_node(best_match_index
);
195 // Now we need to find the first bit where we differ from |best_match|.
196 uint8 differing_byte
;
197 uint8 new_other_bits
;
198 for (differing_byte
= 0; differing_byte
< arraysize(value
);
200 new_other_bits
= value
[differing_byte
] ^ best_match
[differing_byte
];
201 if (new_other_bits
) {
206 // Once we have the XOR the of first differing byte in new_other_bits we need
207 // to find the most significant differing bit. We could do this with a simple
208 // for loop, testing bits 7..0. Instead we fold the bits so that we end up
209 // with a byte where all the bits below the most significant one, are set.
210 new_other_bits
|= new_other_bits
>> 1;
211 new_other_bits
|= new_other_bits
>> 2;
212 new_other_bits
|= new_other_bits
>> 4;
213 // Now this bit trick results in all the bits set, except the original
214 // most-significant one.
215 new_other_bits
= (new_other_bits
& ~(new_other_bits
>> 1)) ^ 255;
217 // Consider the effect of ORing against |new_other_bits|. If |value| did not
218 // have the critical bit set, the result is the same as |new_other_bits|. If
219 // it did, the result is all ones.
221 unsigned newdirection
;
222 if ((new_other_bits
| value
[differing_byte
]) == 0xff) {
228 memcpy(external_node(external_node_index
), value
, sizeof(value
));
229 InternalNode
* inode
= &internal_nodes_
[internal_node_index
];
231 inode
->SetChild(newdirection
, external_node_index
| kExternalFlag
);
232 inode
->SetCritByte(differing_byte
);
233 inode
->SetOtherBits(new_other_bits
);
235 // |where_index| is a pointer to the uint32 which needs to be updated in
236 // order to insert the new internal node into the tree. The internal nodes
237 // store the child indexes in the top 24-bits of a 32-bit word and, to keep
238 // the code simple, we define that |internal_node_head_| is organised the
240 DCHECK_EQ(internal_node_head_
& 0xff, 0u);
241 uint32
* where_index
= &internal_node_head_
;
242 while (((*where_index
>> 8) & kExternalFlag
) == 0) {
243 InternalNode
* node
= &internal_nodes_
[*where_index
>> 8];
244 if (node
->critbyte() > differing_byte
) {
247 if (node
->critbyte() == differing_byte
&&
248 node
->otherbits() > new_other_bits
) {
251 if (node
->critbyte() == differing_byte
&&
252 node
->otherbits() == new_other_bits
) {
256 uint8 c
= value
[node
->critbyte()];
257 const int direction
=
258 (1 + static_cast<unsigned>(node
->otherbits() | c
)) >> 8;
259 where_index
= &node
->data_
[direction
];
262 inode
->SetChild(newdirection
^ 1, *where_index
>> 8);
263 *where_index
= (*where_index
& 0xff) | (internal_node_index
<< 8);
265 DCHECK_LE(horizon_
, nonce_time
);
269 const uint8
* StrikeRegister::orbit() const {
273 uint32
StrikeRegister::GetCurrentValidWindowSecs(
274 uint32 current_time_external
) const {
275 uint32 current_time
= ExternalTimeToInternal(current_time_external
);
276 pair
<uint32
, uint32
> valid_range
= StrikeRegister::GetValidRange(
278 if (valid_range
.second
>= valid_range
.first
) {
279 return valid_range
.second
- current_time
+ 1;
285 void StrikeRegister::Validate() {
286 set
<uint32
> free_internal_nodes
;
287 for (uint32 i
= internal_node_free_head_
; i
!= kNil
;
288 i
= internal_nodes_
[i
].next()) {
289 CHECK_LT(i
, max_entries_
);
290 CHECK_EQ(free_internal_nodes
.count(i
), 0u);
291 free_internal_nodes
.insert(i
);
294 set
<uint32
> free_external_nodes
;
295 for (uint32 i
= external_node_free_head_
; i
!= kNil
;
296 i
= external_node_next_ptr(i
)) {
297 CHECK_LT(i
, max_entries_
);
298 CHECK_EQ(free_external_nodes
.count(i
), 0u);
299 free_external_nodes
.insert(i
);
302 set
<uint32
> used_external_nodes
;
303 set
<uint32
> used_internal_nodes
;
305 if (internal_node_head_
!= kNil
&&
306 ((internal_node_head_
>> 8) & kExternalFlag
) == 0) {
307 vector
<pair
<unsigned, bool>> bits
;
308 ValidateTree(internal_node_head_
>> 8, -1, bits
, free_internal_nodes
,
309 free_external_nodes
, &used_internal_nodes
,
310 &used_external_nodes
);
315 uint32
StrikeRegister::TimeFromBytes(const uint8 d
[4]) {
316 return static_cast<uint32
>(d
[0]) << 24 |
317 static_cast<uint32
>(d
[1]) << 16 |
318 static_cast<uint32
>(d
[2]) << 8 |
319 static_cast<uint32
>(d
[3]);
322 pair
<uint32
, uint32
> StrikeRegister::GetValidRange(
323 uint32 current_time_internal
) const {
324 if (current_time_internal
< horizon_
) {
325 // Empty valid range.
326 return std::make_pair(std::numeric_limits
<uint32
>::max(), 0);
330 if (current_time_internal
>= window_secs_
) {
331 lower_bound
= std::max(horizon_
, current_time_internal
- window_secs_
);
333 lower_bound
= horizon_
;
336 // Also limit the upper range based on horizon_. This makes the
337 // strike register reject inserts that are far in the future and
338 // would consume strike register resources for a long time. This
339 // allows the strike server to degrade optimally in cases where the
340 // insert rate exceeds |max_entries_ / (2 * window_secs_)| entries
342 uint32 upper_bound
= current_time_internal
+
343 std::min(current_time_internal
- horizon_
, window_secs_
);
345 return std::make_pair(lower_bound
, upper_bound
);
348 uint32
StrikeRegister::ExternalTimeToInternal(uint32 external_time
) const {
349 return external_time
- internal_epoch_
;
352 uint32
StrikeRegister::BestMatch(const uint8 v
[24]) const {
353 if (internal_node_head_
== kNil
) {
357 uint32 next
= internal_node_head_
>> 8;
358 while ((next
& kExternalFlag
) == 0) {
359 InternalNode
* node
= &internal_nodes_
[next
];
360 uint8 b
= v
[node
->critbyte()];
362 (1 + static_cast<unsigned>(node
->otherbits() | b
)) >> 8;
363 next
= node
->child(direction
);
366 return next
& ~kExternalFlag
;
369 uint32
& StrikeRegister::external_node_next_ptr(unsigned i
) {
370 return *reinterpret_cast<uint32
*>(&external_nodes_
[i
* kExternalNodeSize
]);
373 uint8
* StrikeRegister::external_node(unsigned i
) {
374 return &external_nodes_
[i
* kExternalNodeSize
];
377 uint32
StrikeRegister::GetFreeExternalNode() {
378 uint32 index
= external_node_free_head_
;
379 DCHECK(index
!= kNil
);
380 external_node_free_head_
= external_node_next_ptr(index
);
384 uint32
StrikeRegister::GetFreeInternalNode() {
385 uint32 index
= internal_node_free_head_
;
386 DCHECK(index
!= kNil
);
387 internal_node_free_head_
= internal_nodes_
[index
].next();
391 void StrikeRegister::DropOldestNode() {
392 // DropOldestNode should never be called on an empty tree.
393 DCHECK(internal_node_head_
!= kNil
);
395 // An internal node in a crit-bit tree always has exactly two children.
396 // This means that, if we are removing an external node (which is one of
397 // those children), then we also need to remove an internal node. In order
398 // to do that we keep pointers to the parent (wherep) and grandparent
399 // (whereq) when walking down the tree.
401 uint32 p
= internal_node_head_
>> 8, *wherep
= &internal_node_head_
,
403 while ((p
& kExternalFlag
) == 0) {
405 InternalNode
* inode
= &internal_nodes_
[p
];
406 // We always go left, towards the smallest element, exploiting the fact
407 // that the timestamp is big-endian and at the start of the value.
408 wherep
= &inode
->data_
[0];
412 const uint32 ext_index
= p
& ~kExternalFlag
;
413 const uint8
* ext_node
= external_node(ext_index
);
414 uint32 new_horizon
= ExternalTimeToInternal(TimeFromBytes(ext_node
)) + 1;
415 DCHECK_LE(horizon_
, new_horizon
);
416 horizon_
= new_horizon
;
419 // We are removing the last element in a tree.
420 internal_node_head_
= kNil
;
421 FreeExternalNode(ext_index
);
425 // |wherep| points to the left child pointer in the parent so we can add
426 // one and dereference to get the right child.
427 const uint32 other_child
= wherep
[1];
428 FreeInternalNode((*whereq
) >> 8);
429 *whereq
= (*whereq
& 0xff) | (other_child
& 0xffffff00);
430 FreeExternalNode(ext_index
);
433 void StrikeRegister::FreeExternalNode(uint32 index
) {
434 external_node_next_ptr(index
) = external_node_free_head_
;
435 external_node_free_head_
= index
;
438 void StrikeRegister::FreeInternalNode(uint32 index
) {
439 internal_nodes_
[index
].SetNextPtr(internal_node_free_head_
);
440 internal_node_free_head_
= index
;
443 void StrikeRegister::ValidateTree(uint32 internal_node
,
445 const vector
<pair
<unsigned, bool>>& bits
,
446 const set
<uint32
>& free_internal_nodes
,
447 const set
<uint32
>& free_external_nodes
,
448 set
<uint32
>* used_internal_nodes
,
449 set
<uint32
>* used_external_nodes
) {
450 CHECK_LT(internal_node
, max_entries_
);
451 const InternalNode
* i
= &internal_nodes_
[internal_node
];
453 switch (i
->otherbits()) {
454 case 0xff & ~(1 << 7):
457 case 0xff & ~(1 << 6):
460 case 0xff & ~(1 << 5):
463 case 0xff & ~(1 << 4):
466 case 0xff & ~(1 << 3):
469 case 0xff & ~(1 << 2):
472 case 0xff & ~(1 << 1):
482 bit
+= 8 * i
->critbyte();
484 CHECK_GT(bit
, static_cast<unsigned>(last_bit
));
487 CHECK_EQ(free_internal_nodes
.count(internal_node
), 0u);
489 for (unsigned child
= 0; child
< 2; child
++) {
490 if (i
->child(child
) & kExternalFlag
) {
491 uint32 ext
= i
->child(child
) & ~kExternalFlag
;
492 CHECK_EQ(free_external_nodes
.count(ext
), 0u);
493 CHECK_EQ(used_external_nodes
->count(ext
), 0u);
494 used_external_nodes
->insert(ext
);
495 const uint8
* bytes
= external_node(ext
);
496 for (const pair
<unsigned, bool>& pair
: bits
) {
497 unsigned byte
= pair
.first
/ 8;
498 DCHECK_LE(byte
, 0xffu
);
499 unsigned bit_new
= pair
.first
% 8;
500 static const uint8 kMasks
[8] =
501 {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
502 CHECK_EQ((bytes
[byte
] & kMasks
[bit_new
]) != 0, pair
.second
);
505 uint32 inter
= i
->child(child
);
506 vector
<pair
<unsigned, bool>> new_bits(bits
);
507 new_bits
.push_back(pair
<unsigned, bool>(bit
, child
!= 0));
508 CHECK_EQ(free_internal_nodes
.count(inter
), 0u);
509 CHECK_EQ(used_internal_nodes
->count(inter
), 0u);
510 used_internal_nodes
->insert(inter
);
511 ValidateTree(inter
, bit
, bits
, free_internal_nodes
, free_external_nodes
,
512 used_internal_nodes
, used_external_nodes
);