xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/internet_checksum_test.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2019 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 "quiche/quic/core/internet_checksum.h"
6 
7 #include "quiche/quic/platform/api/quic_test.h"
8 
9 namespace quic {
10 namespace {
11 
12 // From the Numerical Example described in RFC 1071
13 // https://tools.ietf.org/html/rfc1071#section-3
TEST(InternetChecksumTest,MatchesRFC1071Example)14 TEST(InternetChecksumTest, MatchesRFC1071Example) {
15   uint8_t data[] = {0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6, 0xf7};
16 
17   InternetChecksum checksum;
18   checksum.Update(data, 8);
19   uint16_t result = checksum.Value();
20   auto* result_bytes = reinterpret_cast<uint8_t*>(&result);
21   ASSERT_EQ(0x22, result_bytes[0]);
22   ASSERT_EQ(0x0d, result_bytes[1]);
23 }
24 
25 // Same as above, except 7 bytes. Should behave as if there was an 8th byte
26 // that equals 0.
TEST(InternetChecksumTest,MatchesRFC1071ExampleWithOddByteCount)27 TEST(InternetChecksumTest, MatchesRFC1071ExampleWithOddByteCount) {
28   uint8_t data[] = {0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6};
29 
30   InternetChecksum checksum;
31   checksum.Update(data, 7);
32   uint16_t result = checksum.Value();
33   auto* result_bytes = reinterpret_cast<uint8_t*>(&result);
34   ASSERT_EQ(0x23, result_bytes[0]);
35   ASSERT_EQ(0x04, result_bytes[1]);
36 }
37 
38 // From the example described at:
39 // http://www.cs.berkeley.edu/~kfall/EE122/lec06/tsld023.htm
TEST(InternetChecksumTest,MatchesBerkleyExample)40 TEST(InternetChecksumTest, MatchesBerkleyExample) {
41   uint8_t data[] = {0xe3, 0x4f, 0x23, 0x96, 0x44, 0x27, 0x99, 0xf3};
42 
43   InternetChecksum checksum;
44   checksum.Update(data, 8);
45   uint16_t result = checksum.Value();
46   auto* result_bytes = reinterpret_cast<uint8_t*>(&result);
47   ASSERT_EQ(0x1a, result_bytes[0]);
48   ASSERT_EQ(0xff, result_bytes[1]);
49 }
50 
TEST(InternetChecksumTest,ChecksumRequiringMultipleCarriesInLittleEndian)51 TEST(InternetChecksumTest, ChecksumRequiringMultipleCarriesInLittleEndian) {
52   uint8_t data[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00};
53 
54   // Data will accumulate to 0x0002FFFF
55   // Summing lower and upper halves gives 0x00010001
56   // Second sum of lower and upper halves gives 0x0002
57   // One's complement gives 0xfffd, or [0xfd, 0xff] in network byte order
58   InternetChecksum checksum;
59   checksum.Update(data, 8);
60   uint16_t result = checksum.Value();
61   auto* result_bytes = reinterpret_cast<uint8_t*>(&result);
62   EXPECT_EQ(0xfd, result_bytes[0]);
63   EXPECT_EQ(0xff, result_bytes[1]);
64 }
65 
66 }  // namespace
67 }  // namespace quic
68