blob: 24d1eb8eb46bb14cce1afce6c95e81a68a5ceb81 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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.
4
5#include "net/third_party/quiche/src/quic/core/quic_utils.h"
6
7#include <algorithm>
8#include <cstdint>
vasilvv872e7a32019-03-12 16:42:44 -07009#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050010
11#include "net/third_party/quiche/src/quic/core/quic_constants.h"
12#include "net/third_party/quiche/src/quic/core/quic_types.h"
13#include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h"
14#include "net/third_party/quiche/src/quic/platform/api/quic_arraysize.h"
15#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
16#include "net/third_party/quiche/src/quic/platform/api/quic_endian.h"
17#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
18#include "net/third_party/quiche/src/quic/platform/api/quic_prefetch.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050019#include "net/third_party/quiche/src/quic/platform/api/quic_uint128.h"
20
21namespace quic {
22namespace {
23
24// We know that >= GCC 4.8 and Clang have a __uint128_t intrinsic. Other
25// compilers don't necessarily, notably MSVC.
26#if defined(__x86_64__) && \
27 ((defined(__GNUC__) && \
28 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) || \
29 defined(__clang__))
30#define QUIC_UTIL_HAS_UINT128 1
31#endif
32
33#ifdef QUIC_UTIL_HAS_UINT128
34QuicUint128 IncrementalHashFast(QuicUint128 uhash, QuicStringPiece data) {
35 // This code ends up faster than the naive implementation for 2 reasons:
36 // 1. QuicUint128 is sufficiently complicated that the compiler
37 // cannot transform the multiplication by kPrime into a shift-multiply-add;
38 // it has go through all of the instructions for a 128-bit multiply.
39 // 2. Because there are so fewer instructions (around 13), the hot loop fits
40 // nicely in the instruction queue of many Intel CPUs.
41 // kPrime = 309485009821345068724781371
42 static const QuicUint128 kPrime =
43 (static_cast<QuicUint128>(16777216) << 64) + 315;
44 auto hi = QuicUint128High64(uhash);
45 auto lo = QuicUint128Low64(uhash);
46 QuicUint128 xhash = (static_cast<QuicUint128>(hi) << 64) + lo;
47 const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data());
48 for (size_t i = 0; i < data.length(); ++i) {
49 xhash = (xhash ^ static_cast<uint32_t>(octets[i])) * kPrime;
50 }
51 return MakeQuicUint128(QuicUint128High64(xhash), QuicUint128Low64(xhash));
52}
53#endif
54
55#ifndef QUIC_UTIL_HAS_UINT128
56// Slow implementation of IncrementalHash. In practice, only used by Chromium.
57QuicUint128 IncrementalHashSlow(QuicUint128 hash, QuicStringPiece data) {
58 // kPrime = 309485009821345068724781371
59 static const QuicUint128 kPrime = MakeQuicUint128(16777216, 315);
60 const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data());
61 for (size_t i = 0; i < data.length(); ++i) {
62 hash = hash ^ MakeQuicUint128(0, octets[i]);
63 hash = hash * kPrime;
64 }
65 return hash;
66}
67#endif
68
69QuicUint128 IncrementalHash(QuicUint128 hash, QuicStringPiece data) {
70#ifdef QUIC_UTIL_HAS_UINT128
71 return IncrementalHashFast(hash, data);
72#else
73 return IncrementalHashSlow(hash, data);
74#endif
75}
76
77} // namespace
78
79// static
80uint64_t QuicUtils::FNV1a_64_Hash(QuicStringPiece data) {
81 static const uint64_t kOffset = UINT64_C(14695981039346656037);
82 static const uint64_t kPrime = UINT64_C(1099511628211);
83
84 const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data());
85
86 uint64_t hash = kOffset;
87
88 for (size_t i = 0; i < data.length(); ++i) {
89 hash = hash ^ octets[i];
90 hash = hash * kPrime;
91 }
92
93 return hash;
94}
95
96// static
97QuicUint128 QuicUtils::FNV1a_128_Hash(QuicStringPiece data) {
98 return FNV1a_128_Hash_Three(data, QuicStringPiece(), QuicStringPiece());
99}
100
101// static
102QuicUint128 QuicUtils::FNV1a_128_Hash_Two(QuicStringPiece data1,
103 QuicStringPiece data2) {
104 return FNV1a_128_Hash_Three(data1, data2, QuicStringPiece());
105}
106
107// static
108QuicUint128 QuicUtils::FNV1a_128_Hash_Three(QuicStringPiece data1,
109 QuicStringPiece data2,
110 QuicStringPiece data3) {
111 // The two constants are defined as part of the hash algorithm.
112 // see http://www.isthe.com/chongo/tech/comp/fnv/
113 // kOffset = 144066263297769815596495629667062367629
114 const QuicUint128 kOffset = MakeQuicUint128(UINT64_C(7809847782465536322),
115 UINT64_C(7113472399480571277));
116
117 QuicUint128 hash = IncrementalHash(kOffset, data1);
118 if (data2.empty()) {
119 return hash;
120 }
121
122 hash = IncrementalHash(hash, data2);
123 if (data3.empty()) {
124 return hash;
125 }
126 return IncrementalHash(hash, data3);
127}
128
129// static
130void QuicUtils::SerializeUint128Short(QuicUint128 v, uint8_t* out) {
131 const uint64_t lo = QuicUint128Low64(v);
132 const uint64_t hi = QuicUint128High64(v);
133 // This assumes that the system is little-endian.
134 memcpy(out, &lo, sizeof(lo));
135 memcpy(out + sizeof(lo), &hi, sizeof(hi) / 2);
136}
137
138#define RETURN_STRING_LITERAL(x) \
139 case x: \
140 return #x;
141
142// static
143const char* QuicUtils::EncryptionLevelToString(EncryptionLevel level) {
144 switch (level) {
145 RETURN_STRING_LITERAL(ENCRYPTION_NONE);
146 RETURN_STRING_LITERAL(ENCRYPTION_ZERO_RTT);
147 RETURN_STRING_LITERAL(ENCRYPTION_FORWARD_SECURE);
148 RETURN_STRING_LITERAL(NUM_ENCRYPTION_LEVELS);
149 }
150 return "INVALID_ENCRYPTION_LEVEL";
151}
152
153// static
154const char* QuicUtils::TransmissionTypeToString(TransmissionType type) {
155 switch (type) {
156 RETURN_STRING_LITERAL(NOT_RETRANSMISSION);
157 RETURN_STRING_LITERAL(HANDSHAKE_RETRANSMISSION);
158 RETURN_STRING_LITERAL(LOSS_RETRANSMISSION);
159 RETURN_STRING_LITERAL(ALL_UNACKED_RETRANSMISSION);
160 RETURN_STRING_LITERAL(ALL_INITIAL_RETRANSMISSION);
161 RETURN_STRING_LITERAL(RTO_RETRANSMISSION);
162 RETURN_STRING_LITERAL(TLP_RETRANSMISSION);
163 RETURN_STRING_LITERAL(PROBING_RETRANSMISSION);
164 }
165 return "INVALID_TRANSMISSION_TYPE";
166}
167
vasilvvc48c8712019-03-11 13:38:16 -0700168std::string QuicUtils::AddressChangeTypeToString(AddressChangeType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500169 switch (type) {
170 RETURN_STRING_LITERAL(NO_CHANGE);
171 RETURN_STRING_LITERAL(PORT_CHANGE);
172 RETURN_STRING_LITERAL(IPV4_SUBNET_CHANGE);
173 RETURN_STRING_LITERAL(IPV4_TO_IPV6_CHANGE);
174 RETURN_STRING_LITERAL(IPV6_TO_IPV4_CHANGE);
175 RETURN_STRING_LITERAL(IPV6_TO_IPV6_CHANGE);
176 RETURN_STRING_LITERAL(IPV4_TO_IPV4_CHANGE);
177 }
178 return "INVALID_ADDRESS_CHANGE_TYPE";
179}
180
181const char* QuicUtils::SentPacketStateToString(SentPacketState state) {
182 switch (state) {
183 RETURN_STRING_LITERAL(OUTSTANDING);
184 RETURN_STRING_LITERAL(NEVER_SENT);
185 RETURN_STRING_LITERAL(ACKED);
186 RETURN_STRING_LITERAL(UNACKABLE);
187 RETURN_STRING_LITERAL(HANDSHAKE_RETRANSMITTED);
188 RETURN_STRING_LITERAL(LOST);
189 RETURN_STRING_LITERAL(TLP_RETRANSMITTED);
190 RETURN_STRING_LITERAL(RTO_RETRANSMITTED);
191 RETURN_STRING_LITERAL(PROBE_RETRANSMITTED);
192 }
193 return "INVALID_SENT_PACKET_STATE";
194}
195
196// static
197const char* QuicUtils::QuicLongHeaderTypetoString(QuicLongHeaderType type) {
198 switch (type) {
199 RETURN_STRING_LITERAL(VERSION_NEGOTIATION);
200 RETURN_STRING_LITERAL(INITIAL);
201 RETURN_STRING_LITERAL(RETRY);
202 RETURN_STRING_LITERAL(HANDSHAKE);
203 RETURN_STRING_LITERAL(ZERO_RTT_PROTECTED);
204 default:
205 return "INVALID_PACKET_TYPE";
206 }
207}
208
209// static
210AddressChangeType QuicUtils::DetermineAddressChangeType(
211 const QuicSocketAddress& old_address,
212 const QuicSocketAddress& new_address) {
213 if (!old_address.IsInitialized() || !new_address.IsInitialized() ||
214 old_address == new_address) {
215 return NO_CHANGE;
216 }
217
218 if (old_address.host() == new_address.host()) {
219 return PORT_CHANGE;
220 }
221
222 bool old_ip_is_ipv4 = old_address.host().IsIPv4() ? true : false;
223 bool migrating_ip_is_ipv4 = new_address.host().IsIPv4() ? true : false;
224 if (old_ip_is_ipv4 && !migrating_ip_is_ipv4) {
225 return IPV4_TO_IPV6_CHANGE;
226 }
227
228 if (!old_ip_is_ipv4) {
229 return migrating_ip_is_ipv4 ? IPV6_TO_IPV4_CHANGE : IPV6_TO_IPV6_CHANGE;
230 }
231
232 const int kSubnetMaskLength = 24;
233 if (old_address.host().InSameSubnet(new_address.host(), kSubnetMaskLength)) {
234 // Subnet part does not change (here, we use /24), which is considered to be
235 // caused by NATs.
236 return IPV4_SUBNET_CHANGE;
237 }
238
239 return IPV4_TO_IPV4_CHANGE;
240}
241
242// static
243void QuicUtils::CopyToBuffer(const struct iovec* iov,
244 int iov_count,
245 size_t iov_offset,
246 size_t buffer_length,
247 char* buffer) {
248 int iovnum = 0;
249 while (iovnum < iov_count && iov_offset >= iov[iovnum].iov_len) {
250 iov_offset -= iov[iovnum].iov_len;
251 ++iovnum;
252 }
253 DCHECK_LE(iovnum, iov_count);
254 DCHECK_LE(iov_offset, iov[iovnum].iov_len);
255 if (iovnum >= iov_count || buffer_length == 0) {
256 return;
257 }
258
259 // Unroll the first iteration that handles iov_offset.
260 const size_t iov_available = iov[iovnum].iov_len - iov_offset;
261 size_t copy_len = std::min(buffer_length, iov_available);
262
263 // Try to prefetch the next iov if there is at least one more after the
264 // current. Otherwise, it looks like an irregular access that the hardware
265 // prefetcher won't speculatively prefetch. Only prefetch one iov because
266 // generally, the iov_offset is not 0, input iov consists of 2K buffers and
267 // the output buffer is ~1.4K.
268 if (copy_len == iov_available && iovnum + 1 < iov_count) {
269 char* next_base = static_cast<char*>(iov[iovnum + 1].iov_base);
270 // Prefetch 2 cachelines worth of data to get the prefetcher started; leave
271 // it to the hardware prefetcher after that.
272 QuicPrefetchT0(next_base);
273 if (iov[iovnum + 1].iov_len >= 64) {
274 QuicPrefetchT0(next_base + QUIC_CACHELINE_SIZE);
275 }
276 }
277
278 const char* src = static_cast<char*>(iov[iovnum].iov_base) + iov_offset;
279 while (true) {
280 memcpy(buffer, src, copy_len);
281 buffer_length -= copy_len;
282 buffer += copy_len;
283 if (buffer_length == 0 || ++iovnum >= iov_count) {
284 break;
285 }
286 src = static_cast<char*>(iov[iovnum].iov_base);
287 copy_len = std::min(buffer_length, iov[iovnum].iov_len);
288 }
289 QUIC_BUG_IF(buffer_length > 0) << "Failed to copy entire length to buffer.";
290}
291
292// static
293struct iovec QuicUtils::MakeIovec(QuicStringPiece data) {
294 struct iovec iov = {const_cast<char*>(data.data()),
295 static_cast<size_t>(data.size())};
296 return iov;
297}
298
299// static
300bool QuicUtils::IsAckable(SentPacketState state) {
301 return state != NEVER_SENT && state != ACKED && state != UNACKABLE;
302}
303
304// static
305bool QuicUtils::IsRetransmittableFrame(QuicFrameType type) {
306 switch (type) {
307 case ACK_FRAME:
308 case PADDING_FRAME:
309 case STOP_WAITING_FRAME:
310 case MTU_DISCOVERY_FRAME:
311 return false;
312 default:
313 return true;
314 }
315}
316
317// static
318bool QuicUtils::IsHandshakeFrame(const QuicFrame& frame,
319 QuicTransportVersion transport_version) {
QUICHE teamea740082019-03-11 17:58:43 -0700320 if (!QuicVersionUsesCryptoFrames(transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500321 return frame.type == STREAM_FRAME &&
322 frame.stream_frame.stream_id == GetCryptoStreamId(transport_version);
323 } else {
324 return frame.type == CRYPTO_FRAME;
325 }
326}
327
328// static
329SentPacketState QuicUtils::RetransmissionTypeToPacketState(
330 TransmissionType retransmission_type) {
331 switch (retransmission_type) {
332 case ALL_UNACKED_RETRANSMISSION:
333 case ALL_INITIAL_RETRANSMISSION:
334 return UNACKABLE;
335 case HANDSHAKE_RETRANSMISSION:
336 return HANDSHAKE_RETRANSMITTED;
337 case LOSS_RETRANSMISSION:
338 return LOST;
339 case TLP_RETRANSMISSION:
340 return TLP_RETRANSMITTED;
341 case RTO_RETRANSMISSION:
342 return RTO_RETRANSMITTED;
343 case PROBING_RETRANSMISSION:
344 return PROBE_RETRANSMITTED;
345 default:
346 QUIC_BUG << QuicUtils::TransmissionTypeToString(retransmission_type)
347 << " is not a retransmission_type";
348 return UNACKABLE;
349 }
350}
351
352// static
353bool QuicUtils::IsIetfPacketHeader(uint8_t first_byte) {
354 return (first_byte & FLAGS_LONG_HEADER) || (first_byte & FLAGS_FIXED_BIT) ||
355 !(first_byte & FLAGS_DEMULTIPLEXING_BIT);
356}
357
358// static
359bool QuicUtils::IsIetfPacketShortHeader(uint8_t first_byte) {
360 return IsIetfPacketHeader(first_byte) && !(first_byte & FLAGS_LONG_HEADER);
361}
362
363// static
364QuicStreamId QuicUtils::GetInvalidStreamId(QuicTransportVersion version) {
365 return version == QUIC_VERSION_99 ? std::numeric_limits<QuicStreamId>::max()
366 : 0;
367}
368
369// static
370QuicStreamId QuicUtils::GetCryptoStreamId(QuicTransportVersion version) {
371 // TODO(nharper): Change this to return GetInvalidStreamId for version 47 or
372 // greater. Currently, too many things break with that change.
373 return version == QUIC_VERSION_99 ? 0 : 1;
374}
375
376// static
377QuicStreamId QuicUtils::GetHeadersStreamId(QuicTransportVersion version) {
378 return version == QUIC_VERSION_99 ? 4 : 3;
379}
380
381// static
382bool QuicUtils::IsClientInitiatedStreamId(QuicTransportVersion version,
383 QuicStreamId id) {
384 if (id == GetInvalidStreamId(version)) {
385 return false;
386 }
387 return version == QUIC_VERSION_99 ? id % 2 == 0 : id % 2 != 0;
388}
389
390// static
391bool QuicUtils::IsServerInitiatedStreamId(QuicTransportVersion version,
392 QuicStreamId id) {
393 if (id == GetInvalidStreamId(version)) {
394 return false;
395 }
396 return version == QUIC_VERSION_99 ? id % 2 != 0 : id % 2 == 0;
397}
398
399// static
400bool QuicUtils::IsBidirectionalStreamId(QuicStreamId id) {
401 return id % 4 < 2;
402}
403
404// static
405StreamType QuicUtils::GetStreamType(QuicStreamId id,
406 Perspective perspective,
407 bool peer_initiated) {
408 if (IsBidirectionalStreamId(id)) {
409 return BIDIRECTIONAL;
410 }
411
412 if (peer_initiated) {
413 if (perspective == Perspective::IS_SERVER) {
414 DCHECK_EQ(2u, id % 4);
415 } else {
416 DCHECK_EQ(Perspective::IS_CLIENT, perspective);
417 DCHECK_EQ(3u, id % 4);
418 }
419 return READ_UNIDIRECTIONAL;
420 }
421
422 if (perspective == Perspective::IS_SERVER) {
423 DCHECK_EQ(3u, id % 4);
424 } else {
425 DCHECK_EQ(Perspective::IS_CLIENT, perspective);
426 DCHECK_EQ(2u, id % 4);
427 }
428 return WRITE_UNIDIRECTIONAL;
429}
430
431// static
432QuicStreamId QuicUtils::StreamIdDelta(QuicTransportVersion version) {
433 return version == QUIC_VERSION_99 ? 4 : 2;
434}
435
436// static
437QuicStreamId QuicUtils::GetFirstBidirectionalStreamId(
438 QuicTransportVersion version,
439 Perspective perspective) {
440 if (perspective == Perspective::IS_CLIENT) {
441 return version == QUIC_VERSION_99 ? 4 : 3;
442 }
443 return version == QUIC_VERSION_99 ? 1 : 2;
444}
445
446// static
447QuicStreamId QuicUtils::GetFirstUnidirectionalStreamId(
448 QuicTransportVersion version,
449 Perspective perspective) {
450 if (perspective == Perspective::IS_CLIENT) {
451 return version == QUIC_VERSION_99 ? 2 : 3;
452 }
453 return version == QUIC_VERSION_99 ? 3 : 2;
454}
455
456// static
457QuicConnectionId QuicUtils::CreateRandomConnectionId() {
458 return CreateRandomConnectionId(QuicRandom::GetInstance());
459}
460
461// static
462QuicConnectionId QuicUtils::CreateRandomConnectionId(QuicRandom* random) {
463 char connection_id_bytes[kQuicDefaultConnectionIdLength];
464 random->RandBytes(connection_id_bytes, QUIC_ARRAYSIZE(connection_id_bytes));
465 return QuicConnectionId(static_cast<char*>(connection_id_bytes),
466 QUIC_ARRAYSIZE(connection_id_bytes));
467}
468
469// static
470bool QuicUtils::VariableLengthConnectionIdAllowedForVersion(
471 QuicTransportVersion version) {
472 // TODO(dschinazi): Allow in appropriate version when supported.
473 return false;
474}
475
476// static
477QuicConnectionId QuicUtils::CreateZeroConnectionId(
478 QuicTransportVersion version) {
479 if (!VariableLengthConnectionIdAllowedForVersion(version)) {
480 char connection_id_bytes[8] = {0, 0, 0, 0, 0, 0, 0, 0};
481 return QuicConnectionId(static_cast<char*>(connection_id_bytes),
482 QUIC_ARRAYSIZE(connection_id_bytes));
483 }
484 return EmptyQuicConnectionId();
485}
486
487// static
488bool QuicUtils::IsConnectionIdValidForVersion(QuicConnectionId connection_id,
489 QuicTransportVersion version) {
490 if (VariableLengthConnectionIdAllowedForVersion(version)) {
491 return true;
492 }
493 return connection_id.length() == kQuicDefaultConnectionIdLength;
494}
495
496QuicUint128 QuicUtils::GenerateStatelessResetToken(
497 QuicConnectionId connection_id) {
498 uint64_t data_bytes[3] = {0, 0, 0};
499 static_assert(sizeof(data_bytes) >= kQuicMaxConnectionIdLength,
500 "kQuicMaxConnectionIdLength changed");
501 memcpy(data_bytes, connection_id.data(), connection_id.length());
502 // This is designed so that the common case of 64bit connection IDs
503 // produces a stateless reset token that is equal to the connection ID
504 // interpreted as a 64bit unsigned integer, to facilitate debugging.
505 return MakeQuicUint128(
506 QuicEndian::NetToHost64(sizeof(uint64_t) ^ connection_id.length() ^
507 data_bytes[1] ^ data_bytes[2]),
508 QuicEndian::NetToHost64(data_bytes[0]));
509}
510
511#undef RETURN_STRING_LITERAL // undef for jumbo builds
512} // namespace quic