ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
7a805c5c-8d3f-4d0e-b222-6133bf4825b1
cpp
google/tsl
cpu_info
tsl/platform/cpu_info.cc
tsl/platform/cpu_info_test.cc
#include "tsl/platform/cpu_info.h" #include "absl/base/call_once.h" #include "tsl/platform/logging.h" #include "tsl/platform/platform.h" #include "tsl/platform/types.h" #if defined(PLATFORM_IS_X86) #include <mutex> #endif #if defined(PLATFORM_IS_ARM64) && !defined(__APPLE__) && !defined(__OpenBSD__) #include <sys/auxv.h> #ifndef HWCAP_CPUID #define HWCAP_CPUID (1 << 11) #endif #include <fstream> #endif #ifdef PLATFORM_IS_X86 #ifdef PLATFORM_WINDOWS #define GETCPUID(a, b, c, d, a_inp, c_inp) \ { \ int cpu_info[4] = {-1}; \ __cpuidex(cpu_info, a_inp, c_inp); \ a = cpu_info[0]; \ b = cpu_info[1]; \ c = cpu_info[2]; \ d = cpu_info[3]; \ } #else #define GETCPUID(a, b, c, d, a_inp, c_inp) \ asm("mov %%rbx, %%rdi\n" \ "cpuid\n" \ "xchg %%rdi, %%rbx\n" \ : "=a"(a), "=D"(b), "=c"(c), "=d"(d) \ : "a"(a_inp), "2"(c_inp)) #endif #endif namespace tsl { namespace port { namespace { #ifdef PLATFORM_IS_X86 class CPUIDInfo; void InitCPUIDInfo(); CPUIDInfo *cpuid = nullptr; #ifdef PLATFORM_WINDOWS int GetXCR0EAX() { return _xgetbv(0); } #else int GetXCR0EAX() { int eax, edx; asm("XGETBV" : "=a"(eax), "=d"(edx) : "c"(0)); return eax; } #endif class CPUIDInfo { public: CPUIDInfo() : have_adx_(0), have_aes_(0), have_amx_bf16_(0), have_amx_fp16_(0), have_amx_int8_(0), have_amx_tile_(0), have_avx_(0), have_avx2_(0), have_avx512f_(0), have_avx512cd_(0), have_avx512er_(0), have_avx512pf_(0), have_avx512vl_(0), have_avx512bw_(0), have_avx512dq_(0), have_avx512vbmi_(0), have_avx512ifma_(0), have_avx512_4vnniw_(0), have_avx512_4fmaps_(0), have_avx512_bf16_(0), have_avx512_fp16_(0), have_avx512_vnni_(0), have_avx_vnni_(0), have_avx_vnni_int8_(0), have_avx_ne_convert_(0), have_bmi1_(0), have_bmi2_(0), have_cmov_(0), have_cmpxchg16b_(0), have_cmpxchg8b_(0), have_f16c_(0), have_fma_(0), have_mmx_(0), have_pclmulqdq_(0), have_popcnt_(0), have_prefetchw_(0), have_prefetchwt1_(0), have_rdrand_(0), have_rdseed_(0), have_smap_(0), have_sse_(0), have_sse2_(0), have_sse3_(0), have_sse4_1_(0), have_sse4_2_(0), have_ssse3_(0), have_hypervisor_(0) {} static void Initialize() { CHECK(cpuid == nullptr) << __func__ << " ran more than once"; cpuid = new CPUIDInfo; uint32 eax, ebx, ecx, edx; GETCPUID(eax, ebx, ecx, edx, 0, 0); cpuid->vendor_str_.append(reinterpret_cast<char *>(&ebx), 4); cpuid->vendor_str_.append(reinterpret_cast<char *>(&edx), 4); cpuid->vendor_str_.append(reinterpret_cast<char *>(&ecx), 4); GETCPUID(eax, ebx, ecx, edx, 1, 0); cpuid->model_num_ = static_cast<int>((eax >> 4) & 0xf); cpuid->family_ = static_cast<int>((eax >> 8) & 0xf); cpuid->have_aes_ = (ecx >> 25) & 0x1; cpuid->have_cmov_ = (edx >> 15) & 0x1; cpuid->have_cmpxchg16b_ = (ecx >> 13) & 0x1; cpuid->have_cmpxchg8b_ = (edx >> 8) & 0x1; cpuid->have_mmx_ = (edx >> 23) & 0x1; cpuid->have_pclmulqdq_ = (ecx >> 1) & 0x1; cpuid->have_popcnt_ = (ecx >> 23) & 0x1; cpuid->have_rdrand_ = (ecx >> 30) & 0x1; cpuid->have_sse2_ = (edx >> 26) & 0x1; cpuid->have_sse3_ = ecx & 0x1; cpuid->have_sse4_1_ = (ecx >> 19) & 0x1; cpuid->have_sse4_2_ = (ecx >> 20) & 0x1; cpuid->have_sse_ = (edx >> 25) & 0x1; cpuid->have_ssse3_ = (ecx >> 9) & 0x1; cpuid->have_hypervisor_ = (ecx >> 31) & 1; const uint64 xcr0_xmm_mask = 0x2; const uint64 xcr0_ymm_mask = 0x4; const uint64 xcr0_maskreg_mask = 0x20; const uint64 xcr0_zmm0_15_mask = 0x40; const uint64 xcr0_zmm16_31_mask = 0x80; const uint64 xcr0_avx_mask = xcr0_xmm_mask | xcr0_ymm_mask; const uint64 xcr0_avx512_mask = xcr0_avx_mask | xcr0_maskreg_mask | xcr0_zmm0_15_mask | xcr0_zmm16_31_mask; const bool have_avx = ((ecx >> 27) & 0x1) && ((GetXCR0EAX() & xcr0_avx_mask) == xcr0_avx_mask) && ((ecx >> 28) & 0x1); const bool have_avx512 = ((ecx >> 27) & 0x1) && ((GetXCR0EAX() & xcr0_avx512_mask) == xcr0_avx512_mask); cpuid->have_avx_ = have_avx; cpuid->have_fma_ = have_avx && ((ecx >> 12) & 0x1); cpuid->have_f16c_ = have_avx && ((ecx >> 29) & 0x1); GETCPUID(eax, ebx, ecx, edx, 7, 0); const uint32 kMaxNumSubLeaves = eax; cpuid->have_adx_ = (ebx >> 19) & 0x1; cpuid->have_avx2_ = have_avx && ((ebx >> 5) & 0x1); cpuid->have_bmi1_ = (ebx >> 3) & 0x1; cpuid->have_bmi2_ = (ebx >> 8) & 0x1; cpuid->have_prefetchwt1_ = ecx & 0x1; cpuid->have_rdseed_ = (ebx >> 18) & 0x1; cpuid->have_smap_ = (ebx >> 20) & 0x1; cpuid->have_avx512f_ = have_avx512 && ((ebx >> 16) & 0x1); cpuid->have_avx512cd_ = have_avx512 && ((ebx >> 28) & 0x1); cpuid->have_avx512er_ = have_avx512 && ((ebx >> 27) & 0x1); cpuid->have_avx512pf_ = have_avx512 && ((ebx >> 26) & 0x1); cpuid->have_avx512vl_ = have_avx512 && ((ebx >> 31) & 0x1); cpuid->have_avx512bw_ = have_avx512 && ((ebx >> 30) & 0x1); cpuid->have_avx512dq_ = have_avx512 && ((ebx >> 17) & 0x1); cpuid->have_avx512vbmi_ = have_avx512 && ((ecx >> 1) & 0x1); cpuid->have_avx512ifma_ = have_avx512 && ((ebx >> 21) & 0x1); cpuid->have_avx512_4vnniw_ = have_avx512 && ((edx >> 2) & 0x1); cpuid->have_avx512_4fmaps_ = have_avx512 && ((edx >> 3) & 0x1); cpuid->have_avx512_vnni_ = have_avx512 && ((ecx >> 11) & 0x1); cpuid->have_amx_tile_ = (edx >> 24) & 0x1; cpuid->have_amx_int8_ = (edx >> 25) & 0x1; cpuid->have_amx_bf16_ = (edx >> 22) & 0x1; cpuid->have_avx512_fp16_ = have_avx512 && ((edx >> 23) & 0x1); if (kMaxNumSubLeaves >= 1) { GETCPUID(eax, ebx, ecx, edx, 7, 1); cpuid->have_avx_vnni_ = (eax >> 4) & 0x1; cpuid->have_avx512_bf16_ = have_avx512 && ((eax >> 5) & 0x1); cpuid->have_amx_fp16_ = (eax >> 21) & 0x1; cpuid->have_avx_vnni_int8_ = (edx >> 4) & 0x1; cpuid->have_avx_ne_convert_ = (edx >> 5) & 0x1; } } static bool TestFeature(CPUFeature feature) { InitCPUIDInfo(); switch (feature) { case ADX: return cpuid->have_adx_; case AES: return cpuid->have_aes_; case AMX_BF16: return cpuid->have_amx_bf16_; case AMX_FP16: return cpuid->have_amx_fp16_; case AMX_INT8: return cpuid->have_amx_int8_; case AMX_TILE: return cpuid->have_amx_tile_; case AVX2: return cpuid->have_avx2_; case AVX: return cpuid->have_avx_; case AVX512F: return cpuid->have_avx512f_; case AVX512CD: return cpuid->have_avx512cd_; case AVX512PF: return cpuid->have_avx512pf_; case AVX512ER: return cpuid->have_avx512er_; case AVX512VL: return cpuid->have_avx512vl_; case AVX512BW: return cpuid->have_avx512bw_; case AVX512DQ: return cpuid->have_avx512dq_; case AVX512VBMI: return cpuid->have_avx512vbmi_; case AVX512IFMA: return cpuid->have_avx512ifma_; case AVX512_4VNNIW: return cpuid->have_avx512_4vnniw_; case AVX512_4FMAPS: return cpuid->have_avx512_4fmaps_; case AVX512_BF16: return cpuid->have_avx512_bf16_; case AVX512_FP16: return cpuid->have_avx512_fp16_; case AVX512_VNNI: return cpuid->have_avx512_vnni_; case AVX_VNNI: return cpuid->have_avx_vnni_; case AVX_VNNI_INT8: return cpuid->have_avx_vnni_int8_; case AVX_NE_CONVERT: return cpuid->have_avx_ne_convert_; case BMI1: return cpuid->have_bmi1_; case BMI2: return cpuid->have_bmi2_; case CMOV: return cpuid->have_cmov_; case CMPXCHG16B: return cpuid->have_cmpxchg16b_; case CMPXCHG8B: return cpuid->have_cmpxchg8b_; case F16C: return cpuid->have_f16c_; case FMA: return cpuid->have_fma_; case MMX: return cpuid->have_mmx_; case PCLMULQDQ: return cpuid->have_pclmulqdq_; case POPCNT: return cpuid->have_popcnt_; case PREFETCHW: return cpuid->have_prefetchw_; case PREFETCHWT1: return cpuid->have_prefetchwt1_; case RDRAND: return cpuid->have_rdrand_; case RDSEED: return cpuid->have_rdseed_; case SMAP: return cpuid->have_smap_; case SSE2: return cpuid->have_sse2_; case SSE3: return cpuid->have_sse3_; case SSE4_1: return cpuid->have_sse4_1_; case SSE4_2: return cpuid->have_sse4_2_; case SSE: return cpuid->have_sse_; case SSSE3: return cpuid->have_ssse3_; case HYPERVISOR: return cpuid->have_hypervisor_; default: break; } return false; } string vendor_str() const { return vendor_str_; } int family() const { return family_; } int model_num() { return model_num_; } private: int have_adx_ : 1; int have_aes_ : 1; int have_amx_bf16_ : 1; int have_amx_fp16_ : 1; int have_amx_int8_ : 1; int have_amx_tile_ : 1; int have_avx_ : 1; int have_avx2_ : 1; int have_avx512f_ : 1; int have_avx512cd_ : 1; int have_avx512er_ : 1; int have_avx512pf_ : 1; int have_avx512vl_ : 1; int have_avx512bw_ : 1; int have_avx512dq_ : 1; int have_avx512vbmi_ : 1; int have_avx512ifma_ : 1; int have_avx512_4vnniw_ : 1; int have_avx512_4fmaps_ : 1; int have_avx512_bf16_ : 1; int have_avx512_fp16_ : 1; int have_avx512_vnni_ : 1; int have_avx_vnni_ : 1; int have_avx_vnni_int8_ : 1; int have_avx_ne_convert_ : 1; int have_bmi1_ : 1; int have_bmi2_ : 1; int have_cmov_ : 1; int have_cmpxchg16b_ : 1; int have_cmpxchg8b_ : 1; int have_f16c_ : 1; int have_fma_ : 1; int have_mmx_ : 1; int have_pclmulqdq_ : 1; int have_popcnt_ : 1; int have_prefetchw_ : 1; int have_prefetchwt1_ : 1; int have_rdrand_ : 1; int have_rdseed_ : 1; int have_smap_ : 1; int have_sse_ : 1; int have_sse2_ : 1; int have_sse3_ : 1; int have_sse4_1_ : 1; int have_sse4_2_ : 1; int have_ssse3_ : 1; int have_hypervisor_ : 1; string vendor_str_; int family_; int model_num_; }; absl::once_flag cpuid_once_flag; void InitCPUIDInfo() { absl::call_once(cpuid_once_flag, CPUIDInfo::Initialize); } #endif #if defined(PLATFORM_IS_ARM64) && !defined(__APPLE__) && !defined(__OpenBSD__) class CPUIDInfo; void InitCPUIDInfo(); CPUIDInfo *cpuid = nullptr; class CPUIDInfo { public: CPUIDInfo() : implementer_(0), variant_(0), cpunum_(0), is_arm_neoverse_v1_(0), is_arm_neoverse_n1_(0) {} static void Initialize() { if (cpuid != nullptr) return; cpuid = new CPUIDInfo; if (!(getauxval(AT_HWCAP) & HWCAP_CPUID)) { return; } int present_cpu = -1; #ifndef PLATFORM_WINDOWS std::ifstream CPUspresent; CPUspresent.open("/sys/devices/system/cpu/present", std::ios::in); if (CPUspresent.is_open()) { std::string line; if (static_cast<bool>(getline(CPUspresent, line))) { auto ending = line.end(); for (auto i = line.begin(); i < line.end(); ++i) { if (*i == '-' || *i == ',') { ending = i; break; } } line.erase(ending, line.end()); present_cpu = std::stoi(line); } } #endif if (present_cpu == -1) { return; } #ifndef PLATFORM_WINDOWS std::stringstream str; str << "/sys/devices/system/cpu/cpu" << present_cpu << "/regs/identification/midr_el1"; std::ifstream midr_el1_file(str.str(), std::ios::in); if (midr_el1_file.is_open()) { std::string line; if (static_cast<bool>(getline(midr_el1_file, line))) { uint32 midr_el1 = std::stoul(line, nullptr, 16); cpuid->implementer_ = (midr_el1 >> 24) & 0xFF; cpuid->variant_ = (midr_el1 >> 20) & 0xF; cpuid->cpunum_ = (midr_el1 >> 4) & 0xFFF; if (cpuid->implementer_ == 0x41) { switch (cpuid->cpunum_) { case 0xd40: cpuid->is_arm_neoverse_v1_ = 1; break; case 0xd0c: cpuid->is_arm_neoverse_n1_ = 1; break; default: break; } } } } #endif } int implementer() const { return implementer_; } int cpunum() const { return cpunum_; } static bool TestAarch64CPU(Aarch64CPU cpu) { InitCPUIDInfo(); switch (cpu) { case ARM_NEOVERSE_V1: return cpuid->is_arm_neoverse_v1_; default: return 0; } } private: int implementer_; int variant_; int cpunum_; int is_arm_neoverse_v1_; int is_arm_neoverse_n1_; }; absl::once_flag cpuid_once_flag; void InitCPUIDInfo() { absl::call_once(cpuid_once_flag, CPUIDInfo::Initialize); } #endif } bool TestCPUFeature(CPUFeature feature) { #ifdef PLATFORM_IS_X86 return CPUIDInfo::TestFeature(feature); #else return false; #endif } bool TestAarch64CPU(Aarch64CPU cpu) { #if defined(PLATFORM_IS_ARM64) && !defined(__APPLE__) && !defined(__OpenBSD__) return CPUIDInfo::TestAarch64CPU(cpu); #else return false; #endif } std::string CPUVendorIDString() { #ifdef PLATFORM_IS_X86 InitCPUIDInfo(); return cpuid->vendor_str(); #else return ""; #endif } int CPUFamily() { #ifdef PLATFORM_IS_X86 InitCPUIDInfo(); return cpuid->family(); #elif defined(PLATFORM_IS_ARM64) && !defined(__APPLE__) && !defined(__OpenBSD__) InitCPUIDInfo(); return cpuid->implementer(); #else return 0; #endif } int CPUModelNum() { #ifdef PLATFORM_IS_X86 InitCPUIDInfo(); return cpuid->model_num(); #elif defined(PLATFORM_IS_ARM64) && !defined(__APPLE__) && !defined(__OpenBSD__) InitCPUIDInfo(); return cpuid->cpunum(); #else return 0; #endif } int CPUIDNumSMT() { #ifdef PLATFORM_IS_X86 uint32 eax, ebx, ecx, edx; GETCPUID(eax, ebx, ecx, edx, 0, 0); if (eax >= 11) { GETCPUID(eax, ebx, ecx, edx, 11, 0); if (ebx != 0 && ((ecx & 0xff00) >> 8) == 1) { return 1 << (eax & 0x1f); } } #endif return 0; } } }
#include "tsl/platform/cpu_info.h" #include "tsl/platform/test.h" namespace tsl { TEST(CPUInfo, CommonX86CPU) { if (port::TestCPUFeature(port::CPUFeature::SSE)) { EXPECT_TRUE(port::IsX86CPU()); } } TEST(CPUInfo, Aarch64NeoverseV1CPU) { if (port::TestAarch64CPU(port::Aarch64CPU::ARM_NEOVERSE_V1)) { EXPECT_TRUE(port::IsAarch64CPU()); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cpu_info.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cpu_info_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
865578b9-155a-44ae-b3c1-91ffd8aa63d5
cpp
google/tsl
hash
tsl/platform/hash.cc
tsl/platform/hash_test.cc
#include "tsl/platform/hash.h" #include <string.h> #include "tsl/platform/macros.h" #include "tsl/platform/raw_coding.h" #include "tsl/platform/types.h" namespace tsl { static inline uint32 ByteAs32(char c) { return static_cast<uint32>(c) & 0xff; } static inline uint64 ByteAs64(char c) { return static_cast<uint64>(c) & 0xff; } uint32 Hash32(const char* data, size_t n, uint32 seed) { const uint32 m = 0x5bd1e995; const int r = 24; uint32 h = seed ^ n; while (n >= 4) { uint32 k = core::DecodeFixed32(data); k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; n -= 4; } switch (n) { case 3: h ^= ByteAs32(data[2]) << 16; TF_FALLTHROUGH_INTENDED; case 2: h ^= ByteAs32(data[1]) << 8; TF_FALLTHROUGH_INTENDED; case 1: h ^= ByteAs32(data[0]); h *= m; } h ^= h >> 13; h *= m; h ^= h >> 15; return h; } uint64 Hash64(const char* data, size_t n, uint64 seed) { const uint64 m = 0xc6a4a7935bd1e995; const int r = 47; uint64 h = seed ^ (n * m); while (n >= 8) { uint64 k = core::DecodeFixed64(data); data += 8; n -= 8; k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; } switch (n) { case 7: h ^= ByteAs64(data[6]) << 48; TF_FALLTHROUGH_INTENDED; case 6: h ^= ByteAs64(data[5]) << 40; TF_FALLTHROUGH_INTENDED; case 5: h ^= ByteAs64(data[4]) << 32; TF_FALLTHROUGH_INTENDED; case 4: h ^= ByteAs64(data[3]) << 24; TF_FALLTHROUGH_INTENDED; case 3: h ^= ByteAs64(data[2]) << 16; TF_FALLTHROUGH_INTENDED; case 2: h ^= ByteAs64(data[1]) << 8; TF_FALLTHROUGH_INTENDED; case 1: h ^= ByteAs64(data[0]); h *= m; } h ^= h >> r; h *= m; h ^= h >> r; return h; } }
#include <map> #include <unordered_map> #include <vector> #include "tsl/platform/hash.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { TEST(Hash, SignedUnsignedIssue) { const unsigned char d1[1] = {0x62}; const unsigned char d2[2] = {0xc3, 0x97}; const unsigned char d3[3] = {0xe2, 0x99, 0xa5}; const unsigned char d4[4] = {0xe1, 0x80, 0xb9, 0x32}; const unsigned char d5[48] = { 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; struct Case { uint32 hash32; uint64 hash64; const unsigned char* data; size_t size; uint32 seed; }; for (Case c : std::vector<Case>{ {0x471a8188u, 0x4c61ea3eeda4cb87ull, nullptr, 0, 0xbc9f1d34}, {0xd615eba5u, 0x091309f7ef916c8aull, d1, sizeof(d1), 0xbc9f1d34}, {0x0c3cccdau, 0xa815bcdf1d1af01cull, d2, sizeof(d2), 0xbc9f1d34}, {0x3ba37e0eu, 0x02167564e4d06430ull, d3, sizeof(d3), 0xbc9f1d34}, {0x16174eb3u, 0x8f7ed82ffc21071full, d4, sizeof(d4), 0xbc9f1d34}, {0x98b1926cu, 0xce196580c97aff1eull, d5, sizeof(d5), 0x12345678}, }) { EXPECT_EQ(c.hash32, Hash32(reinterpret_cast<const char*>(c.data), c.size, c.seed)); EXPECT_EQ(c.hash64, Hash64(reinterpret_cast<const char*>(c.data), c.size, c.seed)); for (int align = 1; align <= 7; align++) { std::string input(align, 'x'); input.append(reinterpret_cast<const char*>(c.data), c.size); EXPECT_EQ(c.hash32, Hash32(&input[align], c.size, c.seed)); EXPECT_EQ(c.hash64, Hash64(&input[align], c.size, c.seed)); } } } TEST(Hash, HashPtrIsNotIdentityFunction) { int* ptr = reinterpret_cast<int*>(0xcafe0000); EXPECT_NE(hash<int*>()(ptr), size_t{0xcafe0000}); } static void BM_Hash32(::testing::benchmark::State& state) { int len = state.range(0); std::string input(len, 'x'); uint32 h = 0; for (auto s : state) { h = Hash32(input.data(), len, 1); } state.SetBytesProcessed(state.iterations() * len); VLOG(1) << h; } BENCHMARK(BM_Hash32)->Range(1, 1024); TEST(StringPieceHasher, Equality) { StringPieceHasher hasher; absl::string_view s1("foo"); absl::string_view s2("bar"); absl::string_view s3("baz"); absl::string_view s4("zot"); EXPECT_TRUE(hasher(s1) != hasher(s2)); EXPECT_TRUE(hasher(s1) != hasher(s3)); EXPECT_TRUE(hasher(s1) != hasher(s4)); EXPECT_TRUE(hasher(s2) != hasher(s3)); EXPECT_TRUE(hasher(s2) != hasher(s4)); EXPECT_TRUE(hasher(s3) != hasher(s4)); EXPECT_TRUE(hasher(s1) == hasher(s1)); EXPECT_TRUE(hasher(s2) == hasher(s2)); EXPECT_TRUE(hasher(s3) == hasher(s3)); EXPECT_TRUE(hasher(s4) == hasher(s4)); } TEST(StringPieceHasher, HashMap) { string s1("foo"); string s2("bar"); string s3("baz"); absl::string_view p1(s1); absl::string_view p2(s2); absl::string_view p3(s3); std::unordered_map<absl::string_view, int, StringPieceHasher> map; map.insert(std::make_pair(p1, 0)); map.insert(std::make_pair(p2, 1)); map.insert(std::make_pair(p3, 2)); EXPECT_EQ(map.size(), 3); bool found[3] = {false, false, false}; for (auto const& val : map) { int x = val.second; EXPECT_TRUE(x >= 0 && x < 3); EXPECT_TRUE(!found[x]); found[x] = true; } EXPECT_EQ(found[0], true); EXPECT_EQ(found[1], true); EXPECT_EQ(found[2], true); auto new_iter = map.find("zot"); EXPECT_TRUE(new_iter == map.end()); new_iter = map.find("bar"); EXPECT_TRUE(new_iter != map.end()); map.erase(new_iter); EXPECT_EQ(map.size(), 2); found[0] = false; found[1] = false; found[2] = false; for (const auto& iter : map) { int x = iter.second; EXPECT_TRUE(x >= 0 && x < 3); EXPECT_TRUE(!found[x]); found[x] = true; } EXPECT_EQ(found[0], true); EXPECT_EQ(found[1], false); EXPECT_EQ(found[2], true); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/hash.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/hash_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
1233e3ce-02dc-4555-87e3-68dfbb1d1ff6
cpp
google/tsl
status_matchers
tsl/platform/status_matchers.cc
tsl/platform/status_matchers_test.cc
#include "tsl/platform/status_matchers.h" #include <ostream> #include <string> #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/protobuf/error_codes.pb.h" namespace tsl { namespace testing { namespace internal_status { void StatusIsMatcherCommonImpl::DescribeTo(std::ostream* os) const { *os << "has a status code that "; code_matcher_.DescribeTo(os); *os << ", and has an error message that "; message_matcher_.DescribeTo(os); } void StatusIsMatcherCommonImpl::DescribeNegationTo(std::ostream* os) const { *os << "has a status code that "; code_matcher_.DescribeNegationTo(os); *os << ", or has an error message that "; message_matcher_.DescribeNegationTo(os); } bool StatusIsMatcherCommonImpl::MatchAndExplain( const absl::Status& status, ::testing::MatchResultListener* result_listener) const { ::testing::StringMatchResultListener inner_listener; inner_listener.Clear(); if (!code_matcher_.MatchAndExplain( static_cast<absl::StatusCode>(status.code()), &inner_listener)) { *result_listener << (inner_listener.str().empty() ? "whose status code is wrong" : "which has a status code " + inner_listener.str()); return false; } if (!message_matcher_.Matches(std::string(status.message()))) { *result_listener << "whose error message is wrong"; return false; } return true; } } } }
#include "tsl/platform/status_matchers.h" #include <sstream> #include <string> #include <vector> #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" #include "tsl/protobuf/error_codes.pb.h" namespace tsl { namespace testing { namespace { using ::testing::_; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Matcher; using ::testing::MatchesRegex; using ::testing::Ne; using ::testing::Not; using ::testing::PrintToString; MATCHER_P(LessThan, upper, "") { if (arg < upper) { *result_listener << "which is " << (upper - arg) << " less than " << upper; return true; } *result_listener << "which is " << (arg - upper) << " more than " << upper; return false; } template <typename T> std::string Describe(const Matcher<T>& matcher) { std::stringstream ss; matcher.DescribeTo(&ss); return ss.str(); } template <typename T> std::string DescribeNegation(const Matcher<T>& matcher) { std::stringstream ss; matcher.DescribeNegationTo(&ss); return ss.str(); } template <typename T, typename V> std::string ExplainMatch(const Matcher<T>& matcher, const V& value) { ::testing::StringMatchResultListener listener; matcher.MatchAndExplain(value, &listener); return listener.str(); } TEST(IsOkAndHoldsTest, MatchesValue) { absl::StatusOr<std::string> status_or_message("Hello, world"); EXPECT_THAT(status_or_message, IsOkAndHolds("Hello, world")); EXPECT_THAT(status_or_message, IsOkAndHolds(HasSubstr("Hello,"))); } TEST(IsOkAndHoldsTest, MatchesContainer) { absl::StatusOr<std::vector<std::string>> status_or_messages = std::vector<std::string>{"Hello, world", "Hello, tf"}; EXPECT_THAT(status_or_messages, IsOkAndHolds(ElementsAre("Hello, world", "Hello, tf"))); EXPECT_THAT(status_or_messages, IsOkAndHolds(ElementsAre(HasSubstr("world"), HasSubstr("tf")))); } TEST(IsOkAndHoldsTest, DoesNotMatchStatus) { absl::StatusOr<std::string> status_or_message = errors::InvalidArgument("Invalid argument"); EXPECT_THAT(status_or_message, Not(IsOkAndHolds("Hello, world"))); } TEST(IsOkAndHoldsTest, DoesNotMatchValue) { absl::StatusOr<std::string> status_or_message("Hello, tf"); EXPECT_THAT(status_or_message, Not(IsOkAndHolds("Hello, world"))); } TEST(IsOkAndHoldsTest, DoesNotMatchContainer) { absl::StatusOr<std::vector<int>> status_or_container({1, 2, 3}); EXPECT_THAT(status_or_container, Not(IsOkAndHolds(ElementsAre(4, 5, 6)))); } TEST(IsOkAndHoldsTest, DescribeExpectedValue) { Matcher<absl::StatusOr<std::string>> is_ok_and_has_substr = IsOkAndHolds(HasSubstr("Hello")); EXPECT_EQ(Describe(is_ok_and_has_substr), "is OK and has a value that has substring \"Hello\""); EXPECT_EQ(DescribeNegation(is_ok_and_has_substr), "isn't OK or has a value that has no substring \"Hello\""); } TEST(IsOkAndHoldsTest, ExplainNotMatchingStatus) { Matcher<absl::StatusOr<int>> is_ok_and_less_than = IsOkAndHolds(LessThan(100)); absl::StatusOr<int> status = errors::Unknown("Unknown"); EXPECT_THAT(ExplainMatch(is_ok_and_less_than, status), HasSubstr("which has status UNKNOWN: Unknown")); } TEST(IsOkAndHoldsTest, ExplainNotMatchingValue) { Matcher<absl::StatusOr<int>> is_ok_and_less_than = IsOkAndHolds(LessThan(100)); EXPECT_EQ(ExplainMatch(is_ok_and_less_than, 120), "which contains value 120, which is 20 more than 100"); } TEST(IsOkAndHoldsTest, ExplainNotMatchingContainer) { Matcher<absl::StatusOr<std::vector<int>>> is_ok_and_less_than = IsOkAndHolds(ElementsAre(1, 2, 3)); std::vector<int> actual{4, 5, 6}; EXPECT_THAT(ExplainMatch(is_ok_and_less_than, actual), HasSubstr("which contains value " + PrintToString(actual))); } TEST(StatusIsTest, MatchesOK) { EXPECT_THAT(absl::OkStatus(), StatusIs(error::OK)); absl::StatusOr<std::string> message("Hello, world"); EXPECT_THAT(message, StatusIs(error::OK)); } TEST(StatusIsTest, DoesNotMatchOk) { EXPECT_THAT(errors::DeadlineExceeded("Deadline exceeded"), Not(StatusIs(error::OK))); absl::StatusOr<std::string> status = errors::NotFound("Not found"); EXPECT_THAT(status, Not(StatusIs(error::OK))); } TEST(StatusIsTest, MatchesStatus) { absl::Status s = errors::Cancelled("Cancelled"); EXPECT_THAT(s, StatusIs(error::CANCELLED)); EXPECT_THAT(s, StatusIs(error::CANCELLED, "Cancelled")); EXPECT_THAT(s, StatusIs(_, "Cancelled")); EXPECT_THAT(s, StatusIs(error::CANCELLED, _)); EXPECT_THAT(s, StatusIs(Ne(error::INVALID_ARGUMENT), _)); EXPECT_THAT(s, StatusIs(error::CANCELLED, HasSubstr("Can"))); EXPECT_THAT(s, StatusIs(error::CANCELLED, MatchesRegex("Can.*"))); } TEST(StatusIsTest, StatusOrMatchesStatus) { absl::StatusOr<int> s = errors::InvalidArgument("Invalid Argument"); EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT)); EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, "Invalid Argument")); EXPECT_THAT(s, StatusIs(_, "Invalid Argument")); EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, _)); EXPECT_THAT(s, StatusIs(Ne(error::CANCELLED), _)); EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, HasSubstr("Argument"))); EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, MatchesRegex(".*Argument"))); } TEST(StatusIsTest, DoesNotMatchStatus) { absl::Status s = errors::Internal("Internal"); EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION))); EXPECT_THAT(s, Not(StatusIs(error::INTERNAL, "Failed Precondition"))); EXPECT_THAT(s, Not(StatusIs(_, "Failed Precondition"))); EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION, _))); } TEST(StatusIsTest, StatusOrDoesNotMatchStatus) { absl::StatusOr<int> s = errors::FailedPrecondition("Failed Precondition"); EXPECT_THAT(s, Not(StatusIs(error::INTERNAL))); EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION, "Internal"))); EXPECT_THAT(s, Not(StatusIs(_, "Internal"))); EXPECT_THAT(s, Not(StatusIs(error::INTERNAL, _))); } TEST(StatusIsTest, DescribeExpectedValue) { Matcher<absl::Status> status_is = StatusIs(error::UNAVAILABLE, std::string("Unavailable")); EXPECT_EQ(Describe(status_is), "has a status code that is equal to UNAVAILABLE, " "and has an error message that is equal to \"Unavailable\""); } TEST(StatusIsTest, DescribeNegatedExpectedValue) { Matcher<absl::StatusOr<std::string>> status_is = StatusIs(error::ABORTED, std::string("Aborted")); EXPECT_EQ(DescribeNegation(status_is), "has a status code that isn't equal to ABORTED, " "or has an error message that isn't equal to \"Aborted\""); } TEST(StatusIsTest, ExplainNotMatchingErrorCode) { Matcher<absl::Status> status_is = StatusIs(error::NOT_FOUND, _); const absl::Status status = errors::AlreadyExists("Already exists"); EXPECT_EQ(ExplainMatch(status_is, status), "whose status code is wrong"); } TEST(StatusIsTest, ExplainNotMatchingErrorMessage) { Matcher<absl::Status> status_is = StatusIs(error::NOT_FOUND, "Not found"); const absl::Status status = errors::NotFound("Already exists"); EXPECT_EQ(ExplainMatch(status_is, status), "whose error message is wrong"); } TEST(StatusIsTest, ExplainStatusOrNotMatchingErrorCode) { Matcher<absl::StatusOr<int>> status_is = StatusIs(error::ALREADY_EXISTS, _); const absl::StatusOr<int> status_or = errors::NotFound("Not found"); EXPECT_EQ(ExplainMatch(status_is, status_or), "whose status code is wrong"); } TEST(StatusIsTest, ExplainStatusOrNotMatchingErrorMessage) { Matcher<absl::StatusOr<int>> status_is = StatusIs(error::ALREADY_EXISTS, "Already exists"); const absl::StatusOr<int> status_or = errors::AlreadyExists("Not found"); EXPECT_EQ(ExplainMatch(status_is, status_or), "whose error message is wrong"); } TEST(StatusIsTest, ExplainStatusOrHasValue) { Matcher<absl::StatusOr<int>> status_is = StatusIs(error::RESOURCE_EXHAUSTED, "Resource exhausted"); const absl::StatusOr<int> value = -1; EXPECT_EQ(ExplainMatch(status_is, value), "whose status code is wrong"); } TEST(IsOkTest, MatchesOK) { EXPECT_THAT(absl::OkStatus(), IsOk()); absl::StatusOr<std::string> message = std::string("Hello, world"); EXPECT_THAT(message, IsOk()); } TEST(IsOkTest, DoesNotMatchOK) { EXPECT_THAT(errors::PermissionDenied("Permission denied"), Not(IsOk())); absl::StatusOr<std::string> status = errors::Unauthenticated("Unauthenticated"); EXPECT_THAT(status, Not(IsOk())); } TEST(IsOkTest, DescribeExpectedValue) { Matcher<absl::Status> status_is_ok = IsOk(); EXPECT_EQ(Describe(status_is_ok), "is OK"); Matcher<absl::StatusOr<std::string>> status_or_is_ok = IsOk(); EXPECT_EQ(Describe(status_or_is_ok), "is OK"); } TEST(IsOkTest, DescribeNegatedExpectedValue) { Matcher<absl::Status> status_is_ok = IsOk(); EXPECT_EQ(DescribeNegation(status_is_ok), "is not OK"); Matcher<absl::StatusOr<std::string>> status_or_is_ok = IsOk(); EXPECT_EQ(DescribeNegation(status_or_is_ok), "is not OK"); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/status_matchers.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/status_matchers_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
aefc07d7-fcd2-4f1e-9cd4-616943a4cc7b
cpp
google/tsl
setround
tsl/platform/setround.cc
tsl/platform/setround_test.cc
#include "tsl/platform/setround.h" #include "tsl/platform/logging.h" namespace tsl { namespace port { #if defined(TF_BROKEN_CFENV) ScopedSetRound::ScopedSetRound(const int mode) : original_mode_(mode) { DCHECK_EQ(mode, FE_TONEAREST); } ScopedSetRound::~ScopedSetRound() {} #else ScopedSetRound::ScopedSetRound(const int mode) { original_mode_ = std::fegetround(); if (original_mode_ < 0) { original_mode_ = FE_TONEAREST; } std::fesetround(mode); } ScopedSetRound::~ScopedSetRound() { std::fesetround(original_mode_); } #endif } }
#include "tsl/platform/setround.h" #include <cmath> #include "tsl/platform/test.h" #if !defined(__clang__) || !defined(__OPTIMIZE__) namespace tsl { namespace { void CheckDownward() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(12, std::nearbyint(12.1)); EXPECT_EQ(-13, std::nearbyint(-12.1)); EXPECT_EQ(12, std::nearbyint(12.5)); EXPECT_EQ(12, std::nearbyint(12.9)); EXPECT_EQ(-13, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } void CheckToNearest() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(12, std::nearbyint(12.1)); EXPECT_EQ(-12, std::nearbyint(-12.1)); EXPECT_EQ(12, std::nearbyint(12.5)); EXPECT_EQ(13, std::nearbyint(12.9)); EXPECT_EQ(-13, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } void CheckTowardZero() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(12, std::nearbyint(12.1)); EXPECT_EQ(-12, std::nearbyint(-12.1)); EXPECT_EQ(12, std::nearbyint(12.5)); EXPECT_EQ(12, std::nearbyint(12.9)); EXPECT_EQ(-12, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } void CheckUpward() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(13, std::nearbyint(12.1)); EXPECT_EQ(-12, std::nearbyint(-12.1)); EXPECT_EQ(13, std::nearbyint(12.5)); EXPECT_EQ(13, std::nearbyint(12.9)); EXPECT_EQ(-12, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } TEST(SetScopedSetRound, Downward) { port::ScopedSetRound round(FE_DOWNWARD); CheckDownward(); } TEST(SetScopedSetRound, ToNearest) { port::ScopedSetRound round(FE_TONEAREST); CheckToNearest(); } TEST(SetScopedSetRound, TowardZero) { port::ScopedSetRound round(FE_TOWARDZERO); CheckTowardZero(); } TEST(SetScopedSetRound, Upward) { port::ScopedSetRound round(FE_UPWARD); CheckUpward(); } TEST(SetScopedSetRound, Scoped) { std::fesetround(FE_TONEAREST); CheckToNearest(); { port::ScopedSetRound round(FE_UPWARD); CheckUpward(); } CheckToNearest(); } } } #endif
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/setround.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/setround_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
84744b48-6c8e-41e3-bc3f-835b68c094da
cpp
google/tsl
abi
tsl/platform/abi.cc
tsl/platform/abi_test.cc
#include "tsl/platform/abi.h" #include "tsl/platform/types.h" #if defined(_MSC_VER) #include <windows.h> #include <cstring> #else #include <cxxabi.h> #include <cstdlib> #endif #include <memory> #include <string> #if defined(_MSC_VER) extern "C" char* __unDName(char* output_string, const char* name, int max_string_length, void* (*p_alloc)(std::size_t), void (*p_free)(void*), unsigned short disable_flags); #endif namespace tsl { namespace port { string MaybeAbiDemangle(const char* name) { #if defined(_MSC_VER) std::unique_ptr<char> demangled{__unDName(nullptr, name, 0, std::malloc, std::free, static_cast<unsigned short>(0))}; return string(demangled.get() != nullptr ? demangled.get() : name); #else int status = 0; std::unique_ptr<char, void (*)(void*)> res{ abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free}; return (status == 0) ? res.get() : name; #endif } } }
#include "tsl/platform/abi.h" #include <typeinfo> #include "tsl/platform/test.h" namespace tsl { struct MyRandomPODType {}; TEST(AbiTest, AbiDemangleTest) { EXPECT_EQ(port::MaybeAbiDemangle(typeid(int).name()), "int"); #ifdef PLATFORM_WINDOWS const char pod_type_name[] = "struct tsl::MyRandomPODType"; #else const char pod_type_name[] = "tsl::MyRandomPODType"; #endif EXPECT_EQ(port::MaybeAbiDemangle(typeid(MyRandomPODType).name()), pod_type_name); EXPECT_EQ( port::MaybeAbiDemangle("help! i'm caught in a C++ mangle factoryasdf"), "help! i'm caught in a C++ mangle factoryasdf"); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/abi.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/abi_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
f5ee04c2-fce6-4a1e-9a0e-8ccf8a7ee393
cpp
google/tsl
numbers
tsl/platform/numbers.cc
tsl/platform/numbers_test.cc
#include "tsl/platform/numbers.h" #include <ctype.h> #include <float.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <cinttypes> #include <cmath> #include <cstdint> #include <locale> #include <unordered_map> #include "double-conversion/double-conversion.h" #include "tsl/platform/str_util.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/stringprintf.h" #include "tsl/platform/types.h" namespace tsl { namespace { template <typename T> const std::unordered_map<std::string, T>* GetSpecialNumsSingleton() { static const std::unordered_map<std::string, T>* special_nums = CHECK_NOTNULL((new const std::unordered_map<std::string, T>{ {"inf", std::numeric_limits<T>::infinity()}, {"+inf", std::numeric_limits<T>::infinity()}, {"-inf", -std::numeric_limits<T>::infinity()}, {"infinity", std::numeric_limits<T>::infinity()}, {"+infinity", std::numeric_limits<T>::infinity()}, {"-infinity", -std::numeric_limits<T>::infinity()}, {"nan", std::numeric_limits<T>::quiet_NaN()}, {"+nan", std::numeric_limits<T>::quiet_NaN()}, {"-nan", -std::numeric_limits<T>::quiet_NaN()}, })); return special_nums; } template <typename T> T locale_independent_strtonum(const char* str, const char** endptr) { auto special_nums = GetSpecialNumsSingleton<T>(); std::stringstream s(str); std::string special_num_str; s >> special_num_str; for (size_t i = 0; i < special_num_str.length(); ++i) { special_num_str[i] = std::tolower(special_num_str[i], std::locale::classic()); } auto entry = special_nums->find(special_num_str); if (entry != special_nums->end()) { *endptr = str + (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str)) : s.tellg()); return entry->second; } else { if (special_num_str.compare(0, 2, "0x") == 0 || special_num_str.compare(0, 3, "-0x") == 0) { return strtol(str, const_cast<char**>(endptr), 16); } } s.str(str); s.clear(); s.imbue(std::locale::classic()); T result; s >> result; if (s.fail()) { if (result == std::numeric_limits<T>::max() || result == std::numeric_limits<T>::infinity()) { result = std::numeric_limits<T>::infinity(); s.clear(s.rdstate() & ~std::ios::failbit); } else if (result == -std::numeric_limits<T>::max() || result == -std::numeric_limits<T>::infinity()) { result = -std::numeric_limits<T>::infinity(); s.clear(s.rdstate() & ~std::ios::failbit); } } if (endptr) { *endptr = str + (s.fail() ? static_cast<std::iostream::pos_type>(0) : (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str)) : s.tellg())); } return result; } static inline const double_conversion::StringToDoubleConverter& StringToFloatConverter() { static const double_conversion::StringToDoubleConverter converter( double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES | double_conversion::StringToDoubleConverter::ALLOW_HEX | double_conversion::StringToDoubleConverter::ALLOW_TRAILING_SPACES | double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSIBILITY, 0., 0., "inf", "nan"); return converter; } } namespace strings { size_t FastInt32ToBufferLeft(int32_t i, char* buffer) { uint32_t u = i; size_t length = 0; if (i < 0) { *buffer++ = '-'; ++length; u = 0 - u; } length += FastUInt32ToBufferLeft(u, buffer); return length; } size_t FastUInt32ToBufferLeft(uint32_t i, char* buffer) { char* start = buffer; do { *buffer++ = ((i % 10) + '0'); i /= 10; } while (i > 0); *buffer = 0; std::reverse(start, buffer); return buffer - start; } size_t FastInt64ToBufferLeft(int64_t i, char* buffer) { uint64_t u = i; size_t length = 0; if (i < 0) { *buffer++ = '-'; ++length; u = 0 - u; } length += FastUInt64ToBufferLeft(u, buffer); return length; } size_t FastUInt64ToBufferLeft(uint64_t i, char* buffer) { char* start = buffer; do { *buffer++ = ((i % 10) + '0'); i /= 10; } while (i > 0); *buffer = 0; std::reverse(start, buffer); return buffer - start; } static const double kDoublePrecisionCheckMax = DBL_MAX / 1.000000000000001; size_t DoubleToBuffer(double value, char* buffer) { static_assert(DBL_DIG < 20, "DBL_DIG is too big"); if (std::isnan(value)) { int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan", std::signbit(value) ? "-" : ""); DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); return snprintf_result; } if (std::abs(value) <= kDoublePrecisionCheckMax) { int snprintf_result = snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG, value); DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); if (locale_independent_strtonum<double>(buffer, nullptr) == value) { return snprintf_result; } } int snprintf_result = snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG + 2, value); DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); return snprintf_result; } namespace { char SafeFirstChar(absl::string_view str) { if (str.empty()) return '\0'; return str[0]; } void SkipSpaces(absl::string_view* str) { while (isspace(SafeFirstChar(*str))) str->remove_prefix(1); } } bool safe_strto64(absl::string_view str, int64_t* value) { SkipSpaces(&str); int64_t vlimit = kint64max; int sign = 1; if (absl::ConsumePrefix(&str, "-")) { sign = -1; vlimit = kint64min; } if (!isdigit(SafeFirstChar(str))) return false; int64_t result = 0; if (sign == 1) { do { int digit = SafeFirstChar(str) - '0'; if ((vlimit - digit) / 10 < result) { return false; } result = result * 10 + digit; str.remove_prefix(1); } while (isdigit(SafeFirstChar(str))); } else { do { int digit = SafeFirstChar(str) - '0'; if ((vlimit + digit) / 10 > result) { return false; } result = result * 10 - digit; str.remove_prefix(1); } while (isdigit(SafeFirstChar(str))); } SkipSpaces(&str); if (!str.empty()) return false; *value = result; return true; } bool safe_strtou64(absl::string_view str, uint64_t* value) { SkipSpaces(&str); if (!isdigit(SafeFirstChar(str))) return false; uint64_t result = 0; do { int digit = SafeFirstChar(str) - '0'; if ((kuint64max - digit) / 10 < result) { return false; } result = result * 10 + digit; str.remove_prefix(1); } while (isdigit(SafeFirstChar(str))); SkipSpaces(&str); if (!str.empty()) return false; *value = result; return true; } bool safe_strto32(absl::string_view str, int32_t* value) { SkipSpaces(&str); int64_t vmax = kint32max; int sign = 1; if (absl::ConsumePrefix(&str, "-")) { sign = -1; ++vmax; } if (!isdigit(SafeFirstChar(str))) return false; int64_t result = 0; do { result = result * 10 + SafeFirstChar(str) - '0'; if (result > vmax) { return false; } str.remove_prefix(1); } while (isdigit(SafeFirstChar(str))); SkipSpaces(&str); if (!str.empty()) return false; *value = static_cast<int32_t>(result * sign); return true; } bool safe_strtou32(absl::string_view str, uint32_t* value) { SkipSpaces(&str); if (!isdigit(SafeFirstChar(str))) return false; int64_t result = 0; do { result = result * 10 + SafeFirstChar(str) - '0'; if (result > kuint32max) { return false; } str.remove_prefix(1); } while (isdigit(SafeFirstChar(str))); SkipSpaces(&str); if (!str.empty()) return false; *value = static_cast<uint32_t>(result); return true; } bool safe_strtof(absl::string_view str, float* value) { int processed_characters_count = -1; auto len = str.size(); if (len >= kFastToBufferSize) return false; if (len > std::numeric_limits<int>::max()) return false; *value = StringToFloatConverter().StringToFloat( str.data(), static_cast<int>(len), &processed_characters_count); return processed_characters_count > 0; } bool safe_strtod(absl::string_view str, double* value) { int processed_characters_count = -1; auto len = str.size(); if (len >= kFastToBufferSize) return false; if (len > std::numeric_limits<int>::max()) return false; *value = StringToFloatConverter().StringToDouble( str.data(), static_cast<int>(len), &processed_characters_count); return processed_characters_count > 0; } size_t FloatToBuffer(float value, char* buffer) { static_assert(FLT_DIG < 10, "FLT_DIG is too big"); if (std::isnan(value)) { int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan", std::signbit(value) ? "-" : ""); DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); return snprintf_result; } int snprintf_result = snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG, value); DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); float parsed_value; if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) { snprintf_result = snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG + 3, value); DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); } return snprintf_result; } std::string FpToString(Fprint fp) { char buf[17]; snprintf(buf, sizeof(buf), "%016llx", static_cast<long long>(fp)); return std::string(buf); } bool StringToFp(const std::string& s, Fprint* fp) { char junk; uint64_t result; if (sscanf(s.c_str(), "%" SCNx64 "%c", &result, &junk) == 1) { *fp = result; return true; } else { return false; } } absl::string_view Uint64ToHexString(uint64_t v, char* buf) { static const char* hexdigits = "0123456789abcdef"; const int num_byte = 16; buf[num_byte] = '\0'; for (int i = num_byte - 1; i >= 0; i--) { buf[i] = hexdigits[v & 0xf]; v >>= 4; } return absl::string_view(buf, num_byte); } bool HexStringToUint64(const absl::string_view& s, uint64_t* result) { uint64_t v = 0; if (s.empty()) { return false; } for (size_t i = 0; i < s.size(); i++) { char c = s[i]; if (c >= '0' && c <= '9') { v = (v << 4) + (c - '0'); } else if (c >= 'a' && c <= 'f') { v = (v << 4) + 10 + (c - 'a'); } else if (c >= 'A' && c <= 'F') { v = (v << 4) + 10 + (c - 'A'); } else { return false; } } *result = v; return true; } std::string HumanReadableNum(int64_t value) { std::string s; if (value < 0) { s += "-"; value = -value; } if (value < 1000) { Appendf(&s, "%lld", static_cast<long long>(value)); } else if (value >= static_cast<int64_t>(1e15)) { Appendf(&s, "%0.3G", static_cast<double>(value)); } else { static const char units[] = "kMBT"; const char* unit = units; while (value >= static_cast<int64_t>(1000000)) { value /= static_cast<int64_t>(1000); ++unit; CHECK(unit < units + TF_ARRAYSIZE(units)); } Appendf(&s, "%.2f%c", value / 1000.0, *unit); } return s; } std::string HumanReadableNumBytes(int64_t num_bytes) { if (num_bytes == kint64min) { return "-8E"; } const char* neg_str = (num_bytes < 0) ? "-" : ""; if (num_bytes < 0) { num_bytes = -num_bytes; } if (num_bytes < 1024) { char buf[8]; snprintf(buf, sizeof(buf), "%s%lldB", neg_str, static_cast<long long>(num_bytes)); return std::string(buf); } static const char units[] = "KMGTPE"; const char* unit = units; while (num_bytes >= static_cast<int64_t>(1024) * 1024) { num_bytes /= 1024; ++unit; CHECK(unit < units + TF_ARRAYSIZE(units)); } char buf[16]; snprintf(buf, sizeof(buf), ((*unit == 'K') ? "%s%.1f%ciB" : "%s%.2f%ciB"), neg_str, num_bytes / 1024.0, *unit); return std::string(buf); } std::string HumanReadableElapsedTime(double seconds) { std::string human_readable; if (seconds < 0) { human_readable = "-"; seconds = -seconds; } const double microseconds = seconds * 1.0e6; if (microseconds < 999.5) { strings::Appendf(&human_readable, "%0.3g us", microseconds); return human_readable; } double milliseconds = seconds * 1e3; if (milliseconds >= .995 && milliseconds < 1) { milliseconds = 1.0; } if (milliseconds < 999.5) { strings::Appendf(&human_readable, "%0.3g ms", milliseconds); return human_readable; } if (seconds < 60.0) { strings::Appendf(&human_readable, "%0.3g s", seconds); return human_readable; } seconds /= 60.0; if (seconds < 60.0) { strings::Appendf(&human_readable, "%0.3g min", seconds); return human_readable; } seconds /= 60.0; if (seconds < 24.0) { strings::Appendf(&human_readable, "%0.3g h", seconds); return human_readable; } seconds /= 24.0; if (seconds < 30.0) { strings::Appendf(&human_readable, "%0.3g days", seconds); return human_readable; } if (seconds < 365.2425) { strings::Appendf(&human_readable, "%0.3g months", seconds / 30.436875); return human_readable; } seconds /= 365.2425; strings::Appendf(&human_readable, "%0.3g years", seconds); return human_readable; } } }
#include "tsl/platform/numbers.h" #include <cmath> #include <string> #include "tsl/platform/test.h" namespace tsl { namespace strings { TEST(FpToString, Ints) { for (int s = 0; s < 64; s++) { for (int delta = -1; delta <= 1; delta++) { uint64 fp = (1ull << s) + delta; string s = FpToString(fp); uint64 fp2; EXPECT_TRUE(StringToFp(s, &fp2)); EXPECT_EQ(fp, fp2); } } Fprint dummy; EXPECT_FALSE(StringToFp("", &dummy)); EXPECT_FALSE(StringToFp("xyz", &dummy)); EXPECT_FALSE(StringToFp("0000000000000000xyz", &dummy)); } TEST(Uint64ToHexString, Ints) { for (int s = 0; s < 64; s++) { for (int delta = -1; delta <= 1; delta++) { uint64 fp = (1ull << s) + delta; char buf[kFastToBufferSize]; absl::string_view s = Uint64ToHexString(fp, buf); uint64 fp2; EXPECT_TRUE(HexStringToUint64(s, &fp2)); EXPECT_EQ(fp, fp2) << s; } } uint64 dummy; EXPECT_FALSE(HexStringToUint64("", &dummy)); EXPECT_FALSE(HexStringToUint64("xyz", &dummy)); EXPECT_FALSE(HexStringToUint64("0000000000000000xyz", &dummy)); } TEST(HumanReadableNum, Basic) { EXPECT_EQ(HumanReadableNum(823), "823"); EXPECT_EQ(HumanReadableNum(1024), "1.02k"); EXPECT_EQ(HumanReadableNum(4000), "4.00k"); EXPECT_EQ(HumanReadableNum(999499), "999.50k"); EXPECT_EQ(HumanReadableNum(1000000), "1.00M"); EXPECT_EQ(HumanReadableNum(1048575), "1.05M"); EXPECT_EQ(HumanReadableNum(1048576), "1.05M"); EXPECT_EQ(HumanReadableNum(23956812342), "23.96B"); EXPECT_EQ(HumanReadableNum(123456789012345678), "1.23E+17"); } TEST(HumanReadableNumBytes, Bytes) { EXPECT_EQ("0B", HumanReadableNumBytes(0)); EXPECT_EQ("4B", HumanReadableNumBytes(4)); EXPECT_EQ("1023B", HumanReadableNumBytes(1023)); EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1024)); EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1025)); EXPECT_EQ("1.5KiB", HumanReadableNumBytes(1500)); EXPECT_EQ("1.9KiB", HumanReadableNumBytes(1927)); EXPECT_EQ("2.0KiB", HumanReadableNumBytes(2048)); EXPECT_EQ("1.00MiB", HumanReadableNumBytes(1 << 20)); EXPECT_EQ("11.77MiB", HumanReadableNumBytes(12345678)); EXPECT_EQ("1.00GiB", HumanReadableNumBytes(1 << 30)); EXPECT_EQ("1.00TiB", HumanReadableNumBytes(1LL << 40)); EXPECT_EQ("1.00PiB", HumanReadableNumBytes(1LL << 50)); EXPECT_EQ("1.00EiB", HumanReadableNumBytes(1LL << 60)); EXPECT_EQ("-1B", HumanReadableNumBytes(-1)); EXPECT_EQ("-4B", HumanReadableNumBytes(-4)); EXPECT_EQ("-1000B", HumanReadableNumBytes(-1000)); EXPECT_EQ("-11.77MiB", HumanReadableNumBytes(-12345678)); EXPECT_EQ("-8E", HumanReadableNumBytes(kint64min)); } TEST(HumanReadableElapsedTime, Basic) { EXPECT_EQ(HumanReadableElapsedTime(-10), "-10 s"); EXPECT_EQ(HumanReadableElapsedTime(-0.001), "-1 ms"); EXPECT_EQ(HumanReadableElapsedTime(-60.0), "-1 min"); EXPECT_EQ(HumanReadableElapsedTime(0.00000001), "0.01 us"); EXPECT_EQ(HumanReadableElapsedTime(0.0000012), "1.2 us"); EXPECT_EQ(HumanReadableElapsedTime(0.0012), "1.2 ms"); EXPECT_EQ(HumanReadableElapsedTime(0.12), "120 ms"); EXPECT_EQ(HumanReadableElapsedTime(1.12), "1.12 s"); EXPECT_EQ(HumanReadableElapsedTime(90.0), "1.5 min"); EXPECT_EQ(HumanReadableElapsedTime(600.0), "10 min"); EXPECT_EQ(HumanReadableElapsedTime(9000.0), "2.5 h"); EXPECT_EQ(HumanReadableElapsedTime(87480.0), "1.01 days"); EXPECT_EQ(HumanReadableElapsedTime(7776000.0), "2.96 months"); EXPECT_EQ(HumanReadableElapsedTime(78840000.0), "2.5 years"); EXPECT_EQ(HumanReadableElapsedTime(382386614.40), "12.1 years"); EXPECT_EQ(HumanReadableElapsedTime(DBL_MAX), "5.7e+300 years"); } TEST(safe_strto32, Int32s) { int32 result; EXPECT_EQ(true, safe_strto32("1", &result)); EXPECT_EQ(1, result); EXPECT_EQ(true, safe_strto32("123", &result)); EXPECT_EQ(123, result); EXPECT_EQ(true, safe_strto32(" -123 ", &result)); EXPECT_EQ(-123, result); EXPECT_EQ(true, safe_strto32("2147483647", &result)); EXPECT_EQ(2147483647, result); EXPECT_EQ(true, safe_strto32("-2147483648", &result)); EXPECT_EQ(-2147483648, result); EXPECT_EQ(false, safe_strto32(" 132as ", &result)); EXPECT_EQ(false, safe_strto32(" 132.2 ", &result)); EXPECT_EQ(false, safe_strto32(" -", &result)); EXPECT_EQ(false, safe_strto32("", &result)); EXPECT_EQ(false, safe_strto32(" ", &result)); EXPECT_EQ(false, safe_strto32("123 a", &result)); EXPECT_EQ(false, safe_strto32("2147483648", &result)); EXPECT_EQ(false, safe_strto32("-2147483649", &result)); EXPECT_EQ(true, safe_strto32(absl::string_view("123", 1), &result)); EXPECT_EQ(1, result); EXPECT_EQ(true, safe_strto32(absl::string_view(" -123", 4), &result)); EXPECT_EQ(-12, result); EXPECT_EQ(false, safe_strto32(absl::string_view(nullptr, 0), &result)); } TEST(safe_strtou32, UInt32s) { uint32 result; EXPECT_TRUE(safe_strtou32("0", &result)); EXPECT_EQ(0, result); EXPECT_TRUE(safe_strtou32("1", &result)); EXPECT_EQ(1, result); EXPECT_TRUE(safe_strtou32("123", &result)); EXPECT_EQ(123, result); EXPECT_TRUE(safe_strtou32("4294967295", &result)); EXPECT_EQ(4294967295, result); EXPECT_FALSE(safe_strtou32(" 132as ", &result)); EXPECT_FALSE(safe_strtou32(" 132.2 ", &result)); EXPECT_FALSE(safe_strtou32(" -", &result)); EXPECT_FALSE(safe_strtou32("", &result)); EXPECT_FALSE(safe_strtou32(" ", &result)); EXPECT_FALSE(safe_strtou32("123 a", &result)); EXPECT_FALSE(safe_strtou32("123 456", &result)); EXPECT_FALSE(safe_strtou32("4294967296", &result)); EXPECT_FALSE(safe_strtou32("-1", &result)); EXPECT_TRUE(safe_strtou32(absl::string_view("123", 1), &result)); EXPECT_EQ(1, result); EXPECT_TRUE(safe_strtou32(absl::string_view(" 123", 3), &result)); EXPECT_EQ(12, result); EXPECT_FALSE(safe_strtou32(absl::string_view(nullptr, 0), &result)); } TEST(safe_strto64, Int64s) { int64 result; EXPECT_EQ(true, safe_strto64("1", &result)); EXPECT_EQ(1, result); EXPECT_EQ(true, safe_strto64("123", &result)); EXPECT_EQ(123, result); EXPECT_EQ(true, safe_strto64(" -123 ", &result)); EXPECT_EQ(-123, result); EXPECT_EQ(true, safe_strto64("9223372036854775807", &result)); EXPECT_EQ(9223372036854775807, result); EXPECT_EQ(true, safe_strto64("-9223372036854775808", &result)); EXPECT_EQ(kint64min, result); EXPECT_EQ(false, safe_strto64(" 132as ", &result)); EXPECT_EQ(false, safe_strto64(" 132.2 ", &result)); EXPECT_EQ(false, safe_strto64(" -", &result)); EXPECT_EQ(false, safe_strto64("", &result)); EXPECT_EQ(false, safe_strto64(" ", &result)); EXPECT_EQ(false, safe_strto64("123 a", &result)); EXPECT_EQ(false, safe_strto64("9223372036854775808", &result)); EXPECT_EQ(false, safe_strto64("-9223372036854775809", &result)); EXPECT_EQ(true, safe_strto64(absl::string_view("123", 1), &result)); EXPECT_EQ(1, result); EXPECT_EQ(true, safe_strto64(absl::string_view(" -123", 4), &result)); EXPECT_EQ(-12, result); EXPECT_EQ(false, safe_strto64(absl::string_view(nullptr, 0), &result)); } TEST(safe_strtou64, UInt64s) { uint64 result; EXPECT_TRUE(safe_strtou64("0", &result)); EXPECT_EQ(0, result); EXPECT_TRUE(safe_strtou64("1", &result)); EXPECT_EQ(1, result); EXPECT_TRUE(safe_strtou64("123", &result)); EXPECT_EQ(123, result); EXPECT_TRUE(safe_strtou64(" 345 ", &result)); EXPECT_EQ(345, result); EXPECT_TRUE(safe_strtou64("18446744073709551615", &result)); EXPECT_EQ(18446744073709551615UL, result); EXPECT_FALSE(safe_strtou64(" 132.2 ", &result)); EXPECT_FALSE(safe_strtou64(" 132.2 ", &result)); EXPECT_FALSE(safe_strtou64(" -", &result)); EXPECT_FALSE(safe_strtou64("", &result)); EXPECT_FALSE(safe_strtou64(" ", &result)); EXPECT_FALSE(safe_strtou64("123 a", &result)); EXPECT_FALSE(safe_strtou64("123 456", &result)); EXPECT_FALSE(safe_strtou64("18446744073709551616", &result)); EXPECT_FALSE(safe_strtou64("-1", &result)); EXPECT_TRUE(safe_strtou64(absl::string_view("123", 1), &result)); EXPECT_EQ(1, result); EXPECT_TRUE(safe_strtou64(absl::string_view(" 123", 3), &result)); EXPECT_EQ(12, result); EXPECT_FALSE(safe_strtou64(absl::string_view(nullptr, 0), &result)); } TEST(safe_strtof, Float) { float result = 0; EXPECT_TRUE(safe_strtof("0.123456", &result)); EXPECT_EQ(0.123456f, result); EXPECT_FALSE(safe_strtof("0.12345abc", &result)); EXPECT_TRUE(safe_strtof("1e39", &result)); EXPECT_EQ(std::numeric_limits<float>::infinity(), result); EXPECT_TRUE(safe_strtof("-1e39", &result)); EXPECT_EQ(-std::numeric_limits<float>::infinity(), result); EXPECT_TRUE(safe_strtof("1e-50", &result)); EXPECT_EQ(0, result); EXPECT_TRUE(safe_strtof("0xF", &result)); EXPECT_EQ(0xF, result); EXPECT_TRUE(safe_strtof("-0x2A", &result)); EXPECT_EQ(-42.0f, result); EXPECT_TRUE(safe_strtof(" -0x2", &result)); EXPECT_EQ(-2.0f, result); EXPECT_TRUE(safe_strtof("8 \t", &result)); EXPECT_EQ(8.0f, result); EXPECT_TRUE(safe_strtof("\t20.0\t ", &result)); EXPECT_EQ(20.0f, result); EXPECT_FALSE(safe_strtof("-infinity is awesome", &result)); char test_str[2 * kFastToBufferSize]; for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a'; test_str[kFastToBufferSize + 1] = '\0'; EXPECT_FALSE(safe_strtof(test_str, &result)); EXPECT_TRUE(safe_strtof("-inf", &result)); EXPECT_EQ(-std::numeric_limits<float>::infinity(), result); EXPECT_TRUE(safe_strtof("+inf", &result)); EXPECT_EQ(std::numeric_limits<float>::infinity(), result); EXPECT_TRUE(safe_strtof("InF", &result)); EXPECT_EQ(std::numeric_limits<float>::infinity(), result); EXPECT_TRUE(safe_strtof("-INF", &result)); EXPECT_EQ(-std::numeric_limits<float>::infinity(), result); EXPECT_TRUE(safe_strtof("nan", &result)); EXPECT_TRUE(std::isnan(result)); EXPECT_TRUE(safe_strtof("-nan", &result)); EXPECT_TRUE(std::isnan(result)); EXPECT_TRUE(safe_strtof("-NaN", &result)); EXPECT_TRUE(std::isnan(result)); EXPECT_TRUE(safe_strtof("+NAN", &result)); EXPECT_TRUE(std::isnan(result)); } TEST(safe_strtod, Double) { double result = 0; EXPECT_TRUE(safe_strtod("0.1234567890123", &result)); EXPECT_EQ(0.1234567890123, result); EXPECT_FALSE(safe_strtod("0.1234567890123abc", &result)); char test_str[2 * kFastToBufferSize]; for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a'; test_str[kFastToBufferSize + 1] = '\0'; EXPECT_FALSE(safe_strtod(test_str, &result)); EXPECT_TRUE(safe_strtod("1e310", &result)); EXPECT_EQ(std::numeric_limits<double>::infinity(), result); EXPECT_TRUE(safe_strtod("-1e310", &result)); EXPECT_EQ(-std::numeric_limits<double>::infinity(), result); EXPECT_TRUE(safe_strtod("1e-325", &result)); EXPECT_EQ(0, result); EXPECT_TRUE(safe_strtod(" -0x1c", &result)); EXPECT_EQ(-28.0, result); EXPECT_TRUE(safe_strtod("50 \t", &result)); EXPECT_EQ(50.0, result); EXPECT_TRUE(safe_strtod("\t82.0\t ", &result)); EXPECT_EQ(82.0, result); EXPECT_FALSE(safe_strtod("infinity", &result)); EXPECT_TRUE(safe_strtod("-inf", &result)); EXPECT_EQ(-std::numeric_limits<double>::infinity(), result); EXPECT_TRUE(safe_strtod("+inf", &result)); EXPECT_EQ(std::numeric_limits<double>::infinity(), result); EXPECT_TRUE(safe_strtod("InF", &result)); EXPECT_EQ(std::numeric_limits<double>::infinity(), result); EXPECT_TRUE(safe_strtod("-INF", &result)); EXPECT_EQ(-std::numeric_limits<double>::infinity(), result); EXPECT_TRUE(safe_strtod("nan", &result)); EXPECT_TRUE(std::isnan(result)); EXPECT_TRUE(safe_strtod("-nan", &result)); EXPECT_TRUE(std::isnan(result)); EXPECT_TRUE(safe_strtod("-NaN", &result)); EXPECT_TRUE(std::isnan(result)); EXPECT_TRUE(safe_strtod("+NAN", &result)); EXPECT_TRUE(std::isnan(result)); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/numbers.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/numbers_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
0adf3e86-123b-42ac-bed8-469dd79ae67f
cpp
google/tsl
random
tsl/platform/random.cc
tsl/platform/random_test.cc
#include "tsl/platform/random.h" #include <memory> #include <random> #include "tsl/platform/mutex.h" #include "tsl/platform/types.h" namespace tsl { namespace random { namespace { std::mt19937_64* InitRngWithRandomSeed() { std::random_device device("/dev/urandom"); return new std::mt19937_64(device()); } std::mt19937_64 InitRngWithDefaultSeed() { return std::mt19937_64(); } } uint64 New64() { static std::mt19937_64* rng = InitRngWithRandomSeed(); static mutex mu(LINKER_INITIALIZED); mutex_lock l(mu); return (*rng)(); } uint64 ThreadLocalNew64() { static thread_local std::unique_ptr<std::mt19937_64> rng = std::unique_ptr<std::mt19937_64>(InitRngWithRandomSeed()); return (*rng)(); } uint64 New64DefaultSeed() { static std::mt19937_64 rng = InitRngWithDefaultSeed(); static mutex mu(LINKER_INITIALIZED); mutex_lock l(mu); return rng(); } } }
#include "tsl/platform/random.h" #include <set> #include "tsl/platform/test.h" #include "tsl/platform/types.h" namespace tsl { namespace random { namespace { TEST(New64Test, SanityCheck) { std::set<uint64> values; for (int i = 0; i < 1000000; i++) { uint64 x = New64(); EXPECT_TRUE(values.insert(x).second) << "duplicate " << x; } } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/random.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/random_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
95f9f454-618c-4045-9a6b-8ec0d2a97930
cpp
google/tsl
strcat
tsl/platform/strcat.cc
tsl/platform/strcat_test.cc
#include "tsl/platform/strcat.h" #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <algorithm> #include "absl/meta/type_traits.h" #include "tsl/platform/logging.h" namespace tsl { namespace strings { AlphaNum::AlphaNum(Hex hex) { char *const end = &digits_[kFastToBufferSize]; char *writer = end; uint64 value = hex.value; uint64 width = hex.spec; uint64 mask = (static_cast<uint64>(1) << (width - 1) * 4) | value; static const char hexdigits[] = "0123456789abcdef"; do { *--writer = hexdigits[value & 0xF]; value >>= 4; mask >>= 4; } while (mask != 0); piece_ = absl::string_view(writer, end - writer); } static char *Append1(char *out, const AlphaNum &x) { if (x.data() == nullptr) return out; memcpy(out, x.data(), x.size()); return out + x.size(); } static char *Append2(char *out, const AlphaNum &x1, const AlphaNum &x2) { if (x1.data() != nullptr) { memcpy(out, x1.data(), x1.size()); out += x1.size(); } if (x2.data() == nullptr) return out; memcpy(out, x2.data(), x2.size()); return out + x2.size(); } static char *Append4(char *out, const AlphaNum &x1, const AlphaNum &x2, const AlphaNum &x3, const AlphaNum &x4) { if (x1.data() != nullptr) { memcpy(out, x1.data(), x1.size()); out += x1.size(); } if (x2.data() != nullptr) { memcpy(out, x2.data(), x2.size()); out += x2.size(); } if (x3.data() != nullptr) { memcpy(out, x3.data(), x3.size()); out += x3.size(); } if (x4.data() == nullptr) return out; memcpy(out, x4.data(), x4.size()); return out + x4.size(); } string StrCat(const AlphaNum &a) { return string(a.data(), a.size()); } string StrCat(const AlphaNum &a, const AlphaNum &b) { string result(a.size() + b.size(), '\0'); char *const begin = &*result.begin(); char *out = Append2(begin, a, b); DCHECK_EQ(out, begin + result.size()); return result; } string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) { string result(a.size() + b.size() + c.size(), '\0'); char *const begin = &*result.begin(); char *out = Append2(begin, a, b); out = Append1(out, c); DCHECK_EQ(out, begin + result.size()); return result; } string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d) { string result(a.size() + b.size() + c.size() + d.size(), '\0'); char *const begin = &*result.begin(); char *out = Append4(begin, a, b, c, d); DCHECK_EQ(out, begin + result.size()); return result; } namespace { template <typename string_type, typename = void> struct ResizeUninitializedTraits { using HasMember = std::false_type; static void Resize(string_type *s, size_t new_size) { s->resize(new_size); } }; template <typename string_type> struct ResizeUninitializedTraits< string_type, absl::void_t<decltype(std::declval<string_type &>() .__resize_default_init(237))> > { using HasMember = std::true_type; static void Resize(string_type *s, size_t new_size) { s->__resize_default_init(new_size); } }; static inline void STLStringResizeUninitialized(string *s, size_t new_size) { ResizeUninitializedTraits<string>::Resize(s, new_size); } template <typename string_type> void STLStringReserveAmortized(string_type *s, size_t new_size) { const size_t cap = s->capacity(); if (new_size > cap) { s->reserve((std::max)(new_size, 2 * cap)); } } template <typename string_type> void STLStringResizeUninitializedAmortized(string_type *s, size_t new_size) { STLStringReserveAmortized(s, new_size); STLStringResizeUninitialized(s, new_size); } } namespace internal { string CatPieces(std::initializer_list<absl::string_view> pieces) { size_t total_size = 0; for (const absl::string_view piece : pieces) total_size += piece.size(); string result(total_size, '\0'); char *const begin = &*result.begin(); char *out = begin; for (const absl::string_view piece : pieces) { const size_t this_size = piece.size(); memcpy(out, piece.data(), this_size); out += this_size; } DCHECK_EQ(out, begin + result.size()); return result; } #define DCHECK_NO_OVERLAP(dest, src) \ DCHECK_GE(uintptr_t((src).data() - (dest).data()), uintptr_t((dest).size())) void AppendPieces(string *result, std::initializer_list<absl::string_view> pieces) { size_t old_size = result->size(); size_t total_size = old_size; for (const absl::string_view piece : pieces) { DCHECK_NO_OVERLAP(*result, piece); total_size += piece.size(); } STLStringResizeUninitializedAmortized(result, total_size); char *const begin = &*result->begin(); char *out = begin + old_size; for (const absl::string_view piece : pieces) { const size_t this_size = piece.size(); memcpy(out, piece.data(), this_size); out += this_size; } DCHECK_EQ(out, begin + result->size()); } } void StrAppend(string *result, const AlphaNum &a) { DCHECK_NO_OVERLAP(*result, a); result->append(a.data(), a.size()); } void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b) { DCHECK_NO_OVERLAP(*result, a); DCHECK_NO_OVERLAP(*result, b); string::size_type old_size = result->size(); STLStringResizeUninitializedAmortized(result, old_size + a.size() + b.size()); char *const begin = &*result->begin(); char *out = Append2(begin + old_size, a, b); DCHECK_EQ(out, begin + result->size()); } void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) { DCHECK_NO_OVERLAP(*result, a); DCHECK_NO_OVERLAP(*result, b); DCHECK_NO_OVERLAP(*result, c); string::size_type old_size = result->size(); STLStringResizeUninitializedAmortized( result, old_size + a.size() + b.size() + c.size()); char *const begin = &*result->begin(); char *out = Append2(begin + old_size, a, b); out = Append1(out, c); DCHECK_EQ(out, begin + result->size()); } void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d) { DCHECK_NO_OVERLAP(*result, a); DCHECK_NO_OVERLAP(*result, b); DCHECK_NO_OVERLAP(*result, c); DCHECK_NO_OVERLAP(*result, d); string::size_type old_size = result->size(); STLStringResizeUninitializedAmortized( result, old_size + a.size() + b.size() + c.size() + d.size()); char *const begin = &*result->begin(); char *out = Append4(begin + old_size, a, b, c, d); DCHECK_EQ(out, begin + result->size()); } } }
#include "tsl/platform/strcat.h" #include <string> #include "absl/strings/string_view.h" #include "tsl/platform/stringprintf.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #ifdef _MSC_VER typedef ptrdiff_t ssize_t; #endif namespace tsl { namespace strings { TEST(StrCat, Ints) { const int16_t s = -1; const uint16 us = 2; const int i = -3; const unsigned int ui = 4; const int32_t l = -5; const uint32 ul = 6; const int64_t ll = -7; const uint64 ull = 8; const ptrdiff_t ptrdiff = -9; const size_t size = 10; const ssize_t ssize = -11; const intptr_t intptr = -12; const uintptr_t uintptr = 13; string answer; answer = StrCat(s, us); EXPECT_EQ(answer, "-12"); answer = StrCat(i, ui); EXPECT_EQ(answer, "-34"); answer = StrCat(l, ul); EXPECT_EQ(answer, "-56"); answer = StrCat(ll, ull); EXPECT_EQ(answer, "-78"); answer = StrCat(ptrdiff, size); EXPECT_EQ(answer, "-910"); answer = StrCat(ssize, intptr); EXPECT_EQ(answer, "-11-12"); answer = StrCat(uintptr, 0); EXPECT_EQ(answer, "130"); } TEST(StrCat, Floats) { const int s = 0; const float f = 1.5f; const double d = 1.5; const bfloat16 bf(1.5f); string answer; answer = StrCat(s, f); EXPECT_EQ(answer, "01.5"); answer = StrCat(s, d); EXPECT_EQ(answer, "01.5"); answer = StrCat(s, bf); EXPECT_EQ(answer, "01.5"); } TEST(StrCat, Nulls) { string result; absl::string_view v; string strs[] = {"Hello", "Cruel", "World"}; result = StrCat(v); EXPECT_EQ(result, ""); result = StrCat(strs[0], v); EXPECT_EQ(result, "Hello"); result = StrCat(v, strs[0]); EXPECT_EQ(result, "Hello"); result = StrCat(v, strs[0], strs[1]); EXPECT_EQ(result, "HelloCruel"); result = StrCat(strs[0], v, strs[1]); EXPECT_EQ(result, "HelloCruel"); result = StrCat(strs[0], strs[1], v); EXPECT_EQ(result, "HelloCruel"); result = StrCat(v, strs[0], strs[1], strs[2]); EXPECT_EQ(result, "HelloCruelWorld"); result = StrCat(strs[0], v, strs[1], strs[2]); EXPECT_EQ(result, "HelloCruelWorld"); result = StrCat(strs[0], strs[1], v, strs[2]); EXPECT_EQ(result, "HelloCruelWorld"); result = StrCat(strs[0], strs[1], strs[2], v); EXPECT_EQ(result, "HelloCruelWorld"); } TEST(StrCat, Basics) { string result; string strs[] = {"Hello", "Cruel", "World"}; absl::string_view pieces[] = {"Hello", "Cruel", "World"}; const char *c_strs[] = {"Hello", "Cruel", "World"}; int32 i32s[] = {'H', 'C', 'W'}; uint64 ui64s[] = {12345678910LL, 10987654321LL}; result = StrCat(false, true, 2, 3); EXPECT_EQ(result, "0123"); result = StrCat(-1); EXPECT_EQ(result, "-1"); result = StrCat(0.5); EXPECT_EQ(result, "0.5"); result = StrCat(strs[1], pieces[2]); EXPECT_EQ(result, "CruelWorld"); result = StrCat(strs[0], ", ", pieces[2]); EXPECT_EQ(result, "Hello, World"); result = StrCat(strs[0], ", ", strs[1], " ", strs[2], "!"); EXPECT_EQ(result, "Hello, Cruel World!"); result = StrCat(pieces[0], ", ", pieces[1], " ", pieces[2]); EXPECT_EQ(result, "Hello, Cruel World"); result = StrCat(c_strs[0], ", ", c_strs[1], " ", c_strs[2]); EXPECT_EQ(result, "Hello, Cruel World"); result = StrCat("ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!"); EXPECT_EQ(result, "ASCII 72, 67 87!"); result = StrCat(ui64s[0], ", ", ui64s[1], "!"); EXPECT_EQ(result, "12345678910, 10987654321!"); string one = "1"; result = StrCat("And a ", one.size(), " and a ", &result[2] - &result[0], " and a ", one, " 2 3 4", "!"); EXPECT_EQ(result, "And a 1 and a 2 and a 1 2 3 4!"); result = StrCat("To output a char by ASCII/numeric value, use +: ", '!' + 0); EXPECT_EQ(result, "To output a char by ASCII/numeric value, use +: 33"); float f = 100000.5; result = StrCat("A hundred K and a half is ", f); EXPECT_EQ(result, "A hundred K and a half is 100000.5"); double d = f; d *= d; result = StrCat("A hundred K and a half squared is ", d); EXPECT_EQ(result, "A hundred K and a half squared is 10000100000.25"); result = StrCat(1, 2, 333, 4444, 55555, 666666, 7777777, 88888888, 999999999); EXPECT_EQ(result, "12333444455555666666777777788888888999999999"); } TEST(StrCat, MaxArgs) { string result; result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a"); EXPECT_EQ(result, "123456789a"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b"); EXPECT_EQ(result, "123456789ab"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c"); EXPECT_EQ(result, "123456789abc"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d"); EXPECT_EQ(result, "123456789abcd"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e"); EXPECT_EQ(result, "123456789abcde"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"); EXPECT_EQ(result, "123456789abcdef"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g"); EXPECT_EQ(result, "123456789abcdefg"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h"); EXPECT_EQ(result, "123456789abcdefgh"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i"); EXPECT_EQ(result, "123456789abcdefghi"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); EXPECT_EQ(result, "123456789abcdefghij"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); EXPECT_EQ(result, "123456789abcdefghijk"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"); EXPECT_EQ(result, "123456789abcdefghijkl"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"); EXPECT_EQ(result, "123456789abcdefghijklm"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"); EXPECT_EQ(result, "123456789abcdefghijklmn"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"); EXPECT_EQ(result, "123456789abcdefghijklmno"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"); EXPECT_EQ(result, "123456789abcdefghijklmnop"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q"); EXPECT_EQ(result, "123456789abcdefghijklmnopq"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); EXPECT_EQ(result, "12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); } TEST(StrAppend, Basics) { string result = "existing text"; string strs[] = {"Hello", "Cruel", "World"}; absl::string_view pieces[] = {"Hello", "Cruel", "World"}; const char *c_strs[] = {"Hello", "Cruel", "World"}; int32 i32s[] = {'H', 'C', 'W'}; uint64 ui64s[] = {12345678910LL, 10987654321LL}; string::size_type old_size = result.size(); StrAppend(&result, strs[0]); EXPECT_EQ(result.substr(old_size), "Hello"); old_size = result.size(); StrAppend(&result, strs[1], pieces[2]); EXPECT_EQ(result.substr(old_size), "CruelWorld"); old_size = result.size(); StrAppend(&result, strs[0], ", ", pieces[2]); EXPECT_EQ(result.substr(old_size), "Hello, World"); old_size = result.size(); StrAppend(&result, strs[0], ", ", strs[1], " ", strs[2], "!"); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World!"); old_size = result.size(); StrAppend(&result, pieces[0], ", ", pieces[1], " ", pieces[2]); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World"); old_size = result.size(); StrAppend(&result, c_strs[0], ", ", c_strs[1], " ", c_strs[2]); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World"); old_size = result.size(); StrAppend(&result, "ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!"); EXPECT_EQ(result.substr(old_size), "ASCII 72, 67 87!"); old_size = result.size(); StrAppend(&result, ui64s[0], ", ", ui64s[1], "!"); EXPECT_EQ(result.substr(old_size), "12345678910, 10987654321!"); string one = "1"; old_size = result.size(); StrAppend(&result, "And a ", one.size(), " and a ", &result[2] - &result[0], " and a ", one, " 2 3 4", "!"); EXPECT_EQ(result.substr(old_size), "And a 1 and a 2 and a 1 2 3 4!"); old_size = result.size(); StrAppend(&result, "To output a char by ASCII/numeric value, use +: ", '!' + 0); EXPECT_EQ(result.substr(old_size), "To output a char by ASCII/numeric value, use +: 33"); float f = 100000.5; old_size = result.size(); StrAppend(&result, "A hundred K and a half is ", f); EXPECT_EQ(result.substr(old_size), "A hundred K and a half is 100000.5"); double d = f; d *= d; old_size = result.size(); StrAppend(&result, "A hundred K and a half squared is ", d); EXPECT_EQ(result.substr(old_size), "A hundred K and a half squared is 10000100000.25"); old_size = result.size(); StrAppend(&result, 1, 22, 333, 4444, 55555, 666666, 7777777, 88888888, 9); EXPECT_EQ(result.substr(old_size), "1223334444555556666667777777888888889"); old_size = result.size(); StrAppend(&result, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "No limit thanks to C++11's variadic templates"); EXPECT_EQ(result.substr(old_size), "12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" "No limit thanks to C++11's variadic templates"); } TEST(StrAppend, Death) { string s = "self"; EXPECT_DEBUG_DEATH(StrAppend(&s, s.c_str() + 1), "Check failed:"); EXPECT_DEBUG_DEATH(StrAppend(&s, s), "Check failed:"); } static void CheckHex64(uint64 v) { string actual = StrCat(Hex(v, kZeroPad16)); string expected = Printf("%016llx", static_cast<unsigned long long>(v)); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v, kZeroPad8)); expected = Printf("%08llx", static_cast<unsigned long long>(v)); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v)); expected = Printf("%llx", static_cast<unsigned long long>(v)); EXPECT_EQ(expected, actual) << " decimal value " << v; } static void CheckHex32(uint32 v) { string actual = StrCat(Hex(v, kZeroPad8)); string expected = Printf("%08x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v)); expected = Printf("%x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; } static void CheckHexSigned32(int32_t v) { string actual = StrCat(Hex(v, kZeroPad8)); string expected = Printf("%08x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v)); expected = Printf("%x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; } static void TestFastPrints() { for (int i = 0; i < 10000; i++) { CheckHex64(i); CheckHex32(i); CheckHexSigned32(i); CheckHexSigned32(-i); } CheckHex64(0x123456789abcdef0ull); CheckHex32(0x12345678); int8_t minus_one_8bit = -1; EXPECT_EQ("ff", StrCat(Hex(minus_one_8bit))); int16_t minus_one_16bit = -1; EXPECT_EQ("ffff", StrCat(Hex(minus_one_16bit))); } TEST(Numbers, TestFunctionsMovedOverFromNumbersMain) { TestFastPrints(); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/strcat.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/strcat_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
97bc17f6-6af4-452c-a3ae-cc0e453a192e
cpp
google/tsl
scanner
tsl/platform/scanner.cc
tsl/platform/scanner_test.cc
#include "tsl/platform/scanner.h" namespace tsl { namespace strings { void Scanner::ScanUntilImpl(char end_ch, bool escaped) { for (;;) { if (cur_.empty()) { Error(); return; } const char ch = cur_[0]; if (ch == end_ch) { return; } cur_.remove_prefix(1); if (escaped && ch == '\\') { if (cur_.empty()) { Error(); return; } cur_.remove_prefix(1); } } } bool Scanner::GetResult(absl::string_view* remaining, absl::string_view* capture) { if (error_) { return false; } if (remaining != nullptr) { *remaining = cur_; } if (capture != nullptr) { const char* end = capture_end_ == nullptr ? cur_.data() : capture_end_; *capture = absl::string_view(capture_start_, end - capture_start_); } return true; } } }
#include "tsl/platform/scanner.h" #include "tsl/platform/test.h" namespace tsl { namespace strings { class ScannerTest : public ::testing::Test { protected: string ClassStr(Scanner::CharClass clz) { string s; for (int i = 0; i < 256; ++i) { char ch = i; if (Scanner::Matches(clz, ch)) { s += ch; } } return s; } }; TEST_F(ScannerTest, Any) { absl::string_view remaining, match; EXPECT_TRUE(Scanner(" horse0123") .Any(Scanner::SPACE) .Any(Scanner::DIGIT) .Any(Scanner::LETTER) .GetResult(&remaining, &match)); EXPECT_EQ(" horse", match); EXPECT_EQ("0123", remaining); EXPECT_TRUE(Scanner("") .Any(Scanner::SPACE) .Any(Scanner::DIGIT) .Any(Scanner::LETTER) .GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("", match); EXPECT_TRUE(Scanner("----") .Any(Scanner::SPACE) .Any(Scanner::DIGIT) .Any(Scanner::LETTER) .GetResult(&remaining, &match)); EXPECT_EQ("----", remaining); EXPECT_EQ("", match); } TEST_F(ScannerTest, AnySpace) { absl::string_view remaining, match; EXPECT_TRUE(Scanner(" a b ") .AnySpace() .One(Scanner::LETTER) .AnySpace() .GetResult(&remaining, &match)); EXPECT_EQ(" a ", match); EXPECT_EQ("b ", remaining); } TEST_F(ScannerTest, AnyEscapedNewline) { absl::string_view remaining, match; EXPECT_TRUE(Scanner("\\\n") .Any(Scanner::LETTER_DIGIT_UNDERSCORE) .GetResult(&remaining, &match)); EXPECT_EQ("\\\n", remaining); EXPECT_EQ("", match); } TEST_F(ScannerTest, AnyEmptyString) { absl::string_view remaining, match; EXPECT_TRUE(Scanner("") .Any(Scanner::LETTER_DIGIT_UNDERSCORE) .GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("", match); } TEST_F(ScannerTest, Eos) { EXPECT_FALSE(Scanner("a").Eos().GetResult()); EXPECT_TRUE(Scanner("").Eos().GetResult()); EXPECT_FALSE(Scanner("abc").OneLiteral("ab").Eos().GetResult()); EXPECT_TRUE(Scanner("abc").OneLiteral("abc").Eos().GetResult()); } TEST_F(ScannerTest, Many) { absl::string_view remaining, match; EXPECT_TRUE(Scanner("abc").Many(Scanner::LETTER).GetResult()); EXPECT_FALSE(Scanner("0").Many(Scanner::LETTER).GetResult()); EXPECT_FALSE(Scanner("").Many(Scanner::LETTER).GetResult()); EXPECT_TRUE( Scanner("abc ").Many(Scanner::LETTER).GetResult(&remaining, &match)); EXPECT_EQ(" ", remaining); EXPECT_EQ("abc", match); EXPECT_TRUE( Scanner("abc").Many(Scanner::LETTER).GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("abc", match); } TEST_F(ScannerTest, One) { absl::string_view remaining, match; EXPECT_TRUE(Scanner("abc").One(Scanner::LETTER).GetResult()); EXPECT_FALSE(Scanner("0").One(Scanner::LETTER).GetResult()); EXPECT_FALSE(Scanner("").One(Scanner::LETTER).GetResult()); EXPECT_TRUE(Scanner("abc") .One(Scanner::LETTER) .One(Scanner::LETTER) .GetResult(&remaining, &match)); EXPECT_EQ("c", remaining); EXPECT_EQ("ab", match); EXPECT_TRUE(Scanner("a").One(Scanner::LETTER).GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("a", match); } TEST_F(ScannerTest, OneLiteral) { EXPECT_FALSE(Scanner("abc").OneLiteral("abC").GetResult()); EXPECT_TRUE(Scanner("abc").OneLiteral("ab").OneLiteral("c").GetResult()); } TEST_F(ScannerTest, ScanUntil) { absl::string_view remaining, match; EXPECT_TRUE(Scanner(R"(' \1 \2 \3 \' \\'rest)") .OneLiteral("'") .ScanUntil('\'') .OneLiteral("'") .GetResult(&remaining, &match)); EXPECT_EQ(R"( \\'rest)", remaining); EXPECT_EQ(R"(' \1 \2 \3 \')", match); remaining = match = "unset"; EXPECT_FALSE(Scanner(R"(' \1 \2 \3 \\rest)") .OneLiteral("'") .ScanUntil('\'') .GetResult(&remaining, &match)); EXPECT_EQ("unset", remaining); EXPECT_EQ("unset", match); remaining = match = ""; EXPECT_TRUE( Scanner(R"(123\456)").ScanUntil('\\').GetResult(&remaining, &match)); EXPECT_EQ(R"(\456)", remaining); EXPECT_EQ("123", match); } TEST_F(ScannerTest, ScanEscapedUntil) { absl::string_view remaining, match; EXPECT_TRUE(Scanner(R"(' \1 \2 \3 \' \\'rest)") .OneLiteral("'") .ScanEscapedUntil('\'') .OneLiteral("'") .GetResult(&remaining, &match)); EXPECT_EQ("rest", remaining); EXPECT_EQ(R"(' \1 \2 \3 \' \\')", match); remaining = match = "unset"; EXPECT_FALSE(Scanner(R"(' \1 \2 \3 \' \\rest)") .OneLiteral("'") .ScanEscapedUntil('\'') .GetResult(&remaining, &match)); EXPECT_EQ("unset", remaining); EXPECT_EQ("unset", match); } TEST_F(ScannerTest, ZeroOrOneLiteral) { absl::string_view remaining, match; EXPECT_TRUE( Scanner("abc").ZeroOrOneLiteral("abC").GetResult(&remaining, &match)); EXPECT_EQ("abc", remaining); EXPECT_EQ("", match); EXPECT_TRUE( Scanner("abcd").ZeroOrOneLiteral("ab").ZeroOrOneLiteral("c").GetResult( &remaining, &match)); EXPECT_EQ("d", remaining); EXPECT_EQ("abc", match); EXPECT_TRUE( Scanner("").ZeroOrOneLiteral("abc").GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("", match); } TEST_F(ScannerTest, CaptureAndGetResult) { absl::string_view remaining, match; Scanner scan(" first second"); EXPECT_TRUE(scan.Any(Scanner::SPACE) .RestartCapture() .One(Scanner::LETTER) .Any(Scanner::LETTER_DIGIT) .StopCapture() .Any(Scanner::SPACE) .GetResult(&remaining, &match)); EXPECT_EQ("second", remaining); EXPECT_EQ("first", match); EXPECT_TRUE(scan.GetResult()); remaining = ""; EXPECT_TRUE(scan.GetResult(&remaining)); EXPECT_EQ("second", remaining); remaining = ""; match = ""; EXPECT_TRUE(scan.GetResult(&remaining, &match)); EXPECT_EQ("second", remaining); EXPECT_EQ("first", match); scan.RestartCapture().One(Scanner::LETTER).One(Scanner::LETTER); remaining = ""; match = ""; EXPECT_TRUE(scan.GetResult(&remaining, &match)); EXPECT_EQ("cond", remaining); EXPECT_EQ("se", match); } TEST_F(ScannerTest, MultipleGetResultExtendsCapture) { absl::string_view remaining, match; Scanner scan("one2three"); EXPECT_TRUE(scan.Many(Scanner::LETTER).GetResult(&remaining, &match)); EXPECT_EQ("2three", remaining); EXPECT_EQ("one", match); EXPECT_TRUE(scan.Many(Scanner::DIGIT).GetResult(&remaining, &match)); EXPECT_EQ("three", remaining); EXPECT_EQ("one2", match); EXPECT_TRUE(scan.Many(Scanner::LETTER).GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("one2three", match); } TEST_F(ScannerTest, FailedMatchDoesntChangeResult) { Scanner scan("name"); absl::string_view remaining = "rem"; absl::string_view match = "match"; EXPECT_FALSE(scan.One(Scanner::SPACE).GetResult(&remaining, &match)); EXPECT_EQ("rem", remaining); EXPECT_EQ("match", match); } TEST_F(ScannerTest, DefaultCapturesAll) { Scanner scan("a b"); absl::string_view remaining = "rem"; absl::string_view match = "match"; EXPECT_TRUE(scan.Any(Scanner::LETTER) .AnySpace() .Any(Scanner::LETTER) .GetResult(&remaining, &match)); EXPECT_EQ("", remaining); EXPECT_EQ("a b", match); } TEST_F(ScannerTest, AllCharClasses) { EXPECT_EQ(256, ClassStr(Scanner::ALL).size()); EXPECT_EQ("0123456789", ClassStr(Scanner::DIGIT)); EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER)); EXPECT_EQ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT)); EXPECT_EQ( "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_" "abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_DASH_UNDERSCORE)); EXPECT_EQ( "-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_DASH_DOT_SLASH)); EXPECT_EQ( "-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_" "abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE)); EXPECT_EQ(".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_DOT)); EXPECT_EQ("+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_DOT_PLUS_MINUS)); EXPECT_EQ(".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_DOT_UNDERSCORE)); EXPECT_EQ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LETTER_DIGIT_UNDERSCORE)); EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LOWERLETTER)); EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LOWERLETTER_DIGIT)); EXPECT_EQ("0123456789_abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LOWERLETTER_DIGIT_UNDERSCORE)); EXPECT_EQ("123456789", ClassStr(Scanner::NON_ZERO_DIGIT)); EXPECT_EQ("\t\n\v\f\r ", ClassStr(Scanner::SPACE)); EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", ClassStr(Scanner::UPPERLETTER)); EXPECT_EQ(">", ClassStr(Scanner::RANGLE)); } TEST_F(ScannerTest, Peek) { EXPECT_EQ('a', Scanner("abc").Peek()); EXPECT_EQ('a', Scanner("abc").Peek('b')); EXPECT_EQ('\0', Scanner("").Peek()); EXPECT_EQ('z', Scanner("").Peek('z')); EXPECT_EQ('A', Scanner("0123A").Any(Scanner::DIGIT).Peek()); EXPECT_EQ('\0', Scanner("0123A").Any(Scanner::LETTER_DIGIT).Peek()); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/scanner.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/scanner_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
f681c41e-8beb-4b1d-9b31-c9afbba8d48d
cpp
google/tsl
stringprintf
tsl/platform/stringprintf.cc
tsl/platform/stringprintf_test.cc
#include "tsl/platform/stringprintf.h" #include <errno.h> #include <stdarg.h> #include <stdio.h> namespace tsl { namespace strings { void Appendv(string* dst, const char* format, va_list ap) { static const int kSpaceLength = 1024; char space[kSpaceLength]; va_list backup_ap; va_copy(backup_ap, ap); int result = vsnprintf(space, kSpaceLength, format, backup_ap); va_end(backup_ap); if (result < kSpaceLength) { if (result >= 0) { dst->append(space, result); return; } #ifdef _MSC_VER va_copy(backup_ap, ap); result = vsnprintf(nullptr, 0, format, backup_ap); va_end(backup_ap); #endif if (result < 0) { return; } } int length = result + 1; char* buf = new char[length]; va_copy(backup_ap, ap); result = vsnprintf(buf, length, format, backup_ap); va_end(backup_ap); if (result >= 0 && result < length) { dst->append(buf, result); } delete[] buf; } string Printf(const char* format, ...) { va_list ap; va_start(ap, format); string result; Appendv(&result, format, ap); va_end(ap); return result; } void Appendf(string* dst, const char* format, ...) { va_list ap; va_start(ap, format); Appendv(dst, format, ap); va_end(ap); } } }
#include "tsl/platform/stringprintf.h" #include <string> #include "tsl/platform/test.h" namespace tsl { namespace strings { namespace { TEST(PrintfTest, Empty) { EXPECT_EQ("", Printf("%s", string().c_str())); EXPECT_EQ("", Printf("%s", "")); } TEST(PrintfTest, Misc) { #if !defined(_MSC_VER) EXPECT_EQ("123hello w", Printf("%3$d%2$s %1$c", 'w', "hello", 123)); #endif } TEST(AppendfTest, Empty) { string value("Hello"); const char* empty = ""; Appendf(&value, "%s", empty); EXPECT_EQ("Hello", value); } TEST(AppendfTest, EmptyString) { string value("Hello"); Appendf(&value, "%s", ""); EXPECT_EQ("Hello", value); } TEST(AppendfTest, String) { string value("Hello"); Appendf(&value, " %s", "World"); EXPECT_EQ("Hello World", value); } TEST(AppendfTest, Int) { string value("Hello"); Appendf(&value, " %d", 123); EXPECT_EQ("Hello 123", value); } TEST(PrintfTest, Multibyte) { char* old_locale = setlocale(LC_CTYPE, nullptr); setlocale(LC_CTYPE, "en_US.utf8"); const char kInvalidCodePoint[] = "\375\067s"; string value = Printf("%.*s", 3, kInvalidCodePoint); EXPECT_TRUE(value.empty() || value == kInvalidCodePoint); int n = 2048; char* buf = new char[n + 1]; memset(buf, ' ', n - 3); memcpy(buf + n - 3, kInvalidCodePoint, 4); value = Printf("%.*s", n, buf); EXPECT_TRUE(value.empty() || value == buf); delete[] buf; setlocale(LC_CTYPE, old_locale); } TEST(PrintfTest, NoMultibyte) { char* old_locale = setlocale(LC_CTYPE, nullptr); setlocale(LC_CTYPE, "POSIX"); string value = Printf("%.*s", 3, "\375\067s"); setlocale(LC_CTYPE, old_locale); EXPECT_EQ("\375\067s", value); } TEST(PrintfTest, DontOverwriteErrno) { errno = ECHILD; string value = Printf("Hello, %s!", "World"); EXPECT_EQ(ECHILD, errno); } TEST(PrintfTest, LargeBuf) { int n = 2048; char* buf = new char[n + 1]; memset(buf, ' ', n); buf[n] = 0; string value = Printf("%s", buf); EXPECT_EQ(buf, value); delete[] buf; } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/stringprintf.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/stringprintf_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
b88ae0a9-9163-417c-9fd6-5923a08dc599
cpp
google/tsl
denormal
tsl/platform/denormal.cc
tsl/platform/denormal_test.cc
#include "tsl/platform/denormal.h" #include <cstdint> #include "tsl/platform/cpu_info.h" #include "tsl/platform/platform.h" #if !defined(__SSE3__) && !defined(__clang__) && \ (defined(__GNUC__) && (__GNUC__ < 4) || \ ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))) #define GCC_WITHOUT_INTRINSICS #endif #if defined(PLATFORM_IS_X86) && !defined(IS_MOBILE_PLATFORM) && \ !defined(GCC_WITHOUT_INTRINSICS) #define X86_DENORM_USE_INTRINSICS #endif #ifdef X86_DENORM_USE_INTRINSICS #include <pmmintrin.h> #endif #if defined(PLATFORM_IS_ARM) && defined(__ARM_FP) && (__ARM_FP > 0) #define ARM_DENORM_AVAILABLE #define ARM_FPCR_FZ (1 << 24) #endif namespace tsl { namespace port { bool DenormalState::operator==(const DenormalState& other) const { return flush_to_zero() == other.flush_to_zero() && denormals_are_zero() == other.denormals_are_zero(); } bool DenormalState::operator!=(const DenormalState& other) const { return !(this->operator==(other)); } #ifdef ARM_DENORM_AVAILABLE static inline void ArmSetFloatingPointControlRegister(uint32_t fpcr) { #ifdef PLATFORM_IS_ARM64 __asm__ __volatile__("msr fpcr, %[fpcr]" : : [fpcr] "r"(static_cast<uint64_t>(fpcr))); #else __asm__ __volatile__("vmsr fpscr, %[fpcr]" : : [fpcr] "r"(fpcr)); #endif } static inline uint32_t ArmGetFloatingPointControlRegister() { uint32_t fpcr; #ifdef PLATFORM_IS_ARM64 uint64_t fpcr64; __asm__ __volatile__("mrs %[fpcr], fpcr" : [fpcr] "=r"(fpcr64)); fpcr = static_cast<uint32_t>(fpcr64); #else __asm__ __volatile__("vmrs %[fpcr], fpscr" : [fpcr] "=r"(fpcr)); #endif return fpcr; } #endif bool SetDenormalState(const DenormalState& state) { #ifdef X86_DENORM_USE_INTRINSICS if (TestCPUFeature(SSE3)) { _MM_SET_FLUSH_ZERO_MODE(state.flush_to_zero() ? _MM_FLUSH_ZERO_ON : _MM_FLUSH_ZERO_OFF); _MM_SET_DENORMALS_ZERO_MODE(state.denormals_are_zero() ? _MM_DENORMALS_ZERO_ON : _MM_DENORMALS_ZERO_OFF); return true; } #endif #ifdef ARM_DENORM_AVAILABLE if (state.flush_to_zero() == state.denormals_are_zero()) { uint32_t fpcr = ArmGetFloatingPointControlRegister(); if (state.flush_to_zero()) { fpcr |= ARM_FPCR_FZ; } else { fpcr &= ~ARM_FPCR_FZ; } ArmSetFloatingPointControlRegister(fpcr); return true; } #endif return false; } DenormalState GetDenormalState() { #ifdef X86_DENORM_USE_INTRINSICS if (TestCPUFeature(SSE3)) { bool flush_zero_mode = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON; bool denormals_zero_mode = _MM_GET_DENORMALS_ZERO_MODE() == _MM_DENORMALS_ZERO_ON; return DenormalState(flush_zero_mode, denormals_zero_mode); } #endif #ifdef ARM_DENORM_AVAILABLE uint32_t fpcr = ArmGetFloatingPointControlRegister(); if ((fpcr & ARM_FPCR_FZ) != 0) { return DenormalState(true, true); } #endif return DenormalState(false, false); } ScopedRestoreFlushDenormalState::ScopedRestoreFlushDenormalState() : denormal_state_(GetDenormalState()) {} ScopedRestoreFlushDenormalState::~ScopedRestoreFlushDenormalState() { SetDenormalState(denormal_state_); } ScopedFlushDenormal::ScopedFlushDenormal() { SetDenormalState( DenormalState(true, true)); } ScopedDontFlushDenormal::ScopedDontFlushDenormal() { SetDenormalState( DenormalState(false, false)); } } }
#include "tsl/platform/denormal.h" #include <cstring> #include <limits> #include "tsl/platform/test.h" namespace tsl { namespace port { TEST(DenormalStateTest, ConstructorAndAccessorsWork) { const bool flush_to_zero[] = {true, true, false, false}; const bool denormals_are_zero[] = {true, false, true, false}; for (int i = 0; i < 4; ++i) { const DenormalState state = DenormalState(flush_to_zero[i], denormals_are_zero[i]); EXPECT_EQ(state.flush_to_zero(), flush_to_zero[i]); EXPECT_EQ(state.denormals_are_zero(), denormals_are_zero[i]); } } uint32_t bits(float x) { uint32_t out; memcpy(&out, &x, sizeof(float)); return out; } void CheckDenormalHandling(const DenormalState& state) { volatile float denormal_output = std::numeric_limits<float>::min(); denormal_output *= 0.25f; if (state.flush_to_zero()) { EXPECT_EQ(bits(denormal_output), 0x0); } else { EXPECT_NE(bits(denormal_output), 0x0); } volatile float normal_output = std::numeric_limits<float>::denorm_min(); normal_output *= std::numeric_limits<float>::max(); if (state.denormals_are_zero()) { EXPECT_EQ(bits(normal_output), 0x0); } else { EXPECT_NE(bits(normal_output), 0x0); } } TEST(DenormalTest, GetAndSetStateWorkWithCorrectFlushing) { const DenormalState states[] = { DenormalState(true, true), DenormalState(true, false), DenormalState(false, true), DenormalState(false, false)}; for (const DenormalState& state : states) { if (SetDenormalState(state)) { EXPECT_EQ(GetDenormalState(), state); CheckDenormalHandling(state); } } } TEST(ScopedRestoreFlushDenormalStateTest, RestoresState) { const DenormalState flush_denormals(true, true); const DenormalState dont_flush_denormals(false, false); const bool can_set_denormal_state = SetDenormalState(flush_denormals) && SetDenormalState(dont_flush_denormals); if (can_set_denormal_state) { SetDenormalState(flush_denormals); { ScopedRestoreFlushDenormalState restore_state; SetDenormalState(dont_flush_denormals); EXPECT_EQ(GetDenormalState(), dont_flush_denormals); } EXPECT_EQ(GetDenormalState(), flush_denormals); SetDenormalState(dont_flush_denormals); { ScopedRestoreFlushDenormalState restore_state; SetDenormalState(flush_denormals); EXPECT_EQ(GetDenormalState(), flush_denormals); } EXPECT_EQ(GetDenormalState(), dont_flush_denormals); } } TEST(ScopedFlushDenormalTest, SetsFlushingAndRestoresState) { const DenormalState flush_denormals(true, true); const DenormalState dont_flush_denormals(false, false); const bool can_set_denormal_state = SetDenormalState(flush_denormals) && SetDenormalState(dont_flush_denormals); if (can_set_denormal_state) { SetDenormalState(dont_flush_denormals); { ScopedFlushDenormal scoped_flush_denormal; EXPECT_EQ(GetDenormalState(), flush_denormals); } EXPECT_EQ(GetDenormalState(), dont_flush_denormals); } } TEST(ScopedDontFlushDenormalTest, SetsNoFlushingAndRestoresState) { const DenormalState flush_denormals(true, true); const DenormalState dont_flush_denormals(false, false); const bool can_set_denormal_state = SetDenormalState(flush_denormals) && SetDenormalState(dont_flush_denormals); if (can_set_denormal_state) { SetDenormalState(flush_denormals); { ScopedDontFlushDenormal scoped_dont_flush_denormal; EXPECT_EQ(GetDenormalState(), dont_flush_denormals); } EXPECT_EQ(GetDenormalState(), flush_denormals); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/denormal.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/denormal_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
f8e58a8a-64b4-41fc-96b5-e19ca6c2683f
cpp
google/tsl
retrying_utils
tsl/platform/retrying_utils.cc
tsl/platform/retrying_utils_test.cc
#include "tsl/platform/retrying_utils.h" #include <algorithm> #include <cmath> #include <cstdint> #include <limits> #include "absl/time/time.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/file_system.h" #include "tsl/platform/logging.h" #include "tsl/platform/random.h" namespace tsl { namespace { bool IsRetriable(absl::StatusCode code) { switch (code) { case absl::StatusCode::kUnavailable: case absl::StatusCode::kDeadlineExceeded: case absl::StatusCode::kUnknown: return true; default: return false; } } double GenerateUniformRandomNumber() { return random::New64() * (1.0 / std::numeric_limits<uint64_t>::max()); } double GenerateUniformRandomNumberBetween(double a, double b) { if (a == b) return a; DCHECK_LT(a, b); return a + GenerateUniformRandomNumber() * (b - a); } } absl::Status RetryingUtils::CallWithRetries( const std::function<absl::Status()>& f, const RetryConfig& config) { return CallWithRetries( f, [](int64_t micros) { return Env::Default()->SleepForMicroseconds(micros); }, config); } absl::Status RetryingUtils::CallWithRetries( const std::function<absl::Status()>& f, const std::function<void(int64_t)>& sleep_usec, const RetryConfig& config) { int retries = 0; while (true) { auto status = f(); if (!IsRetriable(status.code())) { return status; } if (retries >= config.max_retries) { return absl::Status( absl::StatusCode::kAborted, strings::StrCat( "All ", config.max_retries, " retry attempts failed. The last failure: ", status.message())); } int64_t delay_micros = 0; if (config.init_delay_time_us > 0) { const int64_t random_micros = random::New64() % 1000000; delay_micros = std::min(config.init_delay_time_us << retries, config.max_delay_time_us) + random_micros; } VLOG(1) << "The operation failed and will be automatically retried in " << (delay_micros / 1000000.0) << " seconds (attempt " << (retries + 1) << " out of " << config.max_retries << "), caused by: " << status.ToString(); sleep_usec(delay_micros); retries++; } } absl::Status RetryingUtils::DeleteWithRetries( const std::function<absl::Status()>& delete_func, const RetryConfig& config) { bool is_retried = false; return RetryingUtils::CallWithRetries( [delete_func, &is_retried]() { const absl::Status status = delete_func(); if (is_retried && status.code() == error::NOT_FOUND) { return absl::OkStatus(); } is_retried = true; return status; }, config); } absl::Duration ComputeRetryBackoff(int current_retry_attempt, absl::Duration min_delay, absl::Duration max_delay) { DCHECK_GE(current_retry_attempt, 0); constexpr double kBackoffBase = 1.3; constexpr double kBackoffRandMult = 0.4; const absl::Duration first_term = min_delay * kBackoffRandMult; absl::Duration uncapped_second_term = min_delay * std::pow(kBackoffBase, current_retry_attempt); absl::Duration second_term = std::min(uncapped_second_term, max_delay - first_term); second_term *= GenerateUniformRandomNumberBetween(1.0 - kBackoffRandMult, 1.0); return std::max(first_term + second_term, min_delay); } }
#include "tsl/platform/retrying_utils.h" #include <cmath> #include <fstream> #include "absl/time/time.h" #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/str_util.h" #include "tsl/platform/test.h" namespace tsl { namespace { TEST(RetryingUtilsTest, CallWithRetries_RetryDelays) { std::vector<double> requested_delays; std::function<void(int64_t)> sleep = [&requested_delays](int64_t delay) { requested_delays.emplace_back(delay / 1000000.0); }; std::function<absl::Status()> f = []() { return errors::Unavailable("Failed."); }; const auto& status = RetryingUtils::CallWithRetries( f, sleep, RetryConfig(500000 )); EXPECT_TRUE(errors::IsAborted(status)); EXPECT_TRUE(absl::StrContains( status.message(), "All 10 retry attempts failed. The last failure: Failed.")) << status; EXPECT_EQ(10, requested_delays.size()); EXPECT_NEAR(0.5, requested_delays[0], 1.0); EXPECT_NEAR(1.0, requested_delays[1], 1.0); EXPECT_NEAR(2.0, requested_delays[2], 1.0); EXPECT_NEAR(4.0, requested_delays[3], 1.0); EXPECT_NEAR(8.0, requested_delays[4], 1.0); EXPECT_NEAR(16.0, requested_delays[5], 1.0); EXPECT_NEAR(32.0, requested_delays[6], 1.0); EXPECT_NEAR(32.0, requested_delays[7], 1.0); EXPECT_NEAR(32.0, requested_delays[8], 1.0); EXPECT_NEAR(32.0, requested_delays[9], 1.0); } TEST(RetryingUtilsTest, CallWithRetries_NotFoundIsNotRetried) { std::vector<absl::Status> results( {errors::Unavailable("Failed."), errors::NotFound("Not found.")}); std::function<absl::Status()> f = [&results]() { auto result = results[0]; results.erase(results.begin()); return result; }; EXPECT_TRUE(errors::IsNotFound(RetryingUtils::CallWithRetries( f, RetryConfig(0 )))); } TEST(RetryingUtilsTest, CallWithRetries_ImmediateSuccess) { std::vector<absl::Status> results({absl::OkStatus()}); std::function<void(int64_t)> sleep = [](int64_t delay) { ADD_FAILURE() << "Unexpected call to sleep."; }; std::function<absl::Status()> f = [&results]() { auto result = results[0]; results.erase(results.begin()); return result; }; TF_EXPECT_OK(RetryingUtils::CallWithRetries( f, sleep, RetryConfig(1L ))); } TEST(RetryingUtilsTest, CallWithRetries_EventualSuccess) { std::vector<absl::Status> results({errors::Unavailable("Failed."), errors::Unavailable("Failed again."), absl::OkStatus()}); std::function<absl::Status()> f = [&results]() { auto result = results[0]; results.erase(results.begin()); return result; }; TF_EXPECT_OK(RetryingUtils::CallWithRetries( f, RetryConfig(0 ))); } TEST(RetryingUtilsTest, DeleteWithRetries_ImmediateSuccess) { std::vector<absl::Status> delete_results({absl::OkStatus()}); const auto delete_func = [&delete_results]() { auto result = delete_results[0]; delete_results.erase(delete_results.begin()); return result; }; TF_EXPECT_OK(RetryingUtils::DeleteWithRetries( delete_func, RetryConfig(0 ))); } TEST(RetryingUtilsTest, DeleteWithRetries_EventualSuccess) { std::vector<absl::Status> delete_results( {errors::Unavailable(""), absl::OkStatus()}); const auto delete_func = [&delete_results]() { auto result = delete_results[0]; delete_results.erase(delete_results.begin()); return result; }; TF_EXPECT_OK(RetryingUtils::DeleteWithRetries( delete_func, RetryConfig(0 ))); } TEST(RetryingUtilsTest, DeleteWithRetries_PermissionDeniedNotRetried) { std::vector<absl::Status> delete_results( {errors::Unavailable(""), errors::PermissionDenied("")}); const auto delete_func = [&delete_results]() { auto result = delete_results[0]; delete_results.erase(delete_results.begin()); return result; }; EXPECT_TRUE(errors::IsPermissionDenied(RetryingUtils::DeleteWithRetries( delete_func, RetryConfig(0 )))); } TEST(RetryingUtilsTest, DeleteWithRetries_SuccessThroughFileNotFound) { std::vector<absl::Status> delete_results( {errors::Unavailable(""), errors::NotFound("")}); const auto delete_func = [&delete_results]() { auto result = delete_results[0]; delete_results.erase(delete_results.begin()); return result; }; TF_EXPECT_OK(RetryingUtils::DeleteWithRetries( delete_func, RetryConfig(0 ))); } TEST(RetryingUtilsTest, DeleteWithRetries_FirstNotFoundReturnedAsIs) { std::vector<absl::Status> delete_results({errors::NotFound("")}); const auto delete_func = [&delete_results]() { auto result = delete_results[0]; delete_results.erase(delete_results.begin()); return result; }; EXPECT_EQ(error::NOT_FOUND, RetryingUtils::DeleteWithRetries( delete_func, RetryConfig(0 )) .code()); } TEST(RetryingUtilsTest, ComputeRetryBackoff) { for (int i = 0; i < 30; ++i) { EXPECT_LE(0.4 * absl::Milliseconds(1) + 0.6 * absl::Milliseconds(1) * std::pow(1.3, i), ComputeRetryBackoff(i)); EXPECT_LE( ComputeRetryBackoff(i), 0.4 * absl::Milliseconds(1) + absl::Milliseconds(1) * std::pow(1.3, i)); } } TEST(RetryingUtilsTest, ComputeRetryBackoff_MinMaxDelays) { for (int i = 0; i < 30; ++i) { EXPECT_EQ(ComputeRetryBackoff(i, absl::Seconds(10)), absl::Seconds(10)); EXPECT_EQ(ComputeRetryBackoff(i, absl::Microseconds(1), absl::Microseconds(1)), absl::Microseconds(1)); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/retrying_utils.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/retrying_utils_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
ade33ad4-1708-4f0a-a0ca-5ac3d17384c5
cpp
google/tsl
cpu_utils
tsl/platform/profile_utils/cpu_utils.cc
tsl/platform/profile_utils/cpu_utils_test.cc
#include "tsl/platform/profile_utils/cpu_utils.h" #include <fstream> #include <limits> #include <mutex> #if defined(_WIN32) #include <windows.h> #endif #if defined(__APPLE__) #include <sys/sysctl.h> #endif #include "absl/base/call_once.h" #include "tsl/platform/logging.h" #include "tsl/platform/profile_utils/android_armv7a_cpu_utils_helper.h" namespace tsl { namespace profile_utils { constexpr int64_t CpuUtils::INVALID_FREQUENCY; static ICpuUtilsHelper* cpu_utils_helper_instance_ = nullptr; #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ (defined(__s390x__)) uint64 CpuUtils::GetCycleCounterFrequency() { static const uint64 cpu_frequency = GetCycleCounterFrequencyImpl(); return cpu_frequency; } #else int64_t CpuUtils::GetCycleCounterFrequency() { static const int64_t cpu_frequency = GetCycleCounterFrequencyImpl(); return cpu_frequency; } #endif double CpuUtils::GetMicroSecPerClock() { static const double micro_sec_per_clock = (1000.0 * 1000.0) / static_cast<double>(GetCycleCounterFrequency()); return micro_sec_per_clock; } void CpuUtils::ResetClockCycle() { GetCpuUtilsHelperSingletonInstance().ResetClockCycle(); } void CpuUtils::EnableClockCycleProfiling() { GetCpuUtilsHelperSingletonInstance().EnableClockCycleProfiling(); } void CpuUtils::DisableClockCycleProfiling() { GetCpuUtilsHelperSingletonInstance().DisableClockCycleProfiling(); } std::chrono::duration<double> CpuUtils::ConvertClockCycleToTime( const int64_t clock_cycle) { return std::chrono::duration<double>(static_cast<double>(clock_cycle) / GetCycleCounterFrequency()); } int64_t CpuUtils::GetCycleCounterFrequencyImpl() { #if defined(__ANDROID__) return GetCpuUtilsHelperSingletonInstance().CalculateCpuFrequency(); #elif defined(__linux__) std::ifstream cpuinfo("/proc/cpuinfo"); if (!cpuinfo) { LOG(WARNING) << "Failed to open /proc/cpuinfo"; return INVALID_FREQUENCY; } string line; while (std::getline(cpuinfo, line)) { double cpu_freq = 0.0; int retval = 0; double freq_factor = 2.0; #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) retval = sscanf(line.c_str(), "clock : %lfMHz", &cpu_freq); freq_factor = 1.0; #elif defined(__s390x__) retval = sscanf(line.c_str(), "bogomips per cpu: %lf", &cpu_freq); #elif defined(__aarch64__) retval = sscanf(line.c_str(), "BogoMIPS : %lf", &cpu_freq); #else retval = sscanf(line.c_str(), "bogomips : %lf", &cpu_freq); #endif if (retval > 0) { const double freq_ghz = cpu_freq / 1000.0 / freq_factor; if (retval != 1 || freq_ghz < 0.01) { LOG(WARNING) << "Failed to get CPU frequency: " << freq_ghz << " GHz"; return INVALID_FREQUENCY; } const int64_t freq_n = static_cast<int64_t>(freq_ghz * 1000.0 * 1000.0 * 1000.0); VLOG(1) << "CPU Frequency: " << freq_n << " Hz"; return freq_n; } } LOG(WARNING) << "Failed to find bogomips or clock in /proc/cpuinfo; cannot determine " "CPU frequency"; return INVALID_FREQUENCY; #elif defined(__APPLE__) int64_t freq_hz = 0; size_t freq_hz_size = sizeof(freq_hz); int retval = sysctlbyname("hw.cpufrequency_max", &freq_hz, &freq_hz_size, NULL, 0); if (retval != 0 || freq_hz < 1e6) { int64_t tbfrequency = 0; size_t tbfrequency_size = sizeof(tbfrequency); retval = sysctlbyname("hw.tbfrequency", &tbfrequency, &tbfrequency_size, NULL, 0); if (retval == 0) { clockinfo clock_info; size_t clock_info_size = sizeof(clock_info); retval = sysctlbyname("kern.clockrate", &clock_info, &clock_info_size, NULL, 0); if (retval == 0) { freq_hz = clock_info.hz * tbfrequency; } } if (retval != 0 || freq_hz < 1e6) { LOG(WARNING) << "Failed to get CPU frequency: " << freq_hz << " Hz"; return INVALID_FREQUENCY; } } return freq_hz; #elif defined(_WIN32) LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); return freq.QuadPart; #else return INVALID_FREQUENCY; #endif } ICpuUtilsHelper& CpuUtils::GetCpuUtilsHelperSingletonInstance() { static absl::once_flag flag; absl::call_once(flag, []() { if (cpu_utils_helper_instance_ != nullptr) { LOG(FATAL) << "cpu_utils_helper_instance_ is already instantiated."; } #if defined(__ANDROID__) && (__ANDROID_API__ >= 21) && \ (defined(__ARM_ARCH_7A__) || defined(__aarch64__)) cpu_utils_helper_instance_ = new AndroidArmV7ACpuUtilsHelper(); #else cpu_utils_helper_instance_ = new DefaultCpuUtilsHelper(); #endif }); return *cpu_utils_helper_instance_; } } }
#include "tsl/platform/profile_utils/cpu_utils.h" #include "tsl/platform/logging.h" #include "tsl/platform/profile_utils/clock_cycle_profiler.h" #include "tsl/platform/test.h" namespace tsl { namespace profile_utils { static constexpr bool DBG = false; class CpuUtilsTest : public ::testing::Test { protected: void SetUp() override { CpuUtils::EnableClockCycleProfiling(); } }; TEST_F(CpuUtilsTest, SetUpTestCase) {} TEST_F(CpuUtilsTest, TearDownTestCase) {} TEST_F(CpuUtilsTest, CheckGetCurrentClockCycle) { static constexpr int LOOP_COUNT = 10; const uint64 start_clock_count = CpuUtils::GetCurrentClockCycle(); CHECK_GT(start_clock_count, 0); uint64 prev_clock_count = start_clock_count; for (int i = 0; i < LOOP_COUNT; ++i) { const uint64 clock_count = CpuUtils::GetCurrentClockCycle(); CHECK_GE(clock_count, prev_clock_count); prev_clock_count = clock_count; } const uint64 end_clock_count = CpuUtils::GetCurrentClockCycle(); if (DBG) { LOG(INFO) << "start clock = " << start_clock_count; LOG(INFO) << "end clock = " << end_clock_count; LOG(INFO) << "average clock = " << ((end_clock_count - start_clock_count) / LOOP_COUNT); } } TEST_F(CpuUtilsTest, CheckCycleCounterFrequency) { #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ (defined(__s390x__)) const uint64 cpu_frequency = CpuUtils::GetCycleCounterFrequency(); CHECK_GT(cpu_frequency, 0); CHECK_NE(cpu_frequency, unsigned(CpuUtils::INVALID_FREQUENCY)); #else const int64_t cpu_frequency = CpuUtils::GetCycleCounterFrequency(); CHECK_GT(cpu_frequency, 0); CHECK_NE(cpu_frequency, CpuUtils::INVALID_FREQUENCY); #endif if (DBG) { LOG(INFO) << "Cpu frequency = " << cpu_frequency; } } TEST_F(CpuUtilsTest, CheckMicroSecPerClock) { const double micro_sec_per_clock = CpuUtils::GetMicroSecPerClock(); CHECK_GT(micro_sec_per_clock, 0.0); if (DBG) { LOG(INFO) << "Micro sec per clock = " << micro_sec_per_clock; } } TEST_F(CpuUtilsTest, SimpleUsageOfClockCycleProfiler) { static constexpr int LOOP_COUNT = 10; ClockCycleProfiler prof; for (int i = 0; i < LOOP_COUNT; ++i) { prof.Start(); prof.Stop(); } EXPECT_EQ(LOOP_COUNT, static_cast<int>(prof.GetCount() + 0.5)); if (DBG) { prof.DumpStatistics("CpuUtilsTest"); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/profile_utils/cpu_utils.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/profile_utils/cpu_utils_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
00590ed8-bc69-40a8-87ea-2346409383fe
cpp
google/tsl
stacktrace_handler
tsl/platform/windows/stacktrace_handler.cc
tsl/platform/stacktrace_handler_test.cc
#include "tsl/platform/stacktrace_handler.h" #include <windows.h> #include <dbghelp.h> #include <errno.h> #include <io.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <thread> #include "tsl/platform/mutex.h" #include "tsl/platform/stacktrace.h" #include "tsl/platform/types.h" namespace tsl { static mutex alarm_mu(LINKER_INITIALIZED); static bool alarm_activated = false; static void AlarmThreadBody() { alarm_mu.lock(); alarm_mu.Await(Condition(&alarm_activated)); alarm_mu.unlock(); Sleep(60000); signal(SIGABRT, SIG_DFL); abort(); } static bool PtrToString(uintptr_t ptr, char* buf, size_t size) { static constexpr char kHexCharacters[] = "0123456789abcdef"; static constexpr int kHexBase = 16; size_t num_hex_chars = 2 * sizeof(uintptr_t); if (size < (num_hex_chars + 4)) { return false; } buf[0] = '0'; buf[1] = 'x'; int start_index = 2; for (int i = num_hex_chars - 1 + start_index; i >= start_index; --i) { buf[i] = kHexCharacters[ptr % kHexBase]; ptr /= kHexBase; } int current_index = start_index + num_hex_chars; buf[current_index] = '\n'; buf[current_index + 1] = '\0'; return true; } static inline void SafePrintStackTracePointers() { static constexpr char begin_msg[] = "*** BEGIN STACK TRACE POINTERS ***\n"; (void)_write(_fileno(stderr), begin_msg, strlen(begin_msg)); static constexpr int kMaxStackFrames = 64; void* trace[kMaxStackFrames]; int num_frames = CaptureStackBackTrace(0, kMaxStackFrames, trace, NULL); for (int i = 0; i < num_frames; ++i) { char buffer[32] = "unsuccessful ptr conversion"; PtrToString(reinterpret_cast<uintptr_t>(trace[i]), buffer, sizeof(buffer)); (void)_write(_fileno(stderr), buffer, strlen(buffer)); } static constexpr char end_msg[] = "*** END STACK TRACE POINTERS ***\n\n"; (void)_write(_fileno(stderr), end_msg, strlen(end_msg)); } static void StacktraceHandler(int sig) { alarm_mu.lock(); alarm_activated = true; alarm_mu.unlock(); char buf[128]; snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig); (void)write(_fileno(stderr), buf, strlen(buf)); SafePrintStackTracePointers(); std::string stacktrace = CurrentStackTrace(); (void)write(_fileno(stderr), stacktrace.c_str(), stacktrace.length()); signal(SIGABRT, SIG_DFL); abort(); } namespace testing { void InstallStacktraceHandler() { int handled_signals[] = {SIGSEGV, SIGABRT, SIGILL, SIGFPE}; std::thread alarm_thread(AlarmThreadBody); alarm_thread.detach(); typedef void (*SignalHandlerPointer)(int); for (int sig : handled_signals) { SignalHandlerPointer previousHandler = signal(sig, StacktraceHandler); if (previousHandler == SIG_ERR) { char buf[128]; snprintf(buf, sizeof(buf), "tensorflow::InstallStackTraceHandler: Warning, can't install " "backtrace signal handler for signal %d, errno:%d \n", sig, errno); (void)write(_fileno(stderr), buf, strlen(buf)); } else if (previousHandler != SIG_DFL) { char buf[128]; snprintf(buf, sizeof(buf), "tensorflow::InstallStackTraceHandler: Warning, backtrace " "signal handler for signal %d overwrote previous handler.\n", sig); (void)write(_fileno(stderr), buf, strlen(buf)); } } } } }
#include <csignal> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace { TEST(StacktraceHandlerTest, GeneratesStacktrace) { EXPECT_DEATH(raise(SIGABRT), "testing::internal::UnitTestImpl::RunAllTests"); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/windows/stacktrace_handler.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/stacktrace_handler_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
c092720c-f1ac-4480-8438-947c924d26ed
cpp
google/tsl
mutex
tsl/platform/default/mutex.cc
tsl/platform/mutex_test.cc
#include "tsl/platform/mutex.h" #include <time.h> #include <cstdint> #include "nsync_cv.h" #include "nsync_mu.h" #include "nsync_mu_wait.h" #include "nsync_time.h" namespace tsl { static_assert(sizeof(nsync::nsync_mu) <= sizeof(internal::MuData), "tsl::internal::MuData needs to be bigger"); static inline nsync::nsync_mu *mu_cast(internal::MuData *mu) { return reinterpret_cast<nsync::nsync_mu *>(mu); } static inline const nsync::nsync_mu *mu_cast(const internal::MuData *mu) { return reinterpret_cast<const nsync::nsync_mu *>(mu); } mutex::mutex() { nsync::nsync_mu_init(mu_cast(&mu_)); } void mutex::lock() { nsync::nsync_mu_lock(mu_cast(&mu_)); } bool mutex::try_lock() { return nsync::nsync_mu_trylock(mu_cast(&mu_)) != 0; }; void mutex::unlock() { nsync::nsync_mu_unlock(mu_cast(&mu_)); } void mutex::assert_held() const TF_ASSERT_EXCLUSIVE_LOCK() { nsync::nsync_mu_assert_held(mu_cast(&mu_)); } void mutex::lock_shared() { nsync::nsync_mu_rlock(mu_cast(&mu_)); } bool mutex::try_lock_shared() { return nsync::nsync_mu_rtrylock(mu_cast(&mu_)) != 0; }; void mutex::unlock_shared() { nsync::nsync_mu_runlock(mu_cast(&mu_)); } void mutex::assert_held_shared() const TF_ASSERT_SHARED_LOCK() { nsync::nsync_mu_rassert_held(mu_cast(&mu_)); } static int EvaluateCondition(const void *vcond) { return static_cast<int>(static_cast<const Condition *>(vcond)->Eval()); } void mutex::Await(const Condition &cond) { nsync::nsync_mu_wait(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr); } bool mutex::AwaitWithDeadline(const Condition &cond, uint64_t abs_deadline_ns) { time_t seconds = abs_deadline_ns / (1000 * 1000 * 1000); nsync::nsync_time abs_time = nsync::nsync_time_s_ns( seconds, abs_deadline_ns - seconds * (1000 * 1000 * 1000)); return nsync::nsync_mu_wait_with_deadline(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr, abs_time, nullptr) == 0; } static_assert(sizeof(nsync::nsync_cv) <= sizeof(internal::CVData), "tsl::internal::CVData needs to be bigger"); static inline nsync::nsync_cv *cv_cast(internal::CVData *cv) { return reinterpret_cast<nsync::nsync_cv *>(cv); } condition_variable::condition_variable() { nsync::nsync_cv_init(cv_cast(&cv_)); } void condition_variable::wait(mutex_lock &lock) { nsync::nsync_cv_wait(cv_cast(&cv_), mu_cast(&lock.mutex()->mu_)); } void condition_variable::notify_one() { nsync::nsync_cv_signal(cv_cast(&cv_)); } void condition_variable::notify_all() { nsync::nsync_cv_broadcast(cv_cast(&cv_)); } namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time) { int r = nsync::nsync_cv_wait_with_deadline(cv_cast(cv_data), mu_cast(mu_data), timeout_time, nullptr); return r ? std::cv_status::timeout : std::cv_status::no_timeout; } } }
#include "tsl/platform/mutex.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl { namespace { class MutexTest : public ::testing::Test { protected: mutex_lock GetLock() TF_NO_THREAD_SAFETY_ANALYSIS { return mutex_lock{mu_}; } tf_shared_lock GetSharedLock() TF_NO_THREAD_SAFETY_ANALYSIS { return tf_shared_lock{mu_}; } bool test_try_lock() { bool test = mu_.try_lock(); if (test) mu_.unlock(); return test; } bool test_try_lock_shared() { bool test = mu_.try_lock_shared(); if (test) mu_.unlock_shared(); return test; } mutex mu_; }; TEST_F(MutexTest, MovableMutexLockTest) { EXPECT_TRUE(test_try_lock()); { mutex_lock lock = GetLock(); EXPECT_FALSE(test_try_lock()); EXPECT_FALSE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST_F(MutexTest, SharedMutexLockTest) { EXPECT_TRUE(test_try_lock()); { tf_shared_lock lock = GetSharedLock(); EXPECT_FALSE(test_try_lock()); EXPECT_TRUE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST(ConditionVariableTest, WaitWithPredicate) { constexpr int kNumThreads = 4; mutex mu; condition_variable cv; bool ready = false; int count = 0; tsl::thread::ThreadPool pool(Env::Default(), "condition_variable_test_wait_with_predicate", kNumThreads); for (int i = 0; i < kNumThreads; ++i) { pool.Schedule([&mu, &cv, &ready, &count]() { mutex_lock lock(mu); cv.wait(lock, [&ready] { return ready; }); ++count; cv.notify_one(); }); } { mutex_lock lock(mu); EXPECT_EQ(count, 0); } { mutex_lock lock(mu); ready = true; cv.notify_all(); } { mutex_lock lock(mu); cv.wait(lock, [&count, kNumThreads] { return count == kNumThreads; }); EXPECT_EQ(count, kNumThreads); } } TEST(ConditionVariableTest, WaitWithTruePredicateDoesntBlock) { mutex mu; mutex_lock lock(mu); condition_variable cv; cv.wait(lock, [] { return true; }); EXPECT_TRUE(static_cast<bool>(lock)); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/default/mutex.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/mutex_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
4c91f456-30fe-4b85-b73d-18b1e8481568
cpp
google/tsl
unbounded_work_queue
tsl/platform/default/unbounded_work_queue.cc
tsl/platform/unbounded_work_queue_test.cc
#include "tsl/platform/default/unbounded_work_queue.h" #include "absl/memory/memory.h" #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/numa.h" namespace tsl { UnboundedWorkQueue::UnboundedWorkQueue(Env* env, const string& thread_name, const ThreadOptions& thread_options) : env_(env), thread_name_(thread_name), thread_options_(thread_options) {} UnboundedWorkQueue::~UnboundedWorkQueue() { { mutex_lock l(work_queue_mu_); cancelled_ = true; work_queue_cv_.notify_all(); if (!work_queue_.empty()) { LOG(ERROR) << "UnboundedWorkQueue named \"" << thread_name_ << "\" was " << "deleted with pending work in its queue. This may indicate " << "a potential use-after-free bug."; } } { mutex_lock l(thread_pool_mu_); thread_pool_.clear(); } } void UnboundedWorkQueue::Schedule(WorkFunction fn) { mutex_lock l(work_queue_mu_); work_queue_.push_back(std::move(fn)); work_queue_cv_.notify_one(); if (work_queue_.size() > num_idle_threads_) { Thread* new_thread = env_->StartThread({}, thread_name_, [this]() { PooledThreadFunc(); }); mutex_lock l(thread_pool_mu_); thread_pool_.emplace_back(new_thread); } } void UnboundedWorkQueue::PooledThreadFunc() { if (thread_options_.numa_node != tsl::port::kNUMANoAffinity) { tsl::port::NUMASetThreadNodeAffinity(thread_options_.numa_node); } while (true) { WorkFunction fn; { mutex_lock l(work_queue_mu_); ++num_idle_threads_; while (!cancelled_ && work_queue_.empty()) { work_queue_cv_.wait(l); } if (cancelled_) { return; } fn = std::move(work_queue_.front()); work_queue_.pop_front(); --num_idle_threads_; } fn(); } } }
#include "tsl/platform/unbounded_work_queue.h" #include "absl/memory/memory.h" #include "tsl/platform/random.h" #include "tsl/platform/blocking_counter.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { namespace { class UnboundedWorkQueueTest : public ::testing::Test { protected: UnboundedWorkQueueTest() : work_queue_( absl::make_unique<UnboundedWorkQueue>(Env::Default(), "test")) {} ~UnboundedWorkQueueTest() override = default; void RunMultipleCopiesOfClosure(const int num_closures, std::function<void()> fn) { for (int i = 0; i < num_closures; ++i) { work_queue_->Schedule([this, fn]() { fn(); mutex_lock l(mu_); ++closure_count_; cond_var_.notify_all(); }); } } void BlockUntilClosuresDone(const int num_closures) { mutex_lock l(mu_); while (closure_count_ < num_closures) { cond_var_.wait(l); } } void ResetQueue() { work_queue_.reset(); } int NumClosuresExecuted() { mutex_lock l(mu_); return closure_count_; } private: mutex mu_; int closure_count_ TF_GUARDED_BY(mu_) = 0; condition_variable cond_var_; std::unique_ptr<UnboundedWorkQueue> work_queue_; }; TEST_F(UnboundedWorkQueueTest, SingleClosure) { constexpr int num_closures = 1; RunMultipleCopiesOfClosure(num_closures, []() {}); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, MultipleClosures) { constexpr int num_closures = 10; RunMultipleCopiesOfClosure(num_closures, []() {}); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, MultipleClosuresSleepingRandomly) { constexpr int num_closures = 1000; RunMultipleCopiesOfClosure(num_closures, []() { Env::Default()->SleepForMicroseconds(random::New64() % 10); }); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, NestedClosures) { constexpr int num_closures = 10; RunMultipleCopiesOfClosure(num_closures, [=]() { RunMultipleCopiesOfClosure(num_closures, []() {}); }); BlockUntilClosuresDone(num_closures * num_closures + num_closures); } TEST_F(UnboundedWorkQueueTest, RacyDestructor) { constexpr int num_closures = 100; RunMultipleCopiesOfClosure(num_closures, []() {}); ResetQueue(); EXPECT_LE(NumClosuresExecuted(), num_closures); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/default/unbounded_work_queue.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/unbounded_work_queue_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
58056da0-f00e-4ef5-be82-e5fd1ed26ade
cpp
google/tsl
subprocess
tsl/platform/windows/subprocess.cc
tsl/platform/subprocess_test.cc
#include "tsl/platform/subprocess.h" #include <io.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <windows.h> #include <vector> #include "tsl/platform/logging.h" #include "tsl/platform/strcat.h" #define PIPE_BUF_SIZE 4096 namespace tsl { namespace { static bool IsProcessFinished(HANDLE h) { DWORD process_return_code = STILL_ACTIVE; GetExitCodeProcess(h, &process_return_code); return process_return_code != STILL_ACTIVE; } struct ThreadData { string* iobuf; HANDLE iohandle; }; DWORD WINAPI InputThreadFunction(LPVOID param) { ThreadData* args = reinterpret_cast<ThreadData*>(param); string* input = args->iobuf; HANDLE in_handle = args->iohandle; size_t buffer_pointer = 0; size_t total_bytes_written = 0; bool ok = true; while (ok && total_bytes_written < input->size()) { DWORD bytes_written_this_time; ok = WriteFile(in_handle, input->data() + total_bytes_written, input->size() - total_bytes_written, &bytes_written_this_time, nullptr); total_bytes_written += bytes_written_this_time; } CloseHandle(in_handle); if (!ok) { return GetLastError(); } else { return 0; } } DWORD WINAPI OutputThreadFunction(LPVOID param) { ThreadData* args = reinterpret_cast<ThreadData*>(param); string* output = args->iobuf; HANDLE out_handle = args->iohandle; char buf[PIPE_BUF_SIZE]; DWORD bytes_read; bool wait_result = WaitForSingleObject(out_handle, INFINITE); if (wait_result != WAIT_OBJECT_0) { LOG(FATAL) << "WaitForSingleObject on child process output failed. " "Error code: " << wait_result; } while (ReadFile(out_handle, buf, sizeof(buf), &bytes_read, nullptr) && bytes_read > 0) { output->append(buf, bytes_read); } CloseHandle(out_handle); return 0; } } SubProcess::SubProcess(int nfds) : running_(false), win_pi_(nullptr), exec_path_(nullptr), exec_argv_(nullptr) { for (int i = 0; i < kNFds; i++) { action_[i] = ACTION_CLOSE; parent_pipe_[i] = nullptr; } } SubProcess::~SubProcess() { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (win_pi_) { auto* pi = reinterpret_cast<PROCESS_INFORMATION*>(win_pi_); CloseHandle(pi->hProcess); CloseHandle(pi->hThread); delete pi; win_pi_ = nullptr; } running_ = false; FreeArgs(); ClosePipes(); } void SubProcess::FreeArgs() { free(exec_path_); exec_path_ = nullptr; if (exec_argv_) { for (int i = 0; exec_argv_[i]; i++) { free(exec_argv_[i]); } delete[] exec_argv_; exec_argv_ = nullptr; } } void SubProcess::ClosePipes() { for (int i = 0; i < kNFds; i++) { if (parent_pipe_[i] != nullptr) { CloseHandle(parent_pipe_[i]); parent_pipe_[i] = nullptr; } } } void SubProcess::SetProgram(const string& file, const std::vector<string>& argv) { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(FATAL) << "SetProgram called after the process was started."; return; } FreeArgs(); exec_path_ = _strdup(file.c_str()); if (exec_path_ == nullptr) { LOG(FATAL) << "SetProgram failed to allocate file string."; return; } int argc = argv.size(); exec_argv_ = new char*[argc + 1]; for (int i = 0; i < argc; i++) { exec_argv_[i] = _strdup(argv[i].c_str()); if (exec_argv_[i] == nullptr) { LOG(FATAL) << "SetProgram failed to allocate command argument."; return; } } exec_argv_[argc] = nullptr; } void SubProcess::SetChannelAction(Channel chan, ChannelAction action) { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(FATAL) << "SetChannelAction called after the process was started."; } else if (!chan_valid(chan)) { LOG(FATAL) << "SetChannelAction called with invalid channel: " << chan; } else if ((action != ACTION_CLOSE) && (action != ACTION_PIPE) && (action != ACTION_DUPPARENT)) { LOG(FATAL) << "SetChannelAction called with invalid action: " << action; } else { action_[chan] = action; } } bool SubProcess::Start() { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(ERROR) << "Start called after the process was started."; return false; } if ((exec_path_ == nullptr) || (exec_argv_ == nullptr)) { LOG(ERROR) << "Start called without setting a program."; return false; } SECURITY_ATTRIBUTES attrs; attrs.nLength = sizeof(SECURITY_ATTRIBUTES); attrs.bInheritHandle = TRUE; attrs.lpSecurityDescriptor = nullptr; HANDLE child_pipe_[kNFds] TF_GUARDED_BY(data_mu_); for (int i = 0; i < kNFds; i++) { if (action_[i] == ACTION_PIPE) { if (!CreatePipe(i == CHAN_STDIN ? child_pipe_ + i : parent_pipe_ + i, i == CHAN_STDIN ? parent_pipe_ + i : child_pipe_ + i, &attrs, PIPE_BUF_SIZE)) { LOG(ERROR) << "Cannot create pipe. Error code: " << GetLastError(); ClosePipes(); return false; } if (!SetHandleInformation(parent_pipe_[i], HANDLE_FLAG_INHERIT, 0)) { LOG(ERROR) << "Cannot set pipe handle attributes."; ClosePipes(); return false; } } else if (action_[i] == ACTION_DUPPARENT) { if (i == CHAN_STDIN) { child_pipe_[i] = GetStdHandle(STD_INPUT_HANDLE); } else if (i == CHAN_STDOUT) { child_pipe_[i] = GetStdHandle(STD_OUTPUT_HANDLE); } else { child_pipe_[i] = GetStdHandle(STD_ERROR_HANDLE); } } else { parent_pipe_[i] = nullptr; child_pipe_[i] = nullptr; } } string command_line = strings::StrCat("\"", exec_path_, "\""); for (int i = 1; exec_argv_[i]; i++) { command_line.append(strings::StrCat(" \"", exec_argv_[i], "\"")); } STARTUPINFOA si; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.dwFlags |= STARTF_USESTDHANDLES; if (child_pipe_[CHAN_STDIN]) { si.hStdInput = child_pipe_[CHAN_STDIN]; } if (child_pipe_[CHAN_STDOUT]) { si.hStdOutput = child_pipe_[CHAN_STDOUT]; } if (child_pipe_[CHAN_STDERR]) { si.hStdError = child_pipe_[CHAN_STDERR]; } win_pi_ = new PROCESS_INFORMATION; bool bSuccess = CreateProcessA(nullptr, const_cast<char*>(command_line.c_str()), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)); if (bSuccess) { for (int i = 0; i < kNFds; i++) { if (child_pipe_[i] != nullptr) { CloseHandle(child_pipe_[i]); child_pipe_[i] = nullptr; } } running_ = true; return true; } else { LOG(ERROR) << "Call to CreateProcess failed. Error code: " << GetLastError() << ", command: '" << command_line << "'"; ClosePipes(); return false; } } bool SubProcess::Wait() { int status; return WaitInternal(&status); } bool SubProcess::WaitInternal(int* status) { proc_mu_.lock(); bool running = running_; PROCESS_INFORMATION pi_ = *reinterpret_cast<PROCESS_INFORMATION*>(win_pi_); proc_mu_.unlock(); bool ret = false; if (running && pi_.hProcess) { DWORD wait_status = WaitForSingleObject(pi_.hProcess, INFINITE); if (wait_status == WAIT_OBJECT_0) { DWORD process_exit_code = 0; if (GetExitCodeProcess(pi_.hProcess, &process_exit_code)) { *status = static_cast<int>(process_exit_code); } else { LOG(FATAL) << "Wait failed with code: " << GetLastError(); } } else { LOG(FATAL) << "WaitForSingleObject call on the process handle failed. " "Error code: " << wait_status; } } proc_mu_.lock(); if ((running_ == running) && (pi_.hProcess == reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)->hProcess)) { running_ = false; CloseHandle(reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)->hProcess); CloseHandle(reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)->hThread); reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)->hProcess = nullptr; reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)->hThread = nullptr; } proc_mu_.unlock(); return *status == 0; } bool SubProcess::Kill(int unused_signal) { proc_mu_.lock(); bool running = running_; PROCESS_INFORMATION pi_ = *reinterpret_cast<PROCESS_INFORMATION*>(win_pi_); proc_mu_.unlock(); bool ret = false; if (running && pi_.hProcess) { ret = TerminateProcess(pi_.hProcess, 0); } return ret; } int SubProcess::Communicate(const string* stdin_input, string* stdout_output, string* stderr_output) { proc_mu_.lock(); bool running = running_; proc_mu_.unlock(); if (!running) { LOG(ERROR) << "Communicate called without a running process."; return 1; } HANDLE thread_handles[kNFds]; int thread_count = 0; ThreadData thread_params[kNFds]; data_mu_.lock(); proc_mu_.lock(); bool process_finished = IsProcessFinished( reinterpret_cast<PROCESS_INFORMATION*>(win_pi_)->hProcess); proc_mu_.unlock(); if (!process_finished || (parent_pipe_[CHAN_STDOUT] != nullptr) || (parent_pipe_[CHAN_STDERR] != nullptr)) { if (parent_pipe_[CHAN_STDIN] != nullptr) { if (stdin_input) { thread_params[thread_count].iobuf = const_cast<string*>(stdin_input); thread_params[thread_count].iohandle = parent_pipe_[CHAN_STDIN]; parent_pipe_[CHAN_STDIN] = nullptr; thread_handles[thread_count] = CreateThread(NULL, 0, InputThreadFunction, thread_params + thread_count, 0, NULL); thread_count++; } } else { CloseHandle(parent_pipe_[CHAN_STDIN]); parent_pipe_[CHAN_STDIN] = NULL; } if (parent_pipe_[CHAN_STDOUT] != nullptr) { if (stdout_output != nullptr) { thread_params[thread_count].iobuf = stdout_output; thread_params[thread_count].iohandle = parent_pipe_[CHAN_STDOUT]; parent_pipe_[CHAN_STDOUT] = NULL; thread_handles[thread_count] = CreateThread(NULL, 0, OutputThreadFunction, thread_params + thread_count, 0, NULL); thread_count++; } else { CloseHandle(parent_pipe_[CHAN_STDOUT]); parent_pipe_[CHAN_STDOUT] = nullptr; } } if (parent_pipe_[CHAN_STDERR] != nullptr) { if (stderr_output != nullptr) { thread_params[thread_count].iobuf = stderr_output; thread_params[thread_count].iohandle = parent_pipe_[CHAN_STDERR]; parent_pipe_[CHAN_STDERR] = NULL; thread_handles[thread_count] = CreateThread(NULL, 0, OutputThreadFunction, thread_params + thread_count, 0, NULL); thread_count++; } else { CloseHandle(parent_pipe_[CHAN_STDERR]); parent_pipe_[CHAN_STDERR] = nullptr; } } } if (thread_count > 0) { DWORD wait_result = WaitForMultipleObjects(thread_count, thread_handles, true, INFINITE); if (wait_result != WAIT_OBJECT_0) { LOG(ERROR) << "Waiting on the io threads failed! result: " << wait_result << std::endl; data_mu_.unlock(); return -1; } for (int i = 0; i < thread_count; i++) { DWORD exit_code; if (GetExitCodeThread(thread_handles[i], &exit_code)) { if (exit_code) { LOG(ERROR) << "One of the IO threads failed with code: " << exit_code; } } else { LOG(ERROR) << "Error checking io thread exit statuses. Error Code: " << GetLastError(); } } } data_mu_.unlock(); int status; return WaitInternal(&status) ? status : -1; } std::unique_ptr<SubProcess> CreateSubProcess(const std::vector<string>& argv) { std::unique_ptr<SubProcess> proc(new SubProcess()); proc->SetProgram(argv[0], argv); proc->SetChannelAction(CHAN_STDERR, ACTION_DUPPARENT); proc->SetChannelAction(CHAN_STDOUT, ACTION_DUPPARENT); return proc; } }
#include "tsl/platform/subprocess.h" #include <stdlib.h> #include <algorithm> #include <string> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/path.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" #ifdef PLATFORM_WINDOWS #define WIFEXITED(code) ((code) != 3) #define WEXITSTATUS(code) (code) #define SIGKILL 9 #else #include <sys/wait.h> #endif namespace tsl { namespace { string EchoProgram() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_echo"); return tsl::io::AppendDotExeIfWindows(path); } string EchoArgv1Program() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_echo_argv_1"); return tsl::io::AppendDotExeIfWindows(path); } string NoopProgram() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_noop"); return tsl::io::AppendDotExeIfWindows(path); } string StdErrProgram() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_stderr"); return tsl::io::AppendDotExeIfWindows(path); } class SubProcessTest : public ::testing::Test {}; TEST_F(SubProcessTest, NoOutputNoComm) { tsl::SubProcess proc; proc.SetProgram(NoopProgram().c_str(), {NoopProgram()}); EXPECT_TRUE(proc.Start()); EXPECT_TRUE(proc.Wait()); } TEST_F(SubProcessTest, NoOutput) { tsl::SubProcess proc; proc.SetProgram(NoopProgram().c_str(), {NoopProgram()}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string out, err; int status = proc.Communicate(nullptr, &out, &err); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); EXPECT_EQ("", out); EXPECT_EQ("", err); } TEST_F(SubProcessTest, Stdout) { tsl::SubProcess proc; const char test_string[] = "hello_world"; proc.SetProgram(EchoArgv1Program().c_str(), {EchoArgv1Program(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string out, err; int status = proc.Communicate(nullptr, &out, &err); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); EXPECT_EQ(test_string, out); EXPECT_EQ("", err); } TEST_F(SubProcessTest, StdoutIgnored) { tsl::SubProcess proc; const char test_string[] = "hello_world"; proc.SetProgram(EchoArgv1Program().c_str(), {EchoArgv1Program(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); int status = proc.Communicate(nullptr, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, Stderr) { tsl::SubProcess proc; const char test_string[] = "muh_failure!"; proc.SetProgram(StdErrProgram().c_str(), {StdErrProgram(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string out, err; int status = proc.Communicate(nullptr, &out, &err); EXPECT_TRUE(WIFEXITED(status)); EXPECT_NE(0, WEXITSTATUS(status)); EXPECT_EQ("", out); EXPECT_EQ(test_string, err); } TEST_F(SubProcessTest, StderrIgnored) { tsl::SubProcess proc; const char test_string[] = "muh_failure!"; proc.SetProgram(StdErrProgram().c_str(), {StdErrProgram(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); int status = proc.Communicate(nullptr, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_NE(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, Stdin) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in = "foobar\nbarfoo\nhaha\n"; int status = proc.Communicate(&in, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, StdinStdout) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in = "foobar\nbarfoo\nhaha\n"; string out; int status = proc.Communicate(&in, &out, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); out.erase(std::remove(out.begin(), out.end(), '\r'), out.end()); EXPECT_EQ(in, out); } TEST_F(SubProcessTest, StdinChildExit) { tsl::SubProcess proc; proc.SetProgram(NoopProgram().c_str(), {NoopProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in; in.reserve(1000000); for (int i = 0; i < 100000; i++) { in += "hello xyz\n"; } int status = proc.Communicate(&in, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, StdinStdoutOverlap) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in; in.reserve(1000000); for (int i = 0; i < 100000; i++) { in += "hello xyz\n"; } string out; int status = proc.Communicate(&in, &out, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); out.erase(std::remove(out.begin(), out.end(), '\r'), out.end()); EXPECT_EQ(in, out); } TEST_F(SubProcessTest, KillProc) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); EXPECT_TRUE(proc.Start()); EXPECT_TRUE(proc.Kill(SIGKILL)); EXPECT_TRUE(proc.Wait()); EXPECT_FALSE(proc.Kill(SIGKILL)); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/windows/subprocess.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/subprocess_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
d0fc22c9-cb54-45c7-b006-ab38399e6d11
cpp
google/tsl
net
tsl/platform/windows/net.cc
tsl/platform/net_test.cc
#include "tsl/platform/net.h" #include <sys/types.h> #include <winsock2.h> #include <cstdlib> #include <unordered_set> #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/windows/error_windows.h" #undef ERROR namespace tsl { namespace internal { namespace { bool IsPortAvailable(int* port, bool is_tcp) { const int protocol = is_tcp ? IPPROTO_TCP : 0; SOCKET sock = socket(AF_INET, is_tcp ? SOCK_STREAM : SOCK_DGRAM, protocol); struct sockaddr_in addr; int addr_len = static_cast<int>(sizeof(addr)); int actual_port; CHECK_GE(*port, 0); CHECK_LE(*port, 65535); if (sock == INVALID_SOCKET) { LOG(ERROR) << "socket() failed: " << tsl::internal::WindowsWSAGetLastErrorMessage(); return false; } const int one = 1; int result = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&one), sizeof(one)); if (result == SOCKET_ERROR) { LOG(ERROR) << "setsockopt() failed: " << tsl::internal::WindowsWSAGetLastErrorMessage(); closesocket(sock); return false; } addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons((uint16_t)*port); result = bind(sock, (struct sockaddr*)&addr, sizeof(addr)); if (result == SOCKET_ERROR) { LOG(WARNING) << "bind(port=" << *port << ") failed: " << tsl::internal::WindowsWSAGetLastErrorMessage(); closesocket(sock); return false; } result = getsockname(sock, (struct sockaddr*)&addr, &addr_len); if (result == SOCKET_ERROR) { LOG(WARNING) << "getsockname() failed: " << tsl::internal::WindowsWSAGetLastErrorMessage(); closesocket(sock); return false; } CHECK_LE(addr_len, sizeof(addr)); actual_port = ntohs(addr.sin_port); CHECK_GT(actual_port, 0); if (*port == 0) { *port = actual_port; } else { CHECK_EQ(*port, actual_port); } closesocket(sock); return true; } const int kNumRandomPortsToPick = 100; const int kMaximumTrials = 1000; } int PickUnusedPortOrDie() { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR) { LOG(ERROR) << "Error at WSAStartup()"; return false; } static std::unordered_set<int> chosen_ports; bool is_tcp = true; int trial = 0; while (true) { int port; trial++; CHECK_LE(trial, kMaximumTrials) << "Failed to pick an unused port for testing."; if (trial == 1) { port = GetCurrentProcessId() % (65536 - 30000) + 30000; } else if (trial <= kNumRandomPortsToPick) { port = rand() % (65536 - 30000) + 30000; } else { port = 0; } if (chosen_ports.find(port) != chosen_ports.end()) { continue; } if (!IsPortAvailable(&port, is_tcp)) { continue; } CHECK_GT(port, 0); if (!IsPortAvailable(&port, !is_tcp)) { is_tcp = !is_tcp; continue; } chosen_ports.insert(port); WSACleanup(); return port; } return 0; } } }
#include "tsl/platform/net.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace internal { TEST(Net, PickUnusedPortOrDie) { int port0 = PickUnusedPortOrDie(); int port1 = PickUnusedPortOrDie(); CHECK_GE(port0, 0); CHECK_LT(port0, 65536); CHECK_GE(port1, 0); CHECK_LT(port1, 65536); CHECK_NE(port0, port1); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/windows/net.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/net_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
a23aaae1-407d-4963-a762-b9cf7a4b9ced
cpp
google/tsl
port
tsl/platform/windows/port.cc
tsl/platform/port_test.cc
#include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef TF_USE_SNAPPY #include "snappy.h" #endif #include <Windows.h> #include <processthreadsapi.h> #include <shlwapi.h> #include "tsl/platform/cpu_info.h" #include "tsl/platform/demangle.h" #include "tsl/platform/host_info.h" #include "tsl/platform/init_main.h" #include "tsl/platform/logging.h" #include "tsl/platform/mem.h" #include "tsl/platform/numa.h" #include "tsl/platform/snappy.h" #include "tsl/platform/types.h" namespace tsl { namespace port { void InitMain(const char* usage, int* argc, char*** argv) {} string Hostname() { char name[1024]; DWORD name_size = sizeof(name); name[0] = 0; if (::GetComputerNameA(name, &name_size)) { name[name_size] = 0; } return name; } string JobName() { const char* job_name_cs = std::getenv("TF_JOB_NAME"); if (job_name_cs != nullptr) { return string(job_name_cs); } return ""; } int64_t JobUid() { return -1; } int64_t TaskId() { return -1; } IOStatistics GetIOStatistics() { return IOStatistics(); } int NumSchedulableCPUs() { SYSTEM_INFO system_info; GetSystemInfo(&system_info); return system_info.dwNumberOfProcessors; } int MaxParallelism() { return NumSchedulableCPUs(); } int MaxParallelism(int numa_node) { if (numa_node != port::kNUMANoAffinity) { return NumSchedulableCPUs() / port::NUMANumNodes(); } return NumSchedulableCPUs(); } int NumTotalCPUs() { return NumSchedulableCPUs(); } int GetCurrentCPU() { return GetCurrentProcessorNumber(); } bool NUMAEnabled() { return false; } int NUMANumNodes() { return 1; } void NUMASetThreadNodeAffinity(int node) {} int NUMAGetThreadNodeAffinity() { return kNUMANoAffinity; } void* NUMAMalloc(int node, size_t size, int minimum_alignment) { return tsl::port::AlignedMalloc(size, minimum_alignment); } void NUMAFree(void* ptr, size_t size) { tsl::port::Free(ptr); } int NUMAGetMemAffinity(const void* addr) { return kNUMANoAffinity; } bool Snappy_Compress(const char* input, size_t length, string* output) { #ifdef TF_USE_SNAPPY output->resize(snappy::MaxCompressedLength(length)); size_t outlen; snappy::RawCompress(input, length, &(*output)[0], &outlen); output->resize(outlen); return true; #else return false; #endif } bool Snappy_CompressFromIOVec(const struct iovec* iov, size_t uncompressed_length, string* output) { #ifdef TF_USE_SNAPPY output->resize(snappy::MaxCompressedLength(uncompressed_length)); size_t outlen; const snappy::iovec* snappy_iov = reinterpret_cast<const snappy::iovec*>(iov); snappy::RawCompressFromIOVec(snappy_iov, uncompressed_length, &(*output)[0], &outlen); output->resize(outlen); return true; #else return false; #endif } bool Snappy_GetUncompressedLength(const char* input, size_t length, size_t* result) { #ifdef TF_USE_SNAPPY return snappy::GetUncompressedLength(input, length, result); #else return false; #endif } bool Snappy_Uncompress(const char* input, size_t length, char* output) { #ifdef TF_USE_SNAPPY return snappy::RawUncompress(input, length, output); #else return false; #endif } bool Snappy_UncompressToIOVec(const char* compressed, size_t compressed_length, const struct iovec* iov, size_t iov_cnt) { #ifdef TF_USE_SNAPPY const snappy::iovec* snappy_iov = reinterpret_cast<const snappy::iovec*>(iov); return snappy::RawUncompressToIOVec(compressed, compressed_length, snappy_iov, iov_cnt); #else return false; #endif } string Demangle(const char* mangled) { return mangled; } double NominalCPUFrequency() { DWORD data; DWORD data_size = sizeof(data); #pragma comment(lib, "shlwapi.lib") if (SUCCEEDED( SHGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "~MHz", nullptr, &data, &data_size))) { return data * 1e6; } return 1.0; } int NumHyperthreadsPerCore() { static const int ht_per_core = tsl::port::CPUIDNumSMT(); return (ht_per_core > 0) ? ht_per_core : 1; } } } namespace tsl { namespace port { void* AlignedMalloc(size_t size, int minimum_alignment) { return _aligned_malloc(size, minimum_alignment); } void AlignedFree(void* aligned_memory) { _aligned_free(aligned_memory); } void AlignedSizedFree(void* aligned_memory, size_t alignment, size_t size) { (void)alignment; (void)size; _aligned_free(aligned_memory); } void* Malloc(size_t size) { return malloc(size); } void* Realloc(void* ptr, size_t size) { return realloc(ptr, size); } void Free(void* ptr) { free(ptr); } void MallocExtension_ReleaseToSystem(std::size_t num_bytes) { } std::size_t MallocExtension_GetAllocatedSize(const void* p) { return 0; } MemoryInfo GetMemoryInfo() { MemoryInfo mem_info = {INT64_MAX, INT64_MAX}; MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); if (GlobalMemoryStatusEx(&statex)) { mem_info.free = statex.ullAvailPhys; mem_info.total = statex.ullTotalPhys; } return mem_info; } MemoryBandwidthInfo GetMemoryBandwidthInfo() { MemoryBandwidthInfo membw_info = {INT64_MAX}; return membw_info; } } }
#include <condition_variable> #include "tsl/platform/cpu_info.h" #include "tsl/platform/env_time.h" #include "tsl/platform/mem.h" #include "tsl/platform/mutex.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl { namespace port { TEST(Port, AlignedMalloc) { for (size_t alignment = 1; alignment <= 1 << 20; alignment <<= 1) { void* p = AlignedMalloc(1, alignment); ASSERT_TRUE(p != nullptr) << "AlignedMalloc(1, " << alignment << ")"; uintptr_t pval = reinterpret_cast<uintptr_t>(p); EXPECT_EQ(pval % alignment, 0); AlignedFree(p); } } TEST(Port, GetCurrentCPU) { const int cpu = GetCurrentCPU(); #if !defined(__APPLE__) EXPECT_GE(cpu, 0); EXPECT_LT(cpu, NumTotalCPUs()); #endif } TEST(ConditionVariable, WaitForMilliseconds_Timeout) { mutex m; mutex_lock l(m); condition_variable cv; ConditionResult result = tsl::kCond_MaybeNotified; time_t start = time(nullptr); while (result == tsl::kCond_MaybeNotified) { result = WaitForMilliseconds(&l, &cv, 3000); } EXPECT_EQ(result, tsl::kCond_Timeout); time_t finish = time(nullptr); EXPECT_GE(finish - start, 3); } TEST(ConditionVariable, WaitForMilliseconds_Signalled) { thread::ThreadPool pool(Env::Default(), "test", 1); mutex m; mutex_lock l(m); condition_variable cv; time_t start = time(nullptr); pool.Schedule([&m, &cv]() { Env::Default()->SleepForMicroseconds(1 * 1000 * 1000); mutex_lock l(m); cv.notify_all(); }); EXPECT_EQ(WaitForMilliseconds(&l, &cv, 3000), tsl::kCond_MaybeNotified); time_t finish = time(nullptr); EXPECT_LT(finish - start, 3); } TEST(ConditionalCriticalSections, AwaitWithDeadline_Timeout) { bool always_false = false; mutex m; m.lock(); time_t start = time(nullptr); bool result = m.AwaitWithDeadline(Condition(&always_false), EnvTime::NowNanos() + 3 * EnvTime::kSecondsToNanos); time_t finish = time(nullptr); m.unlock(); EXPECT_EQ(result, false); EXPECT_GE(finish - start, 3); } TEST(ConditionalCriticalSections, AwaitWithDeadline_Woken) { thread::ThreadPool pool(Env::Default(), "test", 1); bool woken = false; mutex m; m.lock(); time_t start = time(nullptr); pool.Schedule([&m, &woken]() { Env::Default()->SleepForMicroseconds(1 * 1000 * 1000); m.lock(); woken = true; m.unlock(); }); bool result = m.AwaitWithDeadline( Condition(&woken), EnvTime::NowNanos() + 3 * EnvTime::kSecondsToNanos); time_t finish = time(nullptr); m.unlock(); EXPECT_EQ(result, true); EXPECT_LT(finish - start, 3); } static bool Invert(bool* b) { return !*b; } class InvertClass { public: explicit InvertClass(bool* value) : value_(value) {} bool Value() { return !*this->value_; } private: InvertClass(); bool* value_; }; TEST(ConditionalCriticalSections, Await_PingPong) { thread::ThreadPool pool(Env::Default(), "test", 1); bool ping_pong = false; bool done = false; mutex m; pool.Schedule([&m, &ping_pong, &done]() { m.lock(); for (int i = 0; i != 1000; i++) { m.Await(Condition(&ping_pong)); ping_pong = false; } done = true; m.unlock(); }); m.lock(); InvertClass invert(&ping_pong); for (int i = 0; i != 1000; i++) { m.Await(Condition(&Invert, &ping_pong)); ping_pong = true; } m.Await(Condition(&done)); m.unlock(); } TEST(ConditionalCriticalSections, Await_PingPongMethod) { thread::ThreadPool pool(Env::Default(), "test", 1); bool ping_pong = false; bool done = false; mutex m; pool.Schedule([&m, &ping_pong, &done]() { m.lock(); for (int i = 0; i != 1000; i++) { m.Await(Condition(&ping_pong)); ping_pong = false; } done = true; m.unlock(); }); m.lock(); InvertClass invert(&ping_pong); for (int i = 0; i != 1000; i++) { m.Await(Condition(&invert, &InvertClass::Value)); ping_pong = true; } m.Await(Condition(&done)); m.unlock(); } TEST(TestCPUFeature, TestFeature) { const bool has_avx = TestCPUFeature(CPUFeature::AVX); LOG(INFO) << "has_avx = " << has_avx; const bool has_avx2 = TestCPUFeature(CPUFeature::AVX2); LOG(INFO) << "has_avx2 = " << has_avx2; } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/windows/port.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/port_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
2cb2e135-6604-44e0-8fda-15cc4fd7f77a
cpp
google/tsl
logging
tsl/platform/default/logging.cc
tsl/platform/logging_test.cc
#include "tsl/platform/default/logging.h" #include "absl/base/internal/cycleclock.h" #include "absl/base/internal/sysinfo.h" #include "absl/base/log_severity.h" #include "absl/strings/string_view.h" #include "tsl/platform/env_time.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #if defined(PLATFORM_POSIX_ANDROID) #include <android/log.h> #include <iostream> #include <sstream> #endif #include <stdlib.h> #include <string.h> #include <time.h> #include <algorithm> #include <queue> #include <unordered_map> namespace tsl { namespace internal { namespace { class TFLogSinks { public: static TFLogSinks& Instance(); void Add(TFLogSink* sink); void Remove(TFLogSink* sink); std::vector<TFLogSink*> GetSinks() const; void Send(const TFLogEntry& entry); private: TFLogSinks(); void SendToSink(TFLogSink& sink, const TFLogEntry& entry); std::queue<TFLogEntry> log_entry_queue_; static const size_t kMaxLogEntryQueueSize = 128; mutable tsl::mutex mutex_; std::vector<TFLogSink*> sinks_; }; TFLogSinks::TFLogSinks() { #ifndef NO_DEFAULT_LOGGER static TFDefaultLogSink* default_sink = new TFDefaultLogSink(); sinks_.emplace_back(default_sink); #endif } TFLogSinks& TFLogSinks::Instance() { static TFLogSinks* instance = new TFLogSinks(); return *instance; } void TFLogSinks::Add(TFLogSink* sink) { assert(sink != nullptr && "The sink must not be a nullptr"); tsl::mutex_lock lock(mutex_); sinks_.emplace_back(sink); if (sinks_.size() == 1) { while (!log_entry_queue_.empty()) { for (const auto& sink : sinks_) { SendToSink(*sink, log_entry_queue_.front()); } log_entry_queue_.pop(); } } } void TFLogSinks::Remove(TFLogSink* sink) { assert(sink != nullptr && "The sink must not be a nullptr"); tsl::mutex_lock lock(mutex_); auto it = std::find(sinks_.begin(), sinks_.end(), sink); if (it != sinks_.end()) sinks_.erase(it); } std::vector<TFLogSink*> TFLogSinks::GetSinks() const { tsl::mutex_lock lock(mutex_); return sinks_; } void TFLogSinks::Send(const TFLogEntry& entry) { tsl::mutex_lock lock(mutex_); if (sinks_.empty()) { while (log_entry_queue_.size() >= kMaxLogEntryQueueSize) { log_entry_queue_.pop(); } log_entry_queue_.push(entry); return; } while (!log_entry_queue_.empty()) { for (const auto& sink : sinks_) { SendToSink(*sink, log_entry_queue_.front()); } log_entry_queue_.pop(); } for (const auto& sink : sinks_) { SendToSink(*sink, entry); } } void TFLogSinks::SendToSink(TFLogSink& sink, const TFLogEntry& entry) { sink.Send(entry); sink.WaitTillSent(); } class VlogFileMgr { public: VlogFileMgr(); ~VlogFileMgr(); FILE* FilePtr() const; private: FILE* vlog_file_ptr; char* vlog_file_name; }; VlogFileMgr::VlogFileMgr() { vlog_file_name = getenv("TF_CPP_VLOG_FILENAME"); vlog_file_ptr = vlog_file_name == nullptr ? nullptr : fopen(vlog_file_name, "w"); if (vlog_file_ptr == nullptr) { vlog_file_ptr = stderr; } } VlogFileMgr::~VlogFileMgr() { if (vlog_file_ptr != stderr) { fclose(vlog_file_ptr); } } FILE* VlogFileMgr::FilePtr() const { return vlog_file_ptr; } int ParseInteger(const char* str, size_t size) { string integer_str(str, size); std::istringstream ss(integer_str); int level = 0; ss >> level; return level; } int64_t LogLevelStrToInt(const char* tf_env_var_val) { if (tf_env_var_val == nullptr) { return 0; } return ParseInteger(tf_env_var_val, strlen(tf_env_var_val)); } struct StringData { struct Hasher { size_t operator()(const StringData& sdata) const { size_t hash = 5381; const char* data = sdata.data; for (const char* top = data + sdata.size; data < top; ++data) { hash = ((hash << 5) + hash) + (*data); } return hash; } }; StringData() = default; StringData(const char* data, size_t size) : data(data), size(size) {} bool operator==(const StringData& rhs) const { return size == rhs.size && memcmp(data, rhs.data, size) == 0; } const char* data = nullptr; size_t size = 0; }; using VmoduleMap = std::unordered_map<StringData, int, StringData::Hasher>; VmoduleMap* VmodulesMapFromEnv() { const char* env = getenv("TF_CPP_VMODULE"); if (env == nullptr) { return nullptr; } const char* env_data = strdup(env); VmoduleMap* result = new VmoduleMap(); while (true) { const char* eq = strchr(env_data, '='); if (eq == nullptr) { break; } const char* after_eq = eq + 1; const char* comma = strchr(after_eq, ','); const char* new_env_data; if (comma == nullptr) { comma = strchr(after_eq, '\0'); new_env_data = comma; } else { new_env_data = comma + 1; } (*result)[StringData(env_data, eq - env_data)] = ParseInteger(after_eq, comma - after_eq); env_data = new_env_data; } return result; } bool EmitThreadIdFromEnv() { const char* tf_env_var_val = getenv("TF_CPP_LOG_THREAD_ID"); return tf_env_var_val == nullptr ? false : ParseInteger(tf_env_var_val, strlen(tf_env_var_val)) != 0; } } absl::LogSeverityAtLeast MinLogLevelFromEnv() { #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION return absl::LogSeverityAtLeast::kInfinity; #else const char* tf_env_var_val = getenv("TF_CPP_MIN_LOG_LEVEL"); return static_cast<absl::LogSeverityAtLeast>( LogLevelStrToInt(tf_env_var_val)); #endif } int MaxVLogLevelFromEnv() { #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION return 0; #else const char* tf_env_var_val = getenv("TF_CPP_MAX_VLOG_LEVEL"); return LogLevelStrToInt(tf_env_var_val); #endif } LogMessage::LogMessage(const char* fname, int line, absl::LogSeverity severity) : fname_(fname), line_(line), severity_(severity) {} LogMessage& LogMessage::AtLocation(const char* fname, int line) { fname_ = fname; line_ = line; return *this; } LogMessage::~LogMessage() { static absl::LogSeverityAtLeast min_log_level = MinLogLevelFromEnv(); if (severity_ >= min_log_level) { GenerateLogMessage(); } } void LogMessage::GenerateLogMessage() { TFLogSinks::Instance().Send(TFLogEntry(severity_, fname_, line_, str())); } int LogMessage::MaxVLogLevel() { static int max_vlog_level = MaxVLogLevelFromEnv(); return max_vlog_level; } bool LogMessage::VmoduleActivated(const char* fname, int level) { if (level <= MaxVLogLevel()) { return true; } static VmoduleMap* vmodules = VmodulesMapFromEnv(); if (TF_PREDICT_TRUE(vmodules == nullptr)) { return false; } const char* last_slash = strrchr(fname, '/'); const char* module_start = last_slash == nullptr ? fname : last_slash + 1; const char* dot_after = strchr(module_start, '.'); const char* module_limit = dot_after == nullptr ? strchr(fname, '\0') : dot_after; StringData module(module_start, module_limit - module_start); auto it = vmodules->find(module); return it != vmodules->end() && it->second >= level; } LogMessageFatal::LogMessageFatal(const char* file, int line) : LogMessage(file, line, absl::LogSeverity::kFatal) {} LogMessageFatal::~LogMessageFatal() { GenerateLogMessage(); abort(); } void LogString(const char* fname, int line, absl::LogSeverity severity, const string& message) { LogMessage(fname, line, severity) << message; } template <> void MakeCheckOpValueString(std::ostream* os, const char& v) { if (v >= 32 && v <= 126) { (*os) << "'" << v << "'"; } else { (*os) << "char value " << static_cast<int16>(v); } } template <> void MakeCheckOpValueString(std::ostream* os, const signed char& v) { if (v >= 32 && v <= 126) { (*os) << "'" << v << "'"; } else { (*os) << "signed char value " << static_cast<int16>(v); } } template <> void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) { if (v >= 32 && v <= 126) { (*os) << "'" << v << "'"; } else { (*os) << "unsigned char value " << static_cast<uint16>(v); } } #if LANG_CXX11 template <> void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& v) { (*os) << "nullptr"; } #endif CheckOpMessageBuilder::CheckOpMessageBuilder(const char* exprtext) : stream_(new std::ostringstream) { *stream_ << "Check failed: " << exprtext << " ("; } CheckOpMessageBuilder::~CheckOpMessageBuilder() { delete stream_; } std::ostream* CheckOpMessageBuilder::ForVar2() { *stream_ << " vs. "; return stream_; } string* CheckOpMessageBuilder::NewString() { *stream_ << ")"; return new string(stream_->str()); } namespace { uint32 LossyIncrement(std::atomic<uint32>* counter) { const uint32 value = counter->load(std::memory_order_relaxed); counter->store(value + 1, std::memory_order_relaxed); return value; } } bool LogEveryNState::ShouldLog(int n) { return n != 0 && (LossyIncrement(&counter_) % n) == 0; } bool LogFirstNState::ShouldLog(int n) { const int counter_value = static_cast<int>(counter_.load(std::memory_order_relaxed)); if (counter_value < n) { counter_.store(counter_value + 1, std::memory_order_relaxed); return true; } return false; } bool LogEveryPow2State::ShouldLog(int ignored) { const uint32 new_value = LossyIncrement(&counter_) + 1; return (new_value & (new_value - 1)) == 0; } bool LogEveryNSecState::ShouldLog(double seconds) { LossyIncrement(&counter_); const int64_t now_cycles = absl::base_internal::CycleClock::Now(); int64_t next_cycles = next_log_time_cycles_.load(std::memory_order_relaxed); do { if (now_cycles <= next_cycles) return false; } while (!next_log_time_cycles_.compare_exchange_weak( next_cycles, now_cycles + seconds * absl::base_internal::CycleClock::Frequency(), std::memory_order_relaxed, std::memory_order_relaxed)); return true; } } void TFAddLogSink(TFLogSink* sink) { internal::TFLogSinks::Instance().Add(sink); } void TFRemoveLogSink(TFLogSink* sink) { internal::TFLogSinks::Instance().Remove(sink); } std::vector<TFLogSink*> TFGetLogSinks() { return internal::TFLogSinks::Instance().GetSinks(); } void TFDefaultLogSink::Send(const TFLogEntry& entry) { #ifdef PLATFORM_POSIX_ANDROID int android_log_level; switch (entry.log_severity()) { case absl::LogSeverity::kInfo: android_log_level = ANDROID_LOG_INFO; break; case absl::LogSeverity::kWarning: android_log_level = ANDROID_LOG_WARN; break; case absl::LogSeverity::kError: android_log_level = ANDROID_LOG_ERROR; break; case absl::LogSeverity::kFatal: android_log_level = ANDROID_LOG_FATAL; break; default: if (entry.log_severity() < absl::LogSeverity::kInfo) { android_log_level = ANDROID_LOG_VERBOSE; } else { android_log_level = ANDROID_LOG_ERROR; } break; } std::stringstream ss; const auto& fname = entry.FName(); auto pos = fname.find("/"); ss << (pos != std::string::npos ? fname.substr(pos + 1) : fname) << ":" << entry.Line() << " " << entry.ToString(); __android_log_write(android_log_level, "native", ss.str().c_str()); fprintf(stderr, "native : %s\n", ss.str().c_str()); if (entry.log_severity() == absl::LogSeverity::kFatal) { abort(); } #else static const internal::VlogFileMgr vlog_file; static bool log_thread_id = internal::EmitThreadIdFromEnv(); uint64 now_micros = EnvTime::NowMicros(); time_t now_seconds = static_cast<time_t>(now_micros / 1000000); int32_t micros_remainder = static_cast<int32>(now_micros % 1000000); const size_t time_buffer_size = 30; char time_buffer[time_buffer_size]; strftime(time_buffer, time_buffer_size, "%Y-%m-%d %H:%M:%S", localtime(&now_seconds)); const size_t tid_buffer_size = 10; char tid_buffer[tid_buffer_size] = ""; if (log_thread_id) { snprintf(tid_buffer, sizeof(tid_buffer), " %7u", absl::base_internal::GetTID()); } char sev; switch (entry.log_severity()) { case absl::LogSeverity::kInfo: sev = 'I'; break; case absl::LogSeverity::kWarning: sev = 'W'; break; case absl::LogSeverity::kError: sev = 'E'; break; case absl::LogSeverity::kFatal: sev = 'F'; break; default: assert(false && "Unknown logging severity"); sev = '?'; break; } fprintf(vlog_file.FilePtr(), "%s.%06d: %c%s %s:%d] %s\n", time_buffer, micros_remainder, sev, tid_buffer, entry.FName().c_str(), entry.Line(), entry.ToString().c_str()); fflush(vlog_file.FilePtr()); #endif } void UpdateLogVerbosityIfDefined(const char* env_var) {} }
#include "tsl/platform/logging.h" #include <cerrno> #include <cstddef> #include <cstdio> #include <cstdlib> #include <memory> #include <sstream> #include <vector> #include "absl/base/log_severity.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "tsl/platform/path.h" #include "tsl/platform/stacktrace_handler.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" #ifdef PLATFORM_WINDOWS #define popen _popen #define pclose _pclose #endif static char* program_name; namespace tsl { namespace { using ::testing::HasSubstr; using ::testing::Not; TEST(Logging, Log) { LOG(INFO) << "Hello"; LOG(INFO) << "Another log message"; LOG(ERROR) << "Error message"; VLOG(1) << "A VLOG message"; VLOG(2) << "A higher VLOG message"; DVLOG(1) << "A DVLOG message"; DVLOG(2) << "A higher DVLOG message"; } TEST(Logging, CheckChecks) { CHECK(true); CHECK(7 > 5); string a("abc"); string b("xyz"); CHECK_EQ(a, a); CHECK_NE(a, b); CHECK_EQ(3, 3); CHECK_NE(4, 3); CHECK_GT(4, 3); CHECK_GE(3, 3); CHECK_LT(2, 3); CHECK_LE(2, 3); DCHECK(true); DCHECK(7 > 5); DCHECK_EQ(a, a); DCHECK_NE(a, b); DCHECK_EQ(3, 3); DCHECK_NE(4, 3); DCHECK_GT(4, 3); DCHECK_GE(3, 3); DCHECK_LT(2, 3); DCHECK_LE(2, 3); } TEST(LoggingDeathTest, FailedChecks) { string a("abc"); string b("xyz"); const char* p_const = "hello there"; const char* p_null_const = nullptr; char mybuf[10]; char* p_non_const = mybuf; char* p_null = nullptr; CHECK_NOTNULL(p_const); CHECK_NOTNULL(p_non_const); ASSERT_DEATH(CHECK(false), "false"); ASSERT_DEATH(CHECK(9 < 7), "9 < 7"); ASSERT_DEATH(CHECK_EQ(a, b), "a == b"); ASSERT_DEATH(CHECK_EQ(3, 4), "3 == 4"); ASSERT_DEATH(CHECK_NE(3, 3), "3 != 3"); ASSERT_DEATH(CHECK_GT(2, 3), "2 > 3"); ASSERT_DEATH(CHECK_GE(2, 3), "2 >= 3"); ASSERT_DEATH(CHECK_LT(3, 2), "3 < 2"); ASSERT_DEATH(CHECK_LE(3, 2), "3 <= 2"); ASSERT_DEATH(CHECK(false), "false"); ASSERT_DEATH(printf("%s", CHECK_NOTNULL(p_null)), "Must be non NULL"); ASSERT_DEATH(printf("%s", CHECK_NOTNULL(p_null_const)), "Must be non NULL"); #ifndef NDEBUG ASSERT_DEATH(DCHECK(9 < 7), "9 < 7"); ASSERT_DEATH(DCHECK(9 < 7), "9 < 7"); ASSERT_DEATH(DCHECK_EQ(a, b), "a == b"); ASSERT_DEATH(DCHECK_EQ(3, 4), "3 == 4"); ASSERT_DEATH(DCHECK_NE(3, 3), "3 != 3"); ASSERT_DEATH(DCHECK_GT(2, 3), "2 > 3"); ASSERT_DEATH(DCHECK_GE(2, 3), "2 >= 3"); ASSERT_DEATH(DCHECK_LT(3, 2), "3 < 2"); ASSERT_DEATH(DCHECK_LE(3, 2), "3 <= 2"); #endif } TEST(InternalLogString, Basic) { internal::LogString(__FILE__, __LINE__, absl::LogSeverity::kInfo, "Hello there"); } class TestSink : public TFLogSink { public: void Send(const TFLogEntry& entry) override { ss_ << entry.text_message() << std::endl; } std::string Get() const { return ss_.str(); } private: std::stringstream ss_; }; TEST(LogSinkTest, testLogSinks) { const int sinks_initial_size = TFGetLogSinks().size(); TestSink sink; TFAddLogSink(&sink); EXPECT_EQ(TFGetLogSinks().size(), sinks_initial_size + 1); LOG(INFO) << "Foo"; LOG(INFO) << "Bar"; EXPECT_EQ(sink.Get(), "Foo\nBar\n"); TFRemoveLogSink(&sink); EXPECT_EQ(TFGetLogSinks().size(), sinks_initial_size); } std::string ReadFromFilePointer(FILE* fp) { std::string result; while (!feof(fp)) { char buf[512]; size_t len = fread(buf, sizeof(buf[0]), 512, fp); result.append(buf, len); } return result; } absl::StatusOr<std::string> ReadFromFile(const std::string& filename) { std::shared_ptr<FILE> fp(fopen(filename.c_str(), "r"), fclose); if (fp == nullptr) { return absl::ErrnoToStatus(errno, absl::StrFormat("Cannot fopen '%s'", filename)); } return ReadFromFilePointer(fp.get()); } class SubcommandTest : public ::testing::Test { public: static constexpr absl::string_view kLogVLog = "log_and_vlog"; static bool IsSubcommand(absl::string_view subcommand) { return subcommand == kLogVLog; } static int Run(absl::string_view subcommand) { CHECK_EQ(subcommand, kLogVLog); LOG(INFO) << "LOG INFO"; LOG(WARNING) << "LOG WARNING"; LOG(ERROR) << "LOG ERROR"; LOG(INFO) << absl::StrFormat("VLOG_IS_ON(1)? %d", VLOG_IS_ON(1)); LOG(INFO) << absl::StrFormat("VLOG_IS_ON(2)? %d", VLOG_IS_ON(2)); LOG(INFO) << absl::StrFormat("VLOG_IS_ON(3)? %d", VLOG_IS_ON(3)); VLOG(1) << "VLevel 1"; VLOG(2) << "VLevel 2"; VLOG(3) << "VLevel 3"; return EXIT_SUCCESS; } protected: absl::StatusOr<std::string> CaptureOutput(const char* invocation) { std::shared_ptr<FILE> fp(popen(invocation, "r"), pclose); if (fp == nullptr) { return absl::ErrnoToStatus( errno, absl::StrFormat("Cannot popen '%s'", invocation)); } return ReadFromFilePointer(fp.get()); } }; TEST_F(SubcommandTest, LogDefaultTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --alsologtostderr"; #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, HasSubstr("LOG INFO")); EXPECT_THAT(out, HasSubstr("LOG WARNING")); EXPECT_THAT(out, HasSubstr("LOG ERROR")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(1)? 0")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(2)? 0")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(3)? 0")); } TEST_F(SubcommandTest, MinLogLevelTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --minloglevel=1 --alsologtostderr"; #elif defined(PLATFORM_WINDOWS) command = absl::StrFormat("set TF_CPP_MIN_LOG_LEVEL=1 && %s", command); #else command = absl::StrFormat("TF_CPP_MIN_LOG_LEVEL=1 %s", command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, Not(HasSubstr("LOG INFO"))); EXPECT_THAT(out, HasSubstr("LOG WARNING")); EXPECT_THAT(out, HasSubstr("LOG ERROR")); } TEST_F(SubcommandTest, VLogDefaultTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --alsologtostderr"; #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, Not(HasSubstr("VLevel 1"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 2"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); } TEST_F(SubcommandTest, MaxVLogLevelTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --v=2 --alsologtostderr"; #elif defined(PLATFORM_WINDOWS) command = absl::StrFormat("set TF_CPP_MAX_VLOG_LEVEL=2 && %s", command); #else command = absl::StrFormat("TF_CPP_MAX_VLOG_LEVEL=2 %s", command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, HasSubstr("VLevel 1")); EXPECT_THAT(out, HasSubstr("VLevel 2")); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(1)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(2)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(3)? 0")); } TEST_F(SubcommandTest, VModuleTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --vmodule=logging_test=2,shoobadooba=3 --alsologtostderr"; #elif defined(PLATFORM_WINDOWS) command = absl::StrFormat( "set TF_CPP_VMODULE=logging_test=2,shoobadooba=3 && %s", command); #else command = absl::StrFormat("TF_CPP_VMODULE=logging_test=2,shoobadooba=3 %s", command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, HasSubstr("VLevel 1")); EXPECT_THAT(out, HasSubstr("VLevel 2")); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(1)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(2)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(3)? 0")); } TEST_F(SubcommandTest, VLogFilenameTest) { #if defined(PLATFORM_GOOGLE) constexpr bool kVLogFilenameEnvVarIsSupported = false; #else constexpr bool kVLogFilenameEnvVarIsSupported = true; #endif if (!kVLogFilenameEnvVarIsSupported) { GTEST_SKIP() << "Not supported on this platform"; } std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); std::string filename = io::GetTempFilename("logging_test"); #if defined(PLATFORM_WINDOWS) command = absl::StrFormat( "set TF_CPP_VLOG_FILENAME=%s && set TF_CPP_MAX_VLOG_LEVEL=1 && %s", filename, command); #else command = absl::StrFormat( "TF_CPP_VLOG_FILENAME=%s TF_CPP_MAX_VLOG_LEVEL=1 %s", filename, command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, Not(HasSubstr("LOG INFO"))); EXPECT_THAT(out, Not(HasSubstr("LOG WARNING"))); EXPECT_THAT(out, Not(HasSubstr("LOG ERROR"))); EXPECT_THAT(out, Not(HasSubstr("VLOG_IS_ON(1)?"))); EXPECT_THAT(out, Not(HasSubstr("VLOG_IS_ON(2)?"))); EXPECT_THAT(out, Not(HasSubstr("VLOG_IS_ON(3)?"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 1"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 2"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); TF_ASSERT_OK_AND_ASSIGN(std::string log_file, ReadFromFile(filename)); EXPECT_THAT(log_file, HasSubstr("LOG INFO")); EXPECT_THAT(log_file, HasSubstr("LOG WARNING")); EXPECT_THAT(log_file, HasSubstr("LOG ERROR")); EXPECT_THAT(log_file, HasSubstr("VLOG_IS_ON(1)")); EXPECT_THAT(log_file, HasSubstr("VLOG_IS_ON(2)")); EXPECT_THAT(log_file, HasSubstr("VLOG_IS_ON(3)")); EXPECT_THAT(log_file, HasSubstr("VLevel 1")); EXPECT_THAT(log_file, Not(HasSubstr("VLevel 2"))); EXPECT_THAT(log_file, Not(HasSubstr("VLevel 3"))); } } } GTEST_API_ int main(int argc, char** argv) { tsl::testing::InstallStacktraceHandler(); testing::InitGoogleTest(&argc, argv); program_name = argv[0]; if (argc >= 2 && tsl::SubcommandTest::IsSubcommand(argv[1])) { return tsl::SubcommandTest::Run(argv[1]); } return RUN_ALL_TESTS(); }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/default/logging.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/logging_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
3d22ad6c-a254-4b61-adf3-de1bf2716283
cpp
google/tsl
time_util
tsl/platform/cloud/time_util.cc
tsl/platform/cloud/time_util_test.cc
#include "tsl/platform/cloud/time_util.h" #include <time.h> #include <cmath> #include <cstdio> #include <ctime> #ifdef _WIN32 #define timegm _mkgmtime #endif #include "tsl/platform/errors.h" namespace tsl { namespace { constexpr int64_t kNanosecondsPerSecond = 1000 * 1000 * 1000; } absl::Status ParseRfc3339Time(const string& time, int64_t* mtime_nsec) { tm parsed{0}; float seconds; if (sscanf(time.c_str(), "%4d-%2d-%2dT%2d:%2d:%fZ", &(parsed.tm_year), &(parsed.tm_mon), &(parsed.tm_mday), &(parsed.tm_hour), &(parsed.tm_min), &seconds) != 6) { return errors::Internal( strings::StrCat("Unrecognized RFC 3339 time format: ", time)); } const int int_seconds = std::floor(seconds); parsed.tm_year -= 1900; parsed.tm_mon -= 1; parsed.tm_sec = int_seconds; *mtime_nsec = timegm(&parsed) * kNanosecondsPerSecond + static_cast<int64_t>(std::floor((seconds - int_seconds) * kNanosecondsPerSecond)); return absl::OkStatus(); } }
#include "tsl/platform/cloud/time_util.h" #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/test.h" namespace tsl { TEST(TimeUtil, ParseRfc3339Time) { int64_t mtime_nsec; TF_EXPECT_OK(ParseRfc3339Time("2016-04-29T23:15:24.896Z", &mtime_nsec)); EXPECT_NEAR(1461971724896, mtime_nsec / 1000 / 1000, 1); } TEST(TimeUtil, ParseRfc3339Time_ParseError) { int64_t mtime_nsec; EXPECT_EQ("Unrecognized RFC 3339 time format: 2016-04-29", ParseRfc3339Time("2016-04-29", &mtime_nsec).message()); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/time_util.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/time_util_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
fb20ada8-b714-43c8-8b83-15f3843d3fde
cpp
google/tsl
gcs_dns_cache
tsl/platform/cloud/gcs_dns_cache.cc
tsl/platform/cloud/gcs_dns_cache_test.cc
#include "tsl/platform/cloud/gcs_dns_cache.h" #include <cstring> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "tsl/platform/errors.h" #include "tsl/platform/retrying_utils.h" #include "tsl/platform/status.h" #ifndef _WIN32 #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #else #include <Windows.h> #include <winsock2.h> #include <ws2tcpip.h> #endif #include <sys/types.h> namespace tsl { namespace { const std::vector<string>& kCachedDomainNames = *new std::vector<string>{"www.googleapis.com", "storage.googleapis.com"}; inline void print_getaddrinfo_error(const string& name, absl::Status return_status) { LOG(ERROR) << "Error resolving " << name << ": " << return_status; } template <typename T> const T& SelectRandomItemUniform(std::default_random_engine* random, const std::vector<T>& items) { CHECK_GT(items.size(), 0); std::uniform_int_distribution<size_t> distribution(0u, items.size() - 1u); size_t choice_index = distribution(*random); return items[choice_index]; } } GcsDnsCache::GcsDnsCache(Env* env, int64_t refresh_rate_secs) : env_(env), refresh_rate_secs_(refresh_rate_secs) {} void GcsDnsCache::AnnotateRequest(HttpRequest* request) { mutex_lock l(mu_); if (!started_) { VLOG(1) << "Starting GCS DNS cache."; DCHECK(!worker_) << "Worker thread already exists!"; addresses_ = ResolveNames(kCachedDomainNames); worker_.reset(env_->StartThread({}, "gcs_dns_worker", [this]() { return WorkerThread(); })); started_ = true; } CHECK_EQ(kCachedDomainNames.size(), addresses_.size()); for (size_t i = 0; i < kCachedDomainNames.size(); ++i) { const string& name = kCachedDomainNames[i]; const std::vector<string>& addresses = addresses_[i]; if (!addresses.empty()) { const string& chosen_address = SelectRandomItemUniform(&random_, addresses); request->AddResolveOverride(name, 443, chosen_address); VLOG(1) << "Annotated DNS mapping: " << name << " --> " << chosen_address; } else { LOG(WARNING) << "No IP addresses available for " << name; } } } std::vector<string> GcsDnsCache::ResolveName(const string& name) { VLOG(1) << "Resolving DNS name: " << name; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; addrinfo* result = nullptr; RetryConfig retryConfig( 5000, 50 * 1000 * 5000, 5); const absl::Status getaddrinfo_status = RetryingUtils::CallWithRetries( [&name, &hints, &result]() { int return_code = getaddrinfo(name.c_str(), nullptr, &hints, &result); absl::Status return_status; switch (return_code) { case 0: return_status = absl::OkStatus(); break; #ifndef _WIN32 case EAI_ADDRFAMILY: case EAI_SERVICE: case EAI_SOCKTYPE: case EAI_NONAME: return_status = absl::FailedPreconditionError( absl::StrCat("System in invalid state for getaddrinfo call: ", gai_strerror(return_code))); break; case EAI_AGAIN: case EAI_NODATA: return_status = absl::UnavailableError(absl::StrCat( "Resolving ", name, " is temporarily unavailable")); break; case EAI_BADFLAGS: case EAI_FAMILY: return_status = absl::InvalidArgumentError(absl::StrCat( "Bad arguments for getaddrinfo: ", gai_strerror(return_code))); break; case EAI_FAIL: return_status = absl::NotFoundError( absl::StrCat("Permanent failure resolving ", name, ": ", gai_strerror(return_code))); break; case EAI_MEMORY: return_status = absl::ResourceExhaustedError("Out of memory"); break; case EAI_SYSTEM: default: return_status = absl::UnknownError(strerror(return_code)); #else case WSATYPE_NOT_FOUND: case WSAESOCKTNOSUPPORT: case WSAHOST_NOT_FOUND: return_status = absl::FailedPreconditionError( absl::StrCat("System in invalid state for getaddrinfo call: ", gai_strerror(return_code))); break; case WSATRY_AGAIN: return_status = absl::UnavailableError(absl::StrCat( "Resolving ", name, " is temporarily unavailable")); break; case WSAEINVAL: case WSAEAFNOSUPPORT: return_status = absl::InvalidArgumentError(absl::StrCat( "Bad arguments for getaddrinfo: ", gai_strerror(return_code))); break; case WSANO_RECOVERY: return_status = absl::NotFoundError( absl::StrCat("Permanent failure resolving ", name, ": ", gai_strerror(return_code))); break; case WSA_NOT_ENOUGH_MEMORY: return_status = absl::ResourceExhaustedError("Out of memory"); break; default: return_status = absl::UnknownError(strerror(return_code)); #endif } return absl::Status(return_status); }, retryConfig); std::vector<string> output; if (getaddrinfo_status.ok()) { for (const addrinfo* i = result; i != nullptr; i = i->ai_next) { if (i->ai_family != AF_INET || i->ai_addr->sa_family != AF_INET) { LOG(WARNING) << "Non-IPv4 address returned. ai_family: " << i->ai_family << ". sa_family: " << i->ai_addr->sa_family << "."; continue; } char buf[INET_ADDRSTRLEN]; void* address_ptr = &(reinterpret_cast<sockaddr_in*>(i->ai_addr)->sin_addr); const char* formatted = nullptr; if ((formatted = inet_ntop(i->ai_addr->sa_family, address_ptr, buf, INET_ADDRSTRLEN)) == nullptr) { LOG(ERROR) << "Error converting response to IP address for " << name << ": " << strerror(errno); } else { output.emplace_back(buf); VLOG(1) << "... address: " << buf; } } } else { print_getaddrinfo_error(name, getaddrinfo_status); } if (result != nullptr) { freeaddrinfo(result); } return output; } std::vector<std::vector<string>> GcsDnsCache::ResolveNames( const std::vector<string>& names) { std::vector<std::vector<string>> all_addresses; all_addresses.reserve(names.size()); for (const string& name : names) { all_addresses.push_back(ResolveName(name)); } return all_addresses; } void GcsDnsCache::WorkerThread() { while (true) { { mutex_lock l(mu_); if (cancelled_) return; cond_var_.wait_for(l, std::chrono::seconds(refresh_rate_secs_)); if (cancelled_) return; } auto new_addresses = ResolveNames(kCachedDomainNames); { mutex_lock l(mu_); addresses_.swap(new_addresses); } } } }
#include "tsl/platform/cloud/gcs_dns_cache.h" #include "tsl/platform/str_util.h" #include "tsl/platform/test.h" namespace tsl { class TestHttpRequest : public HttpRequest { public: void SetUri(const string& uri) override {} void SetRange(uint64 start, uint64 end) override {} void AddHeader(const string& name, const string& value) override {} void AddResolveOverride(const string& hostname, int64_t port, const string& ip_addr) override { EXPECT_EQ(port, 443) << "Unexpected port set for hostname: " << hostname; auto itr = resolve_overrides_.find(hostname); EXPECT_EQ(itr, resolve_overrides_.end()) << "Hostname " << hostname << "already in map: " << itr->second; resolve_overrides_.insert( std::map<string, string>::value_type(hostname, ip_addr)); } void AddAuthBearerHeader(const string& auth_token) override {} void SetRequestStats(HttpRequest::RequestStats* stats) override {} void SetDeleteRequest() override {} absl::Status SetPutFromFile(const string& body_filepath, size_t offset) override { return absl::OkStatus(); } void SetPutEmptyBody() override {} void SetPostFromBuffer(const char* buffer, size_t size) override {} void SetPostEmptyBody() override {} void SetResultBuffer(std::vector<char>* out_buffer) override {} void SetResultBufferDirect(char* buffer, size_t size) override {} size_t GetResultBufferDirectBytesTransferred() override { return 0; } string GetResponseHeader(const string& name) const override { return ""; } uint64 GetResponseCode() const override { return 0; } absl::Status Send() override { return absl::OkStatus(); } string EscapeString(const string& str) override { return ""; } void SetTimeouts(uint32 connection, uint32 inactivity, uint32 total) override {} std::map<string, string> resolve_overrides_; }; class GcsDnsCacheTest : public ::testing::Test { protected: void ResolveNameTest() { auto response = GcsDnsCache::ResolveName("www.googleapis.com"); EXPECT_LT(1, response.size()) << absl::StrJoin(response, ", "); } void AnnotateRequestTest() { GcsDnsCache d; { mutex_lock l(d.mu_); d.started_ = true; d.addresses_ = {{"192.168.1.1"}, {"172.134.1.1"}}; } TestHttpRequest req; d.AnnotateRequest(&req); EXPECT_EQ("192.168.1.1", req.resolve_overrides_["www.googleapis.com"]); EXPECT_EQ("172.134.1.1", req.resolve_overrides_["storage.googleapis.com"]); } void SuccessfulCleanupTest() { GcsDnsCache d; TestHttpRequest req; d.AnnotateRequest(&req); } }; TEST_F(GcsDnsCacheTest, AnnotateRequest) { AnnotateRequestTest(); } TEST_F(GcsDnsCacheTest, SuccessfulCleanup) { SuccessfulCleanupTest(); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/gcs_dns_cache.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/gcs_dns_cache_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
5ab2c70a-fff9-43d8-8884-621f1dde07fe
cpp
google/tsl
compute_engine_zone_provider
tsl/platform/cloud/compute_engine_zone_provider.cc
tsl/platform/cloud/compute_engine_zone_provider_test.cc
#include "tsl/platform/cloud/compute_engine_zone_provider.h" #include <utility> #include "tsl/platform/str_util.h" namespace tsl { namespace { constexpr char kGceMetadataZonePath[] = "instance/zone"; } ComputeEngineZoneProvider::ComputeEngineZoneProvider( std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client) : google_metadata_client_(std::move(google_metadata_client)) {} absl::Status ComputeEngineZoneProvider::GetZone(string* zone) { if (!cached_zone.empty()) { *zone = cached_zone; return absl::OkStatus(); } std::vector<char> response_buffer; TF_RETURN_IF_ERROR(google_metadata_client_->GetMetadata(kGceMetadataZonePath, &response_buffer)); absl::string_view location(&response_buffer[0], response_buffer.size()); std::vector<string> elems = str_util::Split(location, "/"); if (elems.size() == 4) { cached_zone = elems.back(); *zone = cached_zone; } else { LOG(ERROR) << "Failed to parse the zone name from location: " << string(location); } return absl::OkStatus(); } ComputeEngineZoneProvider::~ComputeEngineZoneProvider() {} }
#include "tsl/platform/cloud/compute_engine_zone_provider.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/test.h" namespace tsl { class ComputeEngineZoneProviderTest : public ::testing::Test { protected: void SetUp() override {} void TearDown() override {} }; TEST_F(ComputeEngineZoneProviderTest, GetZone) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "Header Metadata-Flavor: Google\n", "projects/123456789/zones/us-west1-b")}); auto httpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadata_client = std::make_shared<ComputeEngineMetadataClient>( httpRequestFactory, RetryConfig(0 )); ComputeEngineZoneProvider provider(metadata_client); string zone; TF_EXPECT_OK(provider.GetZone(&zone)); EXPECT_EQ("us-west1-b", zone); TF_EXPECT_OK(provider.GetZone(&zone)); } TEST_F(ComputeEngineZoneProviderTest, InvalidZoneString) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "Header Metadata-Flavor: Google\n", "invalidresponse")}); auto httpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadata_client = std::make_shared<ComputeEngineMetadataClient>( httpRequestFactory, RetryConfig(0 )); ComputeEngineZoneProvider provider(metadata_client); string zone; TF_EXPECT_OK(provider.GetZone(&zone)); EXPECT_EQ("", zone); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/compute_engine_zone_provider.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/compute_engine_zone_provider_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
f1c793e1-4a71-47a5-990f-f229cef257dc
cpp
google/tsl
compute_engine_metadata_client
tsl/platform/cloud/compute_engine_metadata_client.cc
tsl/platform/cloud/compute_engine_metadata_client_test.cc
#include "tsl/platform/cloud/compute_engine_metadata_client.h" #include <cstdlib> #include <utility> #include "absl/strings/str_cat.h" #include "tsl/platform/cloud/curl_http_request.h" namespace tsl { namespace { constexpr char kGceMetadataHost[] = "GCE_METADATA_HOST"; constexpr char kGceMetadataBaseUrl[] = "http: } ComputeEngineMetadataClient::ComputeEngineMetadataClient( std::shared_ptr<HttpRequest::Factory> http_request_factory, const RetryConfig& config) : http_request_factory_(std::move(http_request_factory)), retry_config_(config) {} absl::Status ComputeEngineMetadataClient::GetMetadata( const string& path, std::vector<char>* response_buffer) { const auto get_metadata_from_gce = [path, response_buffer, this]() { string metadata_url; const char* metadata_url_override = std::getenv(kGceMetadataHost); if (metadata_url_override) { metadata_url = absl::StrCat("http: "/computeMetadata/v1/"); } else { metadata_url = kGceMetadataBaseUrl; } std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); request->SetUri(metadata_url + path); request->AddHeader("Metadata-Flavor", "Google"); request->SetResultBuffer(response_buffer); TF_RETURN_IF_ERROR(request->Send()); return absl::OkStatus(); }; return RetryingUtils::CallWithRetries(get_metadata_from_gce, retry_config_); } }
#include "tsl/platform/cloud/compute_engine_metadata_client.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { class ComputeEngineMetadataClientTest : public ::testing::Test { protected: void SetUp() override { ClearEnvVars(); } void TearDown() override { ClearEnvVars(); } void ClearEnvVars() { unsetenv("GCE_METADATA_HOST"); } }; TEST_F(ComputeEngineMetadataClientTest, GetMetadata) { const string example_response = "example response"; std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", example_response)}); std::shared_ptr<HttpRequest::Factory> http_factory = std::make_shared<FakeHttpRequestFactory>(&requests); ComputeEngineMetadataClient client(http_factory, RetryConfig(0 )); std::vector<char> result; TF_EXPECT_OK( client.GetMetadata("instance/service-accounts/default/token", &result)); std::vector<char> expected(example_response.begin(), example_response.end()); EXPECT_EQ(expected, result); } TEST_F(ComputeEngineMetadataClientTest, GetCustomMetadataEndpoint) { const string example_response = "example response"; setenv("GCE_METADATA_HOST", "foo.bar", 1); std::vector<HttpRequest*> requests( {new FakeHttpRequest("Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", example_response)}); std::shared_ptr<HttpRequest::Factory> http_factory = std::make_shared<FakeHttpRequestFactory>(&requests); ComputeEngineMetadataClient client(http_factory, RetryConfig(0 )); std::vector<char> result; TF_EXPECT_OK( client.GetMetadata("instance/service-accounts/default/token", &result)); std::vector<char> expected(example_response.begin(), example_response.end()); EXPECT_EQ(expected, result); } TEST_F(ComputeEngineMetadataClientTest, RetryOnFailure) { const string example_response = "example response"; std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", example_response)}); std::shared_ptr<HttpRequest::Factory> http_factory = std::make_shared<FakeHttpRequestFactory>(&requests); ComputeEngineMetadataClient client(http_factory, RetryConfig(0 )); std::vector<char> result; TF_EXPECT_OK( client.GetMetadata("instance/service-accounts/default/token", &result)); std::vector<char> expected(example_response.begin(), example_response.end()); EXPECT_EQ(expected, result); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/compute_engine_metadata_client.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/compute_engine_metadata_client_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
08dd50bc-773c-4ab0-ba6f-510bc4326bed
cpp
google/tsl
gcs_file_system
tsl/platform/cloud/gcs_file_system.cc
tsl/platform/cloud/gcs_file_system_test.cc
#include "tsl/platform/cloud/gcs_file_system.h" #include <stdio.h> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #ifndef _WIN32 #include <unistd.h> #endif #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <functional> #include <string> #include <utility> #include <vector> #include "tsl/platform/file_statistics.h" #include "tsl/platform/strcat.h" #ifdef _WIN32 #include <io.h> #endif #include "absl/base/macros.h" #include "json/json.h" #include "tsl/platform/cloud/curl_http_request.h" #include "tsl/platform/cloud/file_block_cache.h" #include "tsl/platform/cloud/google_auth_provider.h" #include "tsl/platform/cloud/ram_file_block_cache.h" #include "tsl/platform/cloud/time_util.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/mutex.h" #include "tsl/platform/numbers.h" #include "tsl/platform/path.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/retrying_utils.h" #include "tsl/platform/str_util.h" #include "tsl/platform/stringprintf.h" #include "tsl/platform/thread_annotations.h" #include "tsl/profiler/lib/traceme.h" #ifdef _WIN32 #ifdef DeleteFile #undef DeleteFile #endif #endif namespace tsl { namespace { constexpr char kGcsUriBase[] = "https: constexpr char kGcsUploadUriBase[] = "https: constexpr char kStorageHost[] = "storage.googleapis.com"; constexpr char kBucketMetadataLocationKey[] = "location"; constexpr size_t kReadAppendableFileBufferSize = 1024 * 1024; constexpr int kGetChildrenDefaultPageSize = 1000; constexpr uint64 HTTP_CODE_RESUME_INCOMPLETE = 308; constexpr uint64 HTTP_CODE_PRECONDITION_FAILED = 412; ABSL_DEPRECATED("Use GCS_READ_CACHE_BLOCK_SIZE_MB instead.") constexpr char kReadaheadBufferSize[] = "GCS_READAHEAD_BUFFER_SIZE_BYTES"; constexpr char kStatCacheMaxAge[] = "GCS_STAT_CACHE_MAX_AGE"; constexpr uint64 kStatCacheDefaultMaxAge = 5; constexpr char kStatCacheMaxEntries[] = "GCS_STAT_CACHE_MAX_ENTRIES"; constexpr size_t kStatCacheDefaultMaxEntries = 1024; constexpr char kMatchingPathsCacheMaxAge[] = "GCS_MATCHING_PATHS_CACHE_MAX_AGE"; constexpr uint64 kMatchingPathsCacheDefaultMaxAge = 0; constexpr char kMatchingPathsCacheMaxEntries[] = "GCS_MATCHING_PATHS_CACHE_MAX_ENTRIES"; constexpr size_t kMatchingPathsCacheDefaultMaxEntries = 1024; constexpr size_t kBucketLocationCacheMaxEntries = 10; constexpr size_t kCacheNeverExpire = std::numeric_limits<uint64>::max(); const FileStatistics DIRECTORY_STAT(0, 0, true); constexpr char kResolveCacheSecs[] = "GCS_RESOLVE_REFRESH_SECS"; constexpr char kRequestConnectionTimeout[] = "GCS_REQUEST_CONNECTION_TIMEOUT_SECS"; constexpr char kRequestIdleTimeout[] = "GCS_REQUEST_IDLE_TIMEOUT_SECS"; constexpr char kMetadataRequestTimeout[] = "GCS_METADATA_REQUEST_TIMEOUT_SECS"; constexpr char kReadRequestTimeout[] = "GCS_READ_REQUEST_TIMEOUT_SECS"; constexpr char kWriteRequestTimeout[] = "GCS_WRITE_REQUEST_TIMEOUT_SECS"; constexpr char kAdditionalRequestHeader[] = "GCS_ADDITIONAL_REQUEST_HEADER"; constexpr char kThrottleRate[] = "GCS_THROTTLE_TOKEN_RATE"; constexpr char kThrottleBucket[] = "GCS_THROTTLE_BUCKET_SIZE"; constexpr char kTokensPerRequest[] = "GCS_TOKENS_PER_REQUEST"; constexpr char kInitialTokens[] = "GCS_INITIAL_TOKENS"; constexpr char kRetryConfigInitialDelayTimeUs[] = "GCS_RETRY_CONFIG_INIT_DELAY_TIME_US"; constexpr char kRetryConfigMaxDelayTimeUs[] = "GCS_RETRY_CONFIG_MAX_DELAY_TIME_US"; constexpr char kRetryConfigMaxRetries[] = "GCS_RETRY_CONFIG_MAX_RETRIES"; constexpr char kAllowedBucketLocations[] = "GCS_ALLOWED_BUCKET_LOCATIONS"; constexpr char kDetectZoneSentinelValue[] = "auto"; constexpr char kAppendMode[] = "GCS_APPEND_MODE"; constexpr char kComposeAppend[] = "compose"; absl::Status GetTmpFilename(string* filename) { *filename = io::GetTempFilename(""); return absl::OkStatus(); } string MaybeAppendSlash(const string& name) { if (name.empty()) { return "/"; } if (name.back() != '/') { return strings::StrCat(name, "/"); } return name; } string JoinGcsPath(const string& path, const string& subpath) { return strings::StrCat(MaybeAppendSlash(path), subpath); } std::set<string> AddAllSubpaths(const std::vector<string>& paths) { std::set<string> result; result.insert(paths.begin(), paths.end()); for (const string& path : paths) { absl::string_view subpath = io::Dirname(path); while (!(subpath.empty() || subpath == "/")) { result.emplace(string(subpath)); subpath = io::Dirname(subpath); } } return result; } absl::Status ParseJson(absl::string_view json, Json::Value* result) { Json::Reader reader; if (!reader.parse(json.data(), json.data() + json.size(), *result)) { return errors::Internal("Couldn't parse JSON response from GCS."); } return absl::OkStatus(); } absl::Status ParseJson(const std::vector<char>& json, Json::Value* result) { return ParseJson(absl::string_view{json.data(), json.size()}, result); } absl::Status GetValue(const Json::Value& parent, const char* name, Json::Value* result) { *result = parent.get(name, Json::Value::null); if (result->isNull()) { return errors::Internal("The field '", name, "' was expected in the JSON response."); } return absl::OkStatus(); } absl::Status GetStringValue(const Json::Value& parent, const char* name, string* result) { Json::Value result_value; TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value)); if (!result_value.isString()) { return errors::Internal( "The field '", name, "' in the JSON response was expected to be a string."); } *result = result_value.asString(); return absl::OkStatus(); } absl::Status GetInt64Value(const Json::Value& parent, const char* name, int64_t* result) { Json::Value result_value; TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value)); if (result_value.isNumeric()) { *result = result_value.asInt64(); return absl::OkStatus(); } if (result_value.isString() && strings::safe_strto64(result_value.asCString(), result)) { return absl::OkStatus(); } return errors::Internal( "The field '", name, "' in the JSON response was expected to be a number."); } absl::Status GetBoolValue(const Json::Value& parent, const char* name, bool* result) { Json::Value result_value; TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value)); if (!result_value.isBool()) { return errors::Internal( "The field '", name, "' in the JSON response was expected to be a boolean."); } *result = result_value.asBool(); return absl::OkStatus(); } RetryConfig GetGcsRetryConfig() { RetryConfig retryConfig( 1000 * 1000, 32 * 1000 * 1000, 10); uint64 init_delay_time_us; if (GetEnvVar(kRetryConfigInitialDelayTimeUs, strings::safe_strtou64, &init_delay_time_us)) { retryConfig.init_delay_time_us = init_delay_time_us; } uint64 max_delay_time_us; if (GetEnvVar(kRetryConfigMaxDelayTimeUs, strings::safe_strtou64, &max_delay_time_us)) { retryConfig.max_delay_time_us = max_delay_time_us; } uint32 max_retries; if (GetEnvVar(kRetryConfigMaxRetries, strings::safe_strtou32, &max_retries)) { retryConfig.max_retries = max_retries; } VLOG(1) << "GCS RetryConfig: " << "init_delay_time_us = " << retryConfig.init_delay_time_us << " ; " << "max_delay_time_us = " << retryConfig.max_delay_time_us << " ; " << "max_retries = " << retryConfig.max_retries; return retryConfig; } class GcsRandomAccessFile : public RandomAccessFile { public: using ReadFn = std::function<absl::Status( const string& filename, uint64 offset, size_t n, absl::string_view* result, char* scratch)>; GcsRandomAccessFile(const string& filename, ReadFn read_fn) : filename_(filename), read_fn_(std::move(read_fn)) {} absl::Status Name(absl::string_view* result) const override { *result = filename_; return absl::OkStatus(); } absl::Status Read(uint64 offset, size_t n, absl::string_view* result, char* scratch) const override { return read_fn_(filename_, offset, n, result, scratch); } private: const string filename_; const ReadFn read_fn_; }; class BufferedGcsRandomAccessFile : public RandomAccessFile { public: using ReadFn = std::function<absl::Status( const string& filename, uint64 offset, size_t n, absl::string_view* result, char* scratch)>; BufferedGcsRandomAccessFile(const string& filename, uint64 buffer_size, ReadFn read_fn) : filename_(filename), read_fn_(std::move(read_fn)), buffer_size_(buffer_size), buffer_start_(0), buffer_end_is_past_eof_(false) {} absl::Status Name(absl::string_view* result) const override { *result = filename_; return absl::OkStatus(); } absl::Status Read(uint64 offset, size_t n, absl::string_view* result, char* scratch) const override { if (n > buffer_size_) { return read_fn_(filename_, offset, n, result, scratch); } { mutex_lock l(buffer_mutex_); size_t buffer_end = buffer_start_ + buffer_.size(); size_t copy_size = 0; if (offset < buffer_end && offset >= buffer_start_) { copy_size = std::min(n, static_cast<size_t>(buffer_end - offset)); memcpy(scratch, buffer_.data() + (offset - buffer_start_), copy_size); *result = absl::string_view(scratch, copy_size); } bool consumed_buffer_to_eof = offset + copy_size >= buffer_end && buffer_end_is_past_eof_; if (copy_size < n && !consumed_buffer_to_eof) { absl::Status status = FillBuffer(offset + copy_size); if (!status.ok() && !absl::IsOutOfRange(status)) { buffer_.resize(0); return status; } size_t remaining_copy = std::min(n - copy_size, buffer_.size()); memcpy(scratch + copy_size, buffer_.data(), remaining_copy); copy_size += remaining_copy; *result = absl::string_view(scratch, copy_size); } if (copy_size < n) { buffer_end_is_past_eof_ = false; return errors::OutOfRange("EOF reached. Requested to read ", n, " bytes from ", offset, "."); } } return absl::OkStatus(); } private: absl::Status FillBuffer(uint64 start) const TF_EXCLUSIVE_LOCKS_REQUIRED(buffer_mutex_) { buffer_start_ = start; buffer_.resize(buffer_size_); absl::string_view str_piece; absl::Status status = read_fn_(filename_, buffer_start_, buffer_size_, &str_piece, &(buffer_[0])); buffer_end_is_past_eof_ = absl::IsOutOfRange(status); buffer_.resize(str_piece.size()); return status; } const string filename_; const ReadFn read_fn_; const uint64 buffer_size_; mutable mutex buffer_mutex_; mutable uint64 buffer_start_ TF_GUARDED_BY(buffer_mutex_); mutable bool buffer_end_is_past_eof_ TF_GUARDED_BY(buffer_mutex_); mutable string buffer_ TF_GUARDED_BY(buffer_mutex_); }; typedef std::function<absl::Status( uint64 start_offset, const std::string& object_to_upload, const std::string& bucket, uint64 file_size, const std::string& gcs_path, UploadSessionHandle* session_handle)> SessionCreator; typedef std::function<absl::Status( const std::string& session_uri, uint64 start_offset, uint64 already_uploaded, const std::string& tmp_content_filename, uint64 file_size, const std::string& file_path)> ObjectUploader; typedef std::function<absl::Status(const string& session_uri, uint64 file_size, const std::string& gcs_path, bool* completed, uint64* uploaded)> StatusPoller; typedef std::function<absl::Status(const string& fname, const string& bucket, const string& object, int64_t* generation)> GenerationGetter; class GcsWritableFile : public WritableFile { public: GcsWritableFile(const string& bucket, const string& object, GcsFileSystem* filesystem, GcsFileSystem::TimeoutConfig* timeouts, std::function<void()> file_cache_erase, RetryConfig retry_config, bool compose_append, SessionCreator session_creator, ObjectUploader object_uploader, StatusPoller status_poller, GenerationGetter generation_getter) : bucket_(bucket), object_(object), filesystem_(filesystem), timeouts_(timeouts), file_cache_erase_(std::move(file_cache_erase)), sync_needed_(true), retry_config_(retry_config), compose_append_(compose_append), start_offset_(0), session_creator_(std::move(session_creator)), object_uploader_(std::move(object_uploader)), status_poller_(std::move(status_poller)), generation_getter_(std::move(generation_getter)) { VLOG(3) << "GcsWritableFile: " << GetGcsPath(); if (GetTmpFilename(&tmp_content_filename_).ok()) { outfile_.open(tmp_content_filename_, std::ofstream::binary | std::ofstream::app); } } GcsWritableFile(const string& bucket, const string& object, GcsFileSystem* filesystem, const string& tmp_content_filename, GcsFileSystem::TimeoutConfig* timeouts, std::function<void()> file_cache_erase, RetryConfig retry_config, bool compose_append, SessionCreator session_creator, ObjectUploader object_uploader, StatusPoller status_poller, GenerationGetter generation_getter) : bucket_(bucket), object_(object), filesystem_(filesystem), timeouts_(timeouts), file_cache_erase_(std::move(file_cache_erase)), sync_needed_(true), retry_config_(retry_config), compose_append_(compose_append), start_offset_(0), session_creator_(std::move(session_creator)), object_uploader_(std::move(object_uploader)), status_poller_(std::move(status_poller)), generation_getter_(std::move(generation_getter)) { VLOG(3) << "GcsWritableFile: " << GetGcsPath() << "with existing file " << tmp_content_filename; tmp_content_filename_ = tmp_content_filename; outfile_.open(tmp_content_filename_, std::ofstream::binary | std::ofstream::app); } ~GcsWritableFile() override { Close().IgnoreError(); std::remove(tmp_content_filename_.c_str()); } absl::Status Append(absl::string_view data) override { TF_RETURN_IF_ERROR(CheckWritable()); VLOG(3) << "Append: " << GetGcsPath() << " size " << data.length(); sync_needed_ = true; outfile_ << data; if (!outfile_.good()) { return errors::Internal( "Could not append to the internal temporary file."); } return absl::OkStatus(); } absl::Status Close() override { VLOG(3) << "Close:" << GetGcsPath(); if (outfile_.is_open()) { absl::Status sync_status = Sync(); if (sync_status.ok()) { outfile_.close(); } return sync_status; } return absl::OkStatus(); } absl::Status Flush() override { VLOG(3) << "Flush:" << GetGcsPath(); return Sync(); } absl::Status Name(absl::string_view* result) const override { *result = object_; return absl::OkStatus(); } absl::Status Sync() override { VLOG(3) << "Sync started:" << GetGcsPath(); TF_RETURN_IF_ERROR(CheckWritable()); if (!sync_needed_) { return absl::OkStatus(); } absl::Status status = SyncImpl(); VLOG(3) << "Sync finished " << GetGcsPath(); if (status.ok()) { sync_needed_ = false; } return status; } absl::Status Tell(int64_t* position) override { *position = outfile_.tellp(); if (*position == -1) { return errors::Internal("tellp on the internal temporary file failed"); } return absl::OkStatus(); } private: absl::Status SyncImpl() { outfile_.flush(); if (!outfile_.good()) { return errors::Internal( "Could not write to the internal temporary file."); } UploadSessionHandle session_handle; uint64 start_offset = 0; string object_to_upload = object_; bool should_compose = false; if (compose_append_) { start_offset = start_offset_; should_compose = start_offset > 0; if (should_compose) { object_to_upload = strings::StrCat(io::Dirname(object_), "/.tmpcompose/", io::Basename(object_), ".", start_offset_); } } TF_RETURN_IF_ERROR(CreateNewUploadSession(start_offset, object_to_upload, &session_handle)); uint64 already_uploaded = 0; bool first_attempt = true; const absl::Status upload_status = RetryingUtils::CallWithRetries( [&first_attempt, &already_uploaded, &session_handle, &start_offset, this]() { if (session_handle.resumable && !first_attempt) { bool completed; TF_RETURN_IF_ERROR(RequestUploadSessionStatus( session_handle.session_uri, &completed, &already_uploaded)); LOG(INFO) << "### RequestUploadSessionStatus: completed = " << completed << ", already_uploaded = " << already_uploaded << ", file = " << GetGcsPath(); if (completed) { file_cache_erase_(); return absl::OkStatus(); } } first_attempt = false; return UploadToSession(session_handle.session_uri, start_offset, already_uploaded); }, retry_config_); if (absl::IsNotFound(upload_status)) { return errors::Unavailable( strings::StrCat("Upload to gs: " failed, caused by: ", upload_status.message())); } if (upload_status.ok()) { if (should_compose) { TF_RETURN_IF_ERROR(AppendObject(object_to_upload)); } TF_RETURN_IF_ERROR(GetCurrentFileSize(&start_offset_)); } return upload_status; } absl::Status CheckWritable() const { if (!outfile_.is_open()) { return errors::FailedPrecondition( "The internal temporary file is not writable."); } return absl::OkStatus(); } absl::Status GetCurrentFileSize(uint64* size) { const auto tellp = outfile_.tellp(); if (tellp == static_cast<std::streampos>(-1)) { return errors::Internal( "Could not get the size of the internal temporary file."); } *size = tellp; return absl::OkStatus(); } absl::Status CreateNewUploadSession(uint64 start_offset, std::string object_to_upload, UploadSessionHandle* session_handle) { uint64 file_size; TF_RETURN_IF_ERROR(GetCurrentFileSize(&file_size)); return session_creator_(start_offset, object_to_upload, bucket_, file_size, GetGcsPath(), session_handle); } absl::Status AppendObject(string append_object) { const string append_object_path = GetGcsPathWithObject(append_object); VLOG(3) << "AppendObject: " << append_object_path << " to " << GetGcsPath(); int64_t generation = 0; TF_RETURN_IF_ERROR( generation_getter_(GetGcsPath(), bucket_, object_, &generation)); TF_RETURN_IF_ERROR(RetryingUtils::CallWithRetries( [&append_object, &generation, this]() { std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(filesystem_->CreateHttpRequest(&request)); request->SetUri(strings::StrCat(kGcsUriBase, "b/", bucket_, "/o/", request->EscapeString(object_), "/compose")); const string request_body = strings::StrCat( "{'sourceObjects': [{'name': '", object_, "','objectPrecondition':{'ifGenerationMatch':", generation, "}},{'name': '", append_object, "'}]}"); request->SetTimeouts(timeouts_->connect, timeouts_->idle, timeouts_->metadata); request->AddHeader("content-type", "application/json"); request->SetPostFromBuffer(request_body.c_str(), request_body.size()); TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when composing to ", GetGcsPath()); return absl::OkStatus(); }, retry_config_)); return RetryingUtils::DeleteWithRetries( [&append_object_path, this]() { return filesystem_->DeleteFile(append_object_path, nullptr); }, retry_config_); } absl::Status RequestUploadSessionStatus(const string& session_uri, bool* completed, uint64* uploaded) { uint64 file_size; TF_RETURN_IF_ERROR(GetCurrentFileSize(&file_size)); return status_poller_(session_uri, file_size, GetGcsPath(), completed, uploaded); } absl::Status UploadToSession(const string& session_uri, uint64 start_offset, uint64 already_uploaded) { uint64 file_size; TF_RETURN_IF_ERROR(GetCurrentFileSize(&file_size)); absl::Status status = object_uploader_(session_uri, start_offset, already_uploaded, tmp_content_filename_, file_size, GetGcsPath()); if (status.ok()) { file_cache_erase_(); } return status; } string GetGcsPathWithObject(string object) const { return strings::StrCat("gs: } string GetGcsPath() const { return GetGcsPathWithObject(object_); } string bucket_; string object_; GcsFileSystem* const filesystem_; string tmp_content_filename_; std::ofstream outfile_; GcsFileSystem::TimeoutConfig* timeouts_; std::function<void()> file_cache_erase_; bool sync_needed_; RetryConfig retry_config_ = GetGcsRetryConfig(); bool compose_append_; uint64 start_offset_; const SessionCreator session_creator_; const ObjectUploader object_uploader_; const StatusPoller status_poller_; const GenerationGetter generation_getter_; }; class GcsReadOnlyMemoryRegion : public ReadOnlyMemoryRegion { public: GcsReadOnlyMemoryRegion(std::unique_ptr<char[]> data, uint64 length) : data_(std::move(data)), length_(length) {} const void* data() override { return reinterpret_cast<void*>(data_.get()); } uint64 length() override { return length_; } private: std::unique_ptr<char[]> data_; uint64 length_; }; bool StringPieceIdentity(absl::string_view str, absl::string_view* value) { *value = str; return true; } bool SplitByCommaToLowercaseSet(absl::string_view list, std::unordered_set<string>* set) { std::vector<string> vector = absl::StrSplit(absl::AsciiStrToLower(list), ','); *set = std::unordered_set<string>(vector.begin(), vector.end()); return true; } string ZoneToRegion(string* zone) { return zone->substr(0, zone->find_last_of('-')); } } GcsFileSystem::GcsFileSystem(bool make_default_cache) { uint64 value; block_size_ = kDefaultBlockSize; size_t max_bytes = kDefaultMaxCacheSize; uint64 max_staleness = kDefaultMaxStaleness; http_request_factory_ = std::make_shared<CurlHttpRequest::Factory>(); compute_engine_metadata_client_ = std::make_shared<ComputeEngineMetadataClient>(http_request_factory_); auth_provider_ = std::unique_ptr<AuthProvider>( new GoogleAuthProvider(compute_engine_metadata_client_)); zone_provider_ = std::unique_ptr<ZoneProvider>( new ComputeEngineZoneProvider(compute_engine_metadata_client_)); if (GetEnvVar(kReadaheadBufferSize, strings::safe_strtou64, &value)) { block_size_ = value; } if (GetEnvVar(kBlockSize, strings::safe_strtou64, &value)) { block_size_ = value * 1024 * 1024; } if (GetEnvVar(kMaxCacheSize, strings::safe_strtou64, &value)) { max_bytes = value * 1024 * 1024; } if (GetEnvVar(kMaxStaleness, strings::safe_strtou64, &value)) { max_staleness = value; } if (!make_default_cache) { max_bytes = 0; } VLOG(1) << "GCS cache max size = " << max_bytes << " ; " << "block size = " << block_size_ << " ; " << "max staleness = " << max_staleness; file_block_cache_ = MakeFileBlockCache(block_size_, max_bytes, max_staleness); uint64 stat_cache_max_age = kStatCacheDefaultMaxAge; size_t stat_cache_max_entries = kStatCacheDefaultMaxEntries; if (GetEnvVar(kStatCacheMaxAge, strings::safe_strtou64, &value)) { stat_cache_max_age = value; } if (GetEnvVar(kStatCacheMaxEntries, strings::safe_strtou64, &value)) { stat_cache_max_entries = value; } stat_cache_.reset(new ExpiringLRUCache<GcsFileStat>(stat_cache_max_age, stat_cache_max_entries)); uint64 matching_paths_cache_max_age = kMatchingPathsCacheDefaultMaxAge; size_t matching_paths_cache_max_entries = kMatchingPathsCacheDefaultMaxEntries; if (GetEnvVar(kMatchingPathsCacheMaxAge, strings::safe_strtou64, &value)) { matching_paths_cache_max_age = value; } if (GetEnvVar(kMatchingPathsCacheMaxEntries, strings::safe_strtou64, &value)) { matching_paths_cache_max_entries = value; } matching_paths_cache_.reset(new ExpiringLRUCache<std::vector<string>>( matching_paths_cache_max_age, matching_paths_cache_max_entries)); bucket_location_cache_.reset(new ExpiringLRUCache<string>( kCacheNeverExpire, kBucketLocationCacheMaxEntries)); int64_t resolve_frequency_secs; if (GetEnvVar(kResolveCacheSecs, strings::safe_strto64, &resolve_frequency_secs)) { dns_cache_.reset(new GcsDnsCache(resolve_frequency_secs)); VLOG(1) << "GCS DNS cache is enabled. " << kResolveCacheSecs << " = " << resolve_frequency_secs; } else { VLOG(1) << "GCS DNS cache is disabled, because " << kResolveCacheSecs << " = 0 (or is not set)"; } absl::string_view add_header_contents; if (GetEnvVar(kAdditionalRequestHeader, StringPieceIdentity, &add_header_contents)) { size_t split = add_header_contents.find(':', 0); if (split != absl::string_view::npos) { absl::string_view header_name = add_header_contents.substr(0, split); absl::string_view header_value = add_header_contents.substr(split + 1); if (!header_name.empty() && !header_value.empty()) { additional_header_.reset(new std::pair<const string, const string>( string(header_name), string(header_value))); VLOG(1) << "GCS additional header ENABLED. " << "Name: " << additional_header_->first << ", " << "Value: " << additional_header_->second; } else { LOG(ERROR) << "GCS additional header DISABLED. Invalid contents: " << add_header_contents; } } else { LOG(ERROR) << "GCS additional header DISABLED. Invalid contents: " << add_header_contents; } } else { VLOG(1) << "GCS additional header DISABLED. No environment variable set."; } uint32 timeout_value; if (GetEnvVar(kRequestConnectionTimeout, strings::safe_strtou32, &timeout_value)) { timeouts_.connect = timeout_value; } if (GetEnvVar(kRequestIdleTimeout, strings::safe_strtou32, &timeout_value)) { timeouts_.idle = timeout_value; } if (GetEnvVar(kMetadataRequestTimeout, strings::safe_strtou32, &timeout_value)) { timeouts_.metadata = timeout_value; } if (GetEnvVar(kReadRequestTimeout, strings::safe_strtou32, &timeout_value)) { timeouts_.read = timeout_value; } if (GetEnvVar(kWriteRequestTimeout, strings::safe_strtou32, &timeout_value)) { timeouts_.write = timeout_value; } int64_t token_value; if (GetEnvVar(kThrottleRate, strings::safe_strto64, &token_value)) { GcsThrottleConfig config; config.enabled = true; config.token_rate = token_value; if (GetEnvVar(kThrottleBucket, strings::safe_strto64, &token_value)) { config.bucket_size = token_value; } if (GetEnvVar(kTokensPerRequest, strings::safe_strto64, &token_value)) { config.tokens_per_request = token_value; } if (GetEnvVar(kInitialTokens, strings::safe_strto64, &token_value)) { config.initial_tokens = token_value; } throttle_.SetConfig(config); } GetEnvVar(kAllowedBucketLocations, SplitByCommaToLowercaseSet, &allowed_locations_); absl::string_view append_mode; GetEnvVar(kAppendMode, StringPieceIdentity, &append_mode); if (append_mode == kComposeAppend) { compose_append_ = true; } else { compose_append_ = false; } retry_config_ = GetGcsRetryConfig(); } GcsFileSystem::GcsFileSystem( std::unique_ptr<AuthProvider> auth_provider, std::unique_ptr<HttpRequest::Factory> http_request_factory, std::unique_ptr<ZoneProvider> zone_provider, size_t block_size, size_t max_bytes, uint64 max_staleness, uint64 stat_cache_max_age, size_t stat_cache_max_entries, uint64 matching_paths_cache_max_age, size_t matching_paths_cache_max_entries, RetryConfig retry_config, TimeoutConfig timeouts, const std::unordered_set<string>& allowed_locations, std::pair<const string, const string>* additional_header, bool compose_append) : timeouts_(timeouts), retry_config_(retry_config), auth_provider_(std::move(auth_provider)), http_request_factory_(std::move(http_request_factory)), zone_provider_(std::move(zone_provider)), block_size_(block_size), file_block_cache_( MakeFileBlockCache(block_size, max_bytes, max_staleness)), stat_cache_(new StatCache(stat_cache_max_age, stat_cache_max_entries)), matching_paths_cache_(new MatchingPathsCache( matching_paths_cache_max_age, matching_paths_cache_max_entries)), bucket_location_cache_(new BucketLocationCache( kCacheNeverExpire, kBucketLocationCacheMaxEntries)), allowed_locations_(allowed_locations), compose_append_(compose_append), additional_header_(additional_header) {} absl::Status GcsFileSystem::NewRandomAccessFile( const string& fname, TransactionToken* token, std::unique_ptr<RandomAccessFile>* result) { string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, false, &bucket, &object)); TF_RETURN_IF_ERROR(CheckBucketLocationConstraint(bucket)); if (cache_enabled_) { result->reset(new GcsRandomAccessFile(fname, [this, bucket, object]( const string& fname, uint64 offset, size_t n, absl::string_view* result, char* scratch) { tf_shared_lock l(block_cache_lock_); GcsFileStat stat; TF_RETURN_IF_ERROR(stat_cache_->LookupOrCompute( fname, &stat, [this, bucket, object](const string& fname, GcsFileStat* stat) { return UncachedStatForObject(fname, bucket, object, stat); })); if (!file_block_cache_->ValidateAndUpdateFileSignature( fname, stat.generation_number)) { VLOG(1) << "File signature has been changed. Refreshing the cache. Path: " << fname; } *result = absl::string_view(); size_t bytes_transferred; TF_RETURN_IF_ERROR(file_block_cache_->Read(fname, offset, n, scratch, &bytes_transferred)); *result = absl::string_view(scratch, bytes_transferred); if (bytes_transferred < n) { return errors::OutOfRange("EOF reached, ", result->size(), " bytes were read out of ", n, " bytes requested."); } return absl::OkStatus(); })); } else { result->reset(new BufferedGcsRandomAccessFile( fname, block_size_, [this, bucket, object](const string& fname, uint64 offset, size_t n, absl::string_view* result, char* scratch) { *result = absl::string_view(); size_t bytes_transferred; TF_RETURN_IF_ERROR( LoadBufferFromGCS(fname, offset, n, scratch, &bytes_transferred)); *result = absl::string_view(scratch, bytes_transferred); if (bytes_transferred < n) { return errors::OutOfRange("EOF reached, ", result->size(), " bytes were read out of ", n, " bytes requested."); } return absl::OkStatus(); })); } return absl::OkStatus(); } void GcsFileSystem::ResetFileBlockCache(size_t block_size_bytes, size_t max_bytes, uint64 max_staleness_secs) { mutex_lock l(block_cache_lock_); file_block_cache_ = MakeFileBlockCache(block_size_bytes, max_bytes, max_staleness_secs); if (stats_ != nullptr) { stats_->Configure(this, &throttle_, file_block_cache_.get()); } } std::unique_ptr<FileBlockCache> GcsFileSystem::MakeFileBlockCache( size_t block_size, size_t max_bytes, uint64 max_staleness) { std::unique_ptr<FileBlockCache> file_block_cache(new RamFileBlockCache( block_size, max_bytes, max_staleness, [this](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { return LoadBufferFromGCS(filename, offset, n, buffer, bytes_transferred); })); cache_enabled_ = file_block_cache->IsCacheEnabled(); return file_block_cache; } absl::Status GcsFileSystem::LoadBufferFromGCS(const string& fname, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { *bytes_transferred = 0; string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, false, &bucket, &object)); profiler::TraceMe activity( [fname]() { return absl::StrCat("LoadBufferFromGCS ", fname); }); std::unique_ptr<HttpRequest> request; TF_RETURN_WITH_CONTEXT_IF_ERROR(CreateHttpRequest(&request), "when reading gs: request->SetUri(strings::StrCat("https: request->EscapeString(object))); request->SetRange(offset, offset + n - 1); request->SetResultBufferDirect(buffer, n); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.read); if (stats_ != nullptr) { stats_->RecordBlockLoadRequest(fname, offset); } TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when reading gs: bucket, "/", object); size_t bytes_read = request->GetResultBufferDirectBytesTransferred(); *bytes_transferred = bytes_read; VLOG(1) << "Successful read of gs: << offset << " of size: " << bytes_read; activity.AppendMetadata([bytes_read]() { return profiler::TraceMeEncode({{"block_size", bytes_read}}); }); if (stats_ != nullptr) { stats_->RecordBlockRetrieved(fname, offset, bytes_read); } throttle_.RecordResponse(bytes_read); if (bytes_read < n) { GcsFileStat stat; if (stat_cache_->Lookup(fname, &stat)) { if (offset + bytes_read < stat.base.length) { return errors::Internal(strings::Printf( "File contents are inconsistent for file: %s @ %lu.", fname.c_str(), offset)); } VLOG(2) << "Successful integrity check for: gs: << object << " @ " << offset; } } return absl::OkStatus(); } absl::Status GcsFileSystem::CreateNewUploadSession( uint64 start_offset, const std::string& object_to_upload, const std::string& bucket, uint64 file_size, const std::string& gcs_path, UploadSessionHandle* session_handle) { std::vector<char> output_buffer; std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); std::string uri = strings::StrCat( kGcsUploadUriBase, "b/", bucket, "/o?uploadType=resumable&name=", request->EscapeString(object_to_upload)); request->SetUri(uri); request->AddHeader("X-Upload-Content-Length", absl::StrCat(file_size - start_offset)); request->SetPostEmptyBody(); request->SetResultBuffer(&output_buffer); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when initiating an upload to ", gcs_path); if (session_handle != nullptr) { session_handle->resumable = true; session_handle->session_uri = request->GetResponseHeader("Location"); if (session_handle->session_uri.empty()) { return errors::Internal("Unexpected response from GCS when writing to ", gcs_path, ": 'Location' header not returned."); } } return absl::OkStatus(); } absl::Status GcsFileSystem::UploadToSession( const std::string& session_uri, uint64 start_offset, uint64 already_uploaded, const std::string& tmp_content_filename, uint64 file_size, const std::string& file_path) { std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); request->SetUri(session_uri); if (file_size > 0) { request->AddHeader("Content-Range", strings::StrCat("bytes ", already_uploaded, "-", file_size - start_offset - 1, "/", file_size - start_offset)); } request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.write); TF_RETURN_IF_ERROR(request->SetPutFromFile(tmp_content_filename, start_offset + already_uploaded)); TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when uploading ", file_path); return absl::OkStatus(); } absl::Status GcsFileSystem::RequestUploadSessionStatus( const string& session_uri, uint64 file_size, const std::string& gcs_path, bool* completed, uint64* uploaded) { CHECK(completed != nullptr) << "RequestUploadSessionStatus() called with out " "param 'completed' == nullptr."; CHECK(uploaded != nullptr) << "RequestUploadSessionStatus() called with out " "param 'uploaded' == nullptr."; std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); request->SetUri(session_uri); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); request->AddHeader("Content-Range", strings::StrCat("bytes */", file_size)); request->SetPutEmptyBody(); absl::Status status = request->Send(); if (status.ok()) { *completed = true; return absl::OkStatus(); } *completed = false; if (request->GetResponseCode() != HTTP_CODE_RESUME_INCOMPLETE) { TF_RETURN_WITH_CONTEXT_IF_ERROR(status, " when resuming upload ", gcs_path); } const std::string received_range = request->GetResponseHeader("Range"); if (received_range.empty()) { *uploaded = 0; } else { absl::string_view range_piece(received_range); absl::ConsumePrefix(&range_piece, "bytes="); auto return_error = [](const std::string& gcs_path, const std::string& error_message) { return errors::Internal("Unexpected response from GCS when writing ", gcs_path, ": ", error_message); }; std::vector<string> range_strs = str_util::Split(range_piece, '-'); if (range_strs.size() != 2) { return return_error(gcs_path, "Range header '" + received_range + "' could not be parsed."); } std::vector<int64_t> range_parts; for (const std::string& range_str : range_strs) { int64_t tmp; if (strings::safe_strto64(range_str, &tmp)) { range_parts.push_back(tmp); } else { return return_error(gcs_path, "Range header '" + received_range + "' could not be parsed."); } } if (range_parts[0] != 0) { return return_error(gcs_path, "The returned range '" + received_range + "' does not start at zero."); } *uploaded = range_parts[1] + 1; } return absl::OkStatus(); } absl::Status GcsFileSystem::ParseGcsPathForScheme(absl::string_view fname, string scheme, bool empty_object_ok, string* bucket, string* object) { absl::string_view parsed_scheme, bucketp, objectp; io::ParseURI(fname, &parsed_scheme, &bucketp, &objectp); if (parsed_scheme != scheme) { return errors::InvalidArgument("GCS path doesn't start with 'gs: fname); } *bucket = string(bucketp); if (bucket->empty() || *bucket == ".") { return errors::InvalidArgument("GCS path doesn't contain a bucket name: ", fname); } absl::ConsumePrefix(&objectp, "/"); *object = string(objectp); if (!empty_object_ok && object->empty()) { return errors::InvalidArgument("GCS path doesn't contain an object name: ", fname); } return absl::OkStatus(); } absl::Status GcsFileSystem::ParseGcsPath(absl::string_view fname, bool empty_object_ok, string* bucket, string* object) { return ParseGcsPathForScheme(fname, "gs", empty_object_ok, bucket, object); } void GcsFileSystem::ClearFileCaches(const string& fname) { tf_shared_lock l(block_cache_lock_); file_block_cache_->RemoveFile(fname); stat_cache_->Delete(fname); } absl::Status GcsFileSystem::NewWritableFile( const string& fname, TransactionToken* token, std::unique_ptr<WritableFile>* result) { string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, false, &bucket, &object)); auto session_creator = [this](uint64 start_offset, const std::string& object_to_upload, const std::string& bucket, uint64 file_size, const std::string& gcs_path, UploadSessionHandle* session_handle) { return CreateNewUploadSession(start_offset, object_to_upload, bucket, file_size, gcs_path, session_handle); }; auto object_uploader = [this](const std::string& session_uri, uint64 start_offset, uint64 already_uploaded, const std::string& tmp_content_filename, uint64 file_size, const std::string& file_path) { return UploadToSession(session_uri, start_offset, already_uploaded, tmp_content_filename, file_size, file_path); }; auto status_poller = [this](const string& session_uri, uint64 file_size, const std::string& gcs_path, bool* completed, uint64* uploaded) { return RequestUploadSessionStatus(session_uri, file_size, gcs_path, completed, uploaded); }; auto generation_getter = [this](const string& fname, const string& bucket, const string& object, int64* generation) { GcsFileStat stat; TF_RETURN_IF_ERROR(RetryingUtils::CallWithRetries( [&fname, &bucket, &object, &stat, this]() { return UncachedStatForObject(fname, bucket, object, &stat); }, retry_config_)); *generation = stat.generation_number; return absl::OkStatus(); }; result->reset(new GcsWritableFile( bucket, object, this, &timeouts_, [this, fname]() { ClearFileCaches(fname); }, retry_config_, compose_append_, session_creator, object_uploader, status_poller, generation_getter)); return absl::OkStatus(); } absl::Status GcsFileSystem::NewAppendableFile( const string& fname, TransactionToken* token, std::unique_ptr<WritableFile>* result) { std::unique_ptr<RandomAccessFile> reader; TF_RETURN_IF_ERROR(NewRandomAccessFile(fname, token, &reader)); std::unique_ptr<char[]> buffer(new char[kReadAppendableFileBufferSize]); absl::Status status; uint64 offset = 0; absl::string_view read_chunk; string old_content_filename; TF_RETURN_IF_ERROR(GetTmpFilename(&old_content_filename)); std::ofstream old_content(old_content_filename, std::ofstream::binary); while (true) { status = reader->Read(offset, kReadAppendableFileBufferSize, &read_chunk, buffer.get()); if (status.ok()) { old_content << read_chunk; offset += kReadAppendableFileBufferSize; } else if (status.code() == absl::StatusCode::kNotFound) { break; } else if (status.code() == absl::StatusCode::kOutOfRange) { old_content << read_chunk; break; } else { return status; } } old_content.close(); auto session_creator = [this](uint64 start_offset, const std::string& object_to_upload, const std::string& bucket, uint64 file_size, const std::string& gcs_path, UploadSessionHandle* session_handle) { return CreateNewUploadSession(start_offset, object_to_upload, bucket, file_size, gcs_path, session_handle); }; auto object_uploader = [this](const std::string& session_uri, uint64 start_offset, uint64 already_uploaded, const std::string& tmp_content_filename, uint64 file_size, const std::string& file_path) { return UploadToSession(session_uri, start_offset, already_uploaded, tmp_content_filename, file_size, file_path); }; auto status_poller = [this](const string& session_uri, uint64 file_size, const std::string& gcs_path, bool* completed, uint64* uploaded) { return RequestUploadSessionStatus(session_uri, file_size, gcs_path, completed, uploaded); }; auto generation_getter = [this](const string& fname, const string& bucket, const string& object, int64* generation) { GcsFileStat stat; TF_RETURN_IF_ERROR(RetryingUtils::CallWithRetries( [&fname, &bucket, &object, &stat, this]() { return UncachedStatForObject(fname, bucket, object, &stat); }, retry_config_)); *generation = stat.generation_number; return absl::OkStatus(); }; string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, false, &bucket, &object)); result->reset(new GcsWritableFile( bucket, object, this, old_content_filename, &timeouts_, [this, fname]() { ClearFileCaches(fname); }, retry_config_, compose_append_, session_creator, object_uploader, status_poller, generation_getter)); return absl::OkStatus(); } absl::Status GcsFileSystem::NewReadOnlyMemoryRegionFromFile( const string& fname, TransactionToken* token, std::unique_ptr<ReadOnlyMemoryRegion>* result) { uint64 size; TF_RETURN_IF_ERROR(GetFileSize(fname, token, &size)); std::unique_ptr<char[]> data(new char[size]); std::unique_ptr<RandomAccessFile> file; TF_RETURN_IF_ERROR(NewRandomAccessFile(fname, token, &file)); absl::string_view piece; TF_RETURN_IF_ERROR(file->Read(0, size, &piece, data.get())); result->reset(new GcsReadOnlyMemoryRegion(std::move(data), size)); return absl::OkStatus(); } absl::Status GcsFileSystem::FileExists(const string& fname, TransactionToken* token) { string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, true, &bucket, &object)); if (object.empty()) { bool result; TF_RETURN_IF_ERROR(BucketExists(bucket, &result)); if (result) { return absl::OkStatus(); } else { return absl::NotFoundError( absl::StrCat("The specified bucket ", fname, " was not found.")); } } GcsFileStat stat; const absl::Status status = StatForObject(fname, bucket, object, &stat); if (!absl::IsNotFound(status)) { return status; } bool result; TF_RETURN_IF_ERROR(FolderExists(fname, &result)); if (result) { return absl::OkStatus(); } return errors::NotFound("The specified path ", fname, " was not found."); } absl::Status GcsFileSystem::ObjectExists(const string& fname, const string& bucket, const string& object, bool* result) { GcsFileStat stat; const absl::Status status = StatForObject(fname, bucket, object, &stat); switch (static_cast<int>(status.code())) { case static_cast<int>(error::Code::OK): *result = !stat.base.is_directory; return absl::OkStatus(); case static_cast<int>(error::Code::NOT_FOUND): *result = false; return absl::OkStatus(); default: return status; } } absl::Status GcsFileSystem::UncachedStatForObject(const string& fname, const string& bucket, const string& object, GcsFileStat* stat) { std::vector<char> output_buffer; std::unique_ptr<HttpRequest> request; TF_RETURN_WITH_CONTEXT_IF_ERROR(CreateHttpRequest(&request), " when reading metadata of gs: "/", object); request->SetUri(strings::StrCat(kGcsUriBase, "b/", bucket, "/o/", request->EscapeString(object), "?fields=size%2Cgeneration%2Cupdated")); request->SetResultBuffer(&output_buffer); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); if (stats_ != nullptr) { stats_->RecordStatObjectRequest(); } TF_RETURN_WITH_CONTEXT_IF_ERROR( request->Send(), " when reading metadata of gs: Json::Value root; TF_RETURN_IF_ERROR(ParseJson(output_buffer, &root)); TF_RETURN_IF_ERROR(GetInt64Value(root, "size", &stat->base.length)); TF_RETURN_IF_ERROR( GetInt64Value(root, "generation", &stat->generation_number)); string updated; TF_RETURN_IF_ERROR(GetStringValue(root, "updated", &updated)); TF_RETURN_IF_ERROR(ParseRfc3339Time(updated, &(stat->base.mtime_nsec))); VLOG(1) << "Stat of: gs: << " length: " << stat->base.length << " generation: " << stat->generation_number << "; mtime_nsec: " << stat->base.mtime_nsec << "; updated: " << updated; if (absl::EndsWith(fname, "/")) { stat->base.is_directory = true; } else { stat->base.is_directory = false; } return absl::OkStatus(); } absl::Status GcsFileSystem::StatForObject(const string& fname, const string& bucket, const string& object, GcsFileStat* stat) { if (object.empty()) { return errors::InvalidArgument(strings::Printf( "'object' must be a non-empty string. (File: %s)", fname.c_str())); } TF_RETURN_IF_ERROR(stat_cache_->LookupOrCompute( fname, stat, [this, &bucket, &object](const string& fname, GcsFileStat* stat) { return UncachedStatForObject(fname, bucket, object, stat); })); return absl::OkStatus(); } absl::Status GcsFileSystem::BucketExists(const string& bucket, bool* result) { const absl::Status status = GetBucketMetadata(bucket, nullptr); switch (static_cast<absl::StatusCode>(status.code())) { case absl::StatusCode::kOk: *result = true; return absl::OkStatus(); case absl::StatusCode::kNotFound: *result = false; return absl::OkStatus(); default: return status; } } absl::Status GcsFileSystem::CheckBucketLocationConstraint( const string& bucket) { if (allowed_locations_.empty()) { return absl::OkStatus(); } if (allowed_locations_.erase(kDetectZoneSentinelValue) == 1) { string zone; TF_RETURN_IF_ERROR(zone_provider_->GetZone(&zone)); allowed_locations_.insert(ZoneToRegion(&zone)); } string location; TF_RETURN_IF_ERROR(GetBucketLocation(bucket, &location)); if (allowed_locations_.find(location) != allowed_locations_.end()) { return absl::OkStatus(); } return errors::FailedPrecondition(strings::Printf( "Bucket '%s' is in '%s' location, allowed locations are: (%s).", bucket.c_str(), location.c_str(), absl::StrJoin(allowed_locations_, ", ").c_str())); } absl::Status GcsFileSystem::GetBucketLocation(const string& bucket, string* location) { auto compute_func = [this](const string& bucket, string* location) { std::vector<char> result_buffer; absl::Status status = GetBucketMetadata(bucket, &result_buffer); Json::Value result; TF_RETURN_IF_ERROR(ParseJson(result_buffer, &result)); string bucket_location; TF_RETURN_IF_ERROR( GetStringValue(result, kBucketMetadataLocationKey, &bucket_location)); *location = absl::AsciiStrToLower(bucket_location); return absl::OkStatus(); }; TF_RETURN_IF_ERROR( bucket_location_cache_->LookupOrCompute(bucket, location, compute_func)); return absl::OkStatus(); } absl::Status GcsFileSystem::GetBucketMetadata( const string& bucket, std::vector<char>* result_buffer) { std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); request->SetUri(strings::StrCat(kGcsUriBase, "b/", bucket)); if (result_buffer != nullptr) { request->SetResultBuffer(result_buffer); } request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); return request->Send(); } absl::Status GcsFileSystem::FolderExists(const string& dirname, bool* result) { StatCache::ComputeFunc compute_func = [this](const string& dirname, GcsFileStat* stat) { std::vector<string> children; TF_RETURN_IF_ERROR( GetChildrenBounded(dirname, 1, &children, true , true )); if (!children.empty()) { stat->base = DIRECTORY_STAT; return absl::OkStatus(); } else { return errors::InvalidArgument("Not a directory!"); } }; GcsFileStat stat; absl::Status s = stat_cache_->LookupOrCompute(MaybeAppendSlash(dirname), &stat, compute_func); if (s.ok()) { *result = stat.base.is_directory; return absl::OkStatus(); } if (absl::IsInvalidArgument(s)) { *result = false; return absl::OkStatus(); } return s; } absl::Status GcsFileSystem::GetChildren(const string& dirname, TransactionToken* token, std::vector<string>* result) { return GetChildrenBounded(dirname, UINT64_MAX, result, false , false ); } absl::Status GcsFileSystem::GetMatchingPaths(const string& pattern, TransactionToken* token, std::vector<string>* results) { MatchingPathsCache::ComputeFunc compute_func = [this](const string& pattern, std::vector<string>* results) { results->clear(); const string& fixed_prefix = pattern.substr(0, pattern.find_first_of("*?[\\")); const string dir(this->Dirname(fixed_prefix)); if (dir.empty()) { return errors::InvalidArgument( "A GCS pattern doesn't have a bucket name: ", pattern); } std::vector<string> all_files; TF_RETURN_IF_ERROR(GetChildrenBounded( dir, UINT64_MAX, &all_files, true , false )); const auto& files_and_folders = AddAllSubpaths(all_files); const absl::string_view dir_no_slash = absl::StripSuffix(dir, "/"); for (const auto& path : files_and_folders) { const string full_path = strings::StrCat(dir_no_slash, "/", path); if (this->Match(full_path, pattern)) { results->push_back(full_path); } } return absl::OkStatus(); }; TF_RETURN_IF_ERROR( matching_paths_cache_->LookupOrCompute(pattern, results, compute_func)); return absl::OkStatus(); } absl::Status GcsFileSystem::GetChildrenBounded( const string& dirname, uint64 max_results, std::vector<string>* result, bool recursive, bool include_self_directory_marker) { if (!result) { return errors::InvalidArgument("'result' cannot be null"); } string bucket, object_prefix; TF_RETURN_IF_ERROR( ParseGcsPath(MaybeAppendSlash(dirname), true, &bucket, &object_prefix)); string nextPageToken; uint64 retrieved_results = 0; while (true) { std::vector<char> output_buffer; std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); auto uri = strings::StrCat(kGcsUriBase, "b/", bucket, "/o"); if (recursive) { uri = strings::StrCat(uri, "?fields=items%2Fname%2CnextPageToken"); } else { uri = strings::StrCat(uri, "?fields=items%2Fname%2Cprefixes%2CnextPageToken"); uri = strings::StrCat(uri, "&delimiter=%2F"); } if (!object_prefix.empty()) { uri = strings::StrCat(uri, "&prefix=", request->EscapeString(object_prefix)); } if (!nextPageToken.empty()) { uri = strings::StrCat( uri, "&pageToken=", request->EscapeString(nextPageToken)); } if (max_results - retrieved_results < kGetChildrenDefaultPageSize) { uri = strings::StrCat(uri, "&maxResults=", max_results - retrieved_results); } request->SetUri(uri); request->SetResultBuffer(&output_buffer); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when reading ", dirname); Json::Value root; TF_RETURN_IF_ERROR(ParseJson(output_buffer, &root)); const auto items = root.get("items", Json::Value::null); if (!items.isNull()) { if (!items.isArray()) { return errors::Internal( "Expected an array 'items' in the GCS response."); } for (size_t i = 0; i < items.size(); i++) { const auto item = items.get(i, Json::Value::null); if (!item.isObject()) { return errors::Internal( "Unexpected JSON format: 'items' should be a list of objects."); } string name; TF_RETURN_IF_ERROR(GetStringValue(item, "name", &name)); absl::string_view relative_path(name); if (!absl::ConsumePrefix(&relative_path, object_prefix)) { return errors::Internal(strings::StrCat( "Unexpected response: the returned file name ", name, " doesn't match the prefix ", object_prefix)); } if (!relative_path.empty() || include_self_directory_marker) { result->emplace_back(relative_path); } if (++retrieved_results >= max_results) { return absl::OkStatus(); } } } const auto prefixes = root.get("prefixes", Json::Value::null); if (!prefixes.isNull()) { if (!prefixes.isArray()) { return errors::Internal( "'prefixes' was expected to be an array in the GCS response."); } for (size_t i = 0; i < prefixes.size(); i++) { const auto prefix = prefixes.get(i, Json::Value::null); if (prefix.isNull() || !prefix.isString()) { return errors::Internal( "'prefixes' was expected to be an array of strings in the GCS " "response."); } const string& prefix_str = prefix.asString(); absl::string_view relative_path(prefix_str); if (!absl::ConsumePrefix(&relative_path, object_prefix)) { return errors::Internal( "Unexpected response: the returned folder name ", prefix_str, " doesn't match the prefix ", object_prefix); } result->emplace_back(relative_path); if (++retrieved_results >= max_results) { return absl::OkStatus(); } } } const auto token = root.get("nextPageToken", Json::Value::null); if (token.isNull()) { return absl::OkStatus(); } if (!token.isString()) { return errors::Internal( "Unexpected response: nextPageToken is not a string"); } nextPageToken = token.asString(); } } absl::Status GcsFileSystem::Stat(const string& fname, TransactionToken* token, FileStatistics* stat) { if (!stat) { return errors::Internal("'stat' cannot be nullptr."); } string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, true, &bucket, &object)); if (object.empty()) { bool is_bucket; TF_RETURN_IF_ERROR(BucketExists(bucket, &is_bucket)); if (is_bucket) { *stat = DIRECTORY_STAT; return absl::OkStatus(); } return errors::NotFound("The specified bucket ", fname, " was not found."); } GcsFileStat gcs_stat; const absl::Status status = StatForObject(fname, bucket, object, &gcs_stat); if (status.ok()) { *stat = gcs_stat.base; return absl::OkStatus(); } if (!absl::IsNotFound(status)) { return status; } bool is_folder; TF_RETURN_IF_ERROR(FolderExists(fname, &is_folder)); if (is_folder) { *stat = DIRECTORY_STAT; return absl::OkStatus(); } return errors::NotFound("The specified path ", fname, " was not found."); } absl::Status GcsFileSystem::DeleteFile(const string& fname, TransactionToken* token) { string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, false, &bucket, &object)); std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); request->SetUri(strings::StrCat(kGcsUriBase, "b/", bucket, "/o/", request->EscapeString(object))); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); request->SetDeleteRequest(); TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when deleting ", fname); ClearFileCaches(fname); return absl::OkStatus(); } absl::Status GcsFileSystem::CreateDir(const string& dirname, TransactionToken* token) { string dirname_with_slash = MaybeAppendSlash(dirname); VLOG(3) << "CreateDir: creating directory with dirname: " << dirname << " and dirname_with_slash: " << dirname_with_slash; string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(dirname_with_slash, true, &bucket, &object)); if (object.empty()) { bool is_bucket; TF_RETURN_IF_ERROR(BucketExists(bucket, &is_bucket)); return is_bucket ? absl::OkStatus() : errors::NotFound("The specified bucket ", dirname_with_slash, " was not found."); } if (FileExists(dirname_with_slash, token).ok()) { VLOG(3) << "CreateDir: directory already exists, not uploading " << dirname; return errors::AlreadyExists(dirname); } std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); request->SetUri(strings::StrCat( kGcsUploadUriBase, "b/", bucket, "/o?uploadType=media&name=", request->EscapeString(object), "&ifGenerationMatch=0")); request->SetPostEmptyBody(); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); const absl::Status& status = request->Send(); if (status.ok()) { VLOG(3) << "CreateDir: finished uploading directory " << dirname; return absl::OkStatus(); } if (request->GetResponseCode() != HTTP_CODE_PRECONDITION_FAILED) { TF_RETURN_WITH_CONTEXT_IF_ERROR(status, " when uploading ", dirname_with_slash); } VLOG(3) << "Ignoring directory already exists on object " << dirname_with_slash; return errors::AlreadyExists(dirname); } absl::Status GcsFileSystem::DeleteDir(const string& dirname, TransactionToken* token) { std::vector<string> children; TF_RETURN_IF_ERROR( GetChildrenBounded(dirname, 2, &children, true , true )); if (children.size() > 1 || (children.size() == 1 && !children[0].empty())) { return errors::FailedPrecondition("Cannot delete a non-empty directory."); } if (children.size() == 1 && children[0].empty()) { return DeleteFile(MaybeAppendSlash(dirname), token); } return absl::OkStatus(); } absl::Status GcsFileSystem::GetFileSize(const string& fname, TransactionToken* token, uint64* file_size) { if (!file_size) { return errors::Internal("'file_size' cannot be nullptr."); } string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, false, &bucket, &object)); FileStatistics stat; TF_RETURN_IF_ERROR(Stat(fname, token, &stat)); *file_size = stat.length; return absl::OkStatus(); } absl::Status GcsFileSystem::RenameFile(const string& src, const string& target, TransactionToken* token) { if (!IsDirectory(src, token).ok()) { return RenameObject(src, target); } std::vector<string> children; TF_RETURN_IF_ERROR( GetChildrenBounded(src, UINT64_MAX, &children, true , true )); for (const string& subpath : children) { TF_RETURN_IF_ERROR( RenameObject(JoinGcsPath(src, subpath), JoinGcsPath(target, subpath))); } return absl::OkStatus(); } absl::Status GcsFileSystem::RenameObject(const string& src, const string& target) { VLOG(3) << "RenameObject: started gs: string src_bucket, src_object, target_bucket, target_object; TF_RETURN_IF_ERROR(ParseGcsPath(src, false, &src_bucket, &src_object)); TF_RETURN_IF_ERROR( ParseGcsPath(target, false, &target_bucket, &target_object)); std::unique_ptr<HttpRequest> request; TF_RETURN_IF_ERROR(CreateHttpRequest(&request)); request->SetUri(strings::StrCat(kGcsUriBase, "b/", src_bucket, "/o/", request->EscapeString(src_object), "/rewriteTo/b/", target_bucket, "/o/", request->EscapeString(target_object))); request->SetPostEmptyBody(); request->SetTimeouts(timeouts_.connect, timeouts_.idle, timeouts_.metadata); std::vector<char> output_buffer; request->SetResultBuffer(&output_buffer); TF_RETURN_WITH_CONTEXT_IF_ERROR(request->Send(), " when renaming ", src, " to ", target); ClearFileCaches(target); Json::Value root; TF_RETURN_IF_ERROR(ParseJson(output_buffer, &root)); bool done; TF_RETURN_IF_ERROR(GetBoolValue(root, "done", &done)); if (!done) { return errors::Unimplemented( "Couldn't rename ", src, " to ", target, ": moving large files between buckets with different " "locations or storage classes is not supported."); } VLOG(3) << "RenameObject: finished from: gs: return RetryingUtils::DeleteWithRetries( [this, &src]() { return DeleteFile(src, nullptr); }, retry_config_); } absl::Status GcsFileSystem::IsDirectory(const string& fname, TransactionToken* token) { string bucket, object; TF_RETURN_IF_ERROR(ParseGcsPath(fname, true, &bucket, &object)); if (object.empty()) { bool is_bucket; TF_RETURN_IF_ERROR(BucketExists(bucket, &is_bucket)); if (is_bucket) { return absl::OkStatus(); } return errors::NotFound("The specified bucket gs: " was not found."); } bool is_folder; TF_RETURN_IF_ERROR(FolderExists(fname, &is_folder)); if (is_folder) { return absl::OkStatus(); } bool is_object; TF_RETURN_IF_ERROR(ObjectExists(fname, bucket, object, &is_object)); if (is_object) { return errors::FailedPrecondition("The specified path ", fname, " is not a directory."); } return errors::NotFound("The specified path ", fname, " was not found."); } absl::Status GcsFileSystem::DeleteRecursively(const string& dirname, TransactionToken* token, int64_t* undeleted_files, int64_t* undeleted_dirs) { if (!undeleted_files || !undeleted_dirs) { return errors::Internal( "'undeleted_files' and 'undeleted_dirs' cannot be nullptr."); } *undeleted_files = 0; *undeleted_dirs = 0; if (!IsDirectory(dirname, token).ok()) { *undeleted_dirs = 1; return absl::Status( absl::StatusCode::kNotFound, strings::StrCat(dirname, " doesn't exist or not a directory.")); } std::vector<string> all_objects; TF_RETURN_IF_ERROR(GetChildrenBounded( dirname, UINT64_MAX, &all_objects, true , true )); for (const string& object : all_objects) { const string& full_path = JoinGcsPath(dirname, object); const auto& delete_file_status = RetryingUtils::DeleteWithRetries( [this, &full_path, token]() { return DeleteFile(full_path, token); }, retry_config_); if (!delete_file_status.ok()) { if (IsDirectory(full_path, token).ok()) { (*undeleted_dirs)++; } else { (*undeleted_files)++; } } } return absl::OkStatus(); } void GcsFileSystem::FlushCaches(TransactionToken* token) { tf_shared_lock l(block_cache_lock_); file_block_cache_->Flush(); stat_cache_->Clear(); matching_paths_cache_->Clear(); bucket_location_cache_->Clear(); } void GcsFileSystem::SetStats(GcsStatsInterface* stats) { CHECK(stats_ == nullptr) << "SetStats() has already been called."; CHECK(stats != nullptr); mutex_lock l(block_cache_lock_); stats_ = stats; stats_->Configure(this, &throttle_, file_block_cache_.get()); } void GcsFileSystem::SetCacheStats(FileBlockCacheStatsInterface* cache_stats) { tf_shared_lock l(block_cache_lock_); if (file_block_cache_ == nullptr) { LOG(ERROR) << "Tried to set cache stats of non-initialized file block " "cache object. This may result in not exporting the intended " "monitoring data"; return; } file_block_cache_->SetStats(cache_stats); } void GcsFileSystem::SetAuthProvider( std::unique_ptr<AuthProvider> auth_provider) { mutex_lock l(mu_); auth_provider_ = std::move(auth_provider); } absl::Status GcsFileSystem::CreateHttpRequest( std::unique_ptr<HttpRequest>* request) { std::unique_ptr<HttpRequest> new_request{http_request_factory_->Create()}; if (dns_cache_) { dns_cache_->AnnotateRequest(new_request.get()); } string auth_token; { tf_shared_lock l(mu_); TF_RETURN_IF_ERROR( AuthProvider::GetToken(auth_provider_.get(), &auth_token)); } new_request->AddAuthBearerHeader(auth_token); if (additional_header_) { new_request->AddHeader(additional_header_->first, additional_header_->second); } if (stats_ != nullptr) { new_request->SetRequestStats(stats_->HttpStats()); } if (!throttle_.AdmitRequest()) { return errors::Unavailable("Request throttled"); } *request = std::move(new_request); return absl::OkStatus(); } RetryingGcsFileSystem::RetryingGcsFileSystem() : RetryingFileSystem(std::make_unique<GcsFileSystem>(), RetryConfig(GetGcsRetryConfig())) {} } REGISTER_LEGACY_FILE_SYSTEM("gs", ::tsl::RetryingGcsFileSystem);
#include "tsl/platform/cloud/gcs_file_system.h" #include <fstream> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/errors.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" #ifdef PLATFORM_WINDOWS #undef DeleteFile #endif namespace tsl { namespace { static GcsFileSystem::TimeoutConfig kTestTimeoutConfig(5, 1, 10, 20, 30); static RetryConfig kTestRetryConfig(0 ); static std::unordered_set<string>* kAllowedLocationsDefault = new std::unordered_set<string>(); static std::unordered_set<string>* kAllowedLocationsAuto = new std::unordered_set<string>({"auto"}); class FakeAuthProvider : public AuthProvider { public: absl::Status GetToken(string* token) override { *token = "fake_token"; return absl::OkStatus(); } }; class FakeZoneProvider : public ZoneProvider { public: absl::Status GetZone(string* zone) override { *zone = "us-east1-b"; return absl::OkStatus(); } }; TEST(GcsFileSystemTest, NewRandomAccessFile_NoBlockCache) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-5\n" "Timeouts: 5 1 20\n", "012345"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 6-11\n" "Timeouts: 5 1 20\n", "6789")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[6]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("012345", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("6789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered) { std::vector<HttpRequest*> requests({ new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "0123456789"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 10-19\n" "Timeouts: 5 1 20\n", ""), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[6]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("012345", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("6789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_Errors) { std::vector<HttpRequest*> requests({ new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "Server Not", errors::Unavailable("important HTTP error 308"), nullptr, {}, 308), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 6-15\n" "Timeouts: 5 1 20\n", "123"), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[6]; absl::string_view result; EXPECT_TRUE( errors::IsUnavailable(file->Read(0, sizeof(scratch), &result, scratch))); EXPECT_EQ("", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("123", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_ReadAtEOF) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "0123456789"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 10-19\n" "Timeouts: 5 1 20\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[10]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("0123456789", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_CachedOutOfRange) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "012345678")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[5]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("01234", result); TF_EXPECT_OK(file->Read(4, sizeof(scratch), &result, scratch)); EXPECT_EQ("45678", result); EXPECT_TRUE( errors::IsOutOfRange(file->Read(5, sizeof(scratch), &result, scratch))); EXPECT_EQ("5678", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_CachedNotSequential) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 1-10\n" "Timeouts: 5 1 20\n", "12345678"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "012345678")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[5]; absl::string_view result; TF_EXPECT_OK(file->Read(1, sizeof(scratch), &result, scratch)); EXPECT_EQ("12345", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("01234", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_Growing) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "012345678"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 9-18\n" "Timeouts: 5 1 20\n", "9")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[10]; absl::string_view result; EXPECT_TRUE( errors::IsOutOfRange(file->Read(0, sizeof(scratch), &result, scratch))); EXPECT_EQ("012345678", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("0123456789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_ReadBackwards) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 5-14\n" "Timeouts: 5 1 20\n", "56789"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "0123456789")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: absl::string_view filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[10]; absl::string_view result; EXPECT_TRUE( errors::IsOutOfRange(file->Read(5, sizeof(scratch), &result, scratch))); EXPECT_EQ("56789", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("0123456789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintInSameLocation) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsAuto, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: } TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintCaching) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsAuto, nullptr , false ); std::unique_ptr<RandomAccessFile> file; string bucket = "gs: string another_bucket = "gs: TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(another_bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(another_bucket, nullptr, &file)); fs.FlushCaches(nullptr); TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintInDifferentLocation) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"BARFOO" })")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsAuto, nullptr , false ); std::unique_ptr<RandomAccessFile> file; EXPECT_EQ( errors::FailedPrecondition( "Bucket 'bucket' is in 'barfoo' location, allowed locations " "are: (us-east1)."), fs.NewRandomAccessFile("gs: } TEST(GcsFileSystemTest, NewRandomAccessFile_NoBlockCache_DifferentN) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-2\n" "Timeouts: 5 1 20\n", "012"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 3-12\n" "Timeouts: 5 1 20\n", "3456789")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char small_scratch[3]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(small_scratch), &result, small_scratch)); EXPECT_EQ("012", result); char large_scratch[10]; EXPECT_TRUE(errors::IsOutOfRange(file->Read( sizeof(small_scratch), sizeof(large_scratch), &result, large_scratch))); EXPECT_EQ("3456789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"15\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "012345678"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 9-17\n" "Timeouts: 5 1 20\n", "9abcde"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 18-26\n" "Timeouts: 5 1 20\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 , 18 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; absl::string_view result; { std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK(fs.NewRandomAccessFile("gs: nullptr, &file)); scratch[5] = 'x'; TF_EXPECT_OK(file->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); EXPECT_EQ(scratch[5], 'x'); TF_EXPECT_OK(file->Read(4, 4, &result, scratch)); EXPECT_EQ("4567", result); TF_EXPECT_OK(file->Read(6, 5, &result, scratch)); EXPECT_EQ("6789a", result); EXPECT_TRUE(errors::IsOutOfRange(file->Read(6, 10, &result, scratch))); EXPECT_EQ("6789abcde", result); EXPECT_TRUE(errors::IsOutOfRange(file->Read(20, 10, &result, scratch))); EXPECT_TRUE(result.empty()); TF_EXPECT_OK(file->Read(0, 4, &result, scratch)); } EXPECT_EQ("0123", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_Flush) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"15\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "012345678"), new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"15\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "012345678")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 , 18 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; absl::string_view result; std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: scratch[5] = 'x'; TF_EXPECT_OK(file->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); EXPECT_EQ(scratch[5], 'x'); fs.FlushCaches(nullptr); TF_EXPECT_OK(file->Read(4, 4, &result, scratch)); EXPECT_EQ("4567", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_MaxStaleness) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "object?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"16\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Range: 0-7\n" "Timeouts: 5 1 20\n", "01234567"), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Range: 8-15\n" "Timeouts: 5 1 20\n", "89abcdef")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 8 , 16 , 3600 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; absl::string_view result; for (int i = 0; i < 10; i++) { std::unique_ptr<RandomAccessFile> file1; std::unique_ptr<RandomAccessFile> file2; TF_EXPECT_OK(fs.NewRandomAccessFile("gs: TF_EXPECT_OK(fs.NewRandomAccessFile("gs: TF_EXPECT_OK(file1->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); TF_EXPECT_OK(file2->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); TF_EXPECT_OK(file2->Read(8, 8, &result, scratch)); EXPECT_EQ("89abcdef", result); TF_EXPECT_OK(file1->Read(8, 8, &result, scratch)); EXPECT_EQ("89abcdef", result); } } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_FileSignatureChanges) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"5\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "01234"), new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"5\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "43210")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 , 18 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char scratch[5]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("01234", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("43210", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_NoObjectName) { std::vector<HttpRequest*> requests; GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; EXPECT_TRUE(errors::IsInvalidArgument( fs.NewRandomAccessFile("gs: } TEST(GcsFileSystemTest, NewRandomAccessFile_InconsistentRead) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"6\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-5\n" "Timeouts: 5 1 20\n", "012")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 1e3 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; TF_ASSERT_OK(fs.Stat("gs: std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK( fs.NewRandomAccessFile("gs: char scratch[6]; absl::string_view result; EXPECT_TRUE( errors::IsInternal(file->Read(0, sizeof(scratch), &result, scratch))); } TEST(GcsFileSystemTest, NewWritableFile) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Fwriteable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"16\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-7\n" "Timeouts: 5 1 20\n", "01234567"), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", ""), new FakeHttpRequest( "Uri: https: "path%2Fwriteable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"33\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:15:34.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-7\n" "Timeouts: 5 1 20\n", "01234567")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 8 , 8 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> rfile; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char scratch[100]; absl::string_view result; TF_EXPECT_OK(rfile->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); std::unique_ptr<WritableFile> wfile; TF_EXPECT_OK( fs.NewWritableFile("gs: TF_EXPECT_OK(wfile->Append("content1,")); int64_t pos; TF_EXPECT_OK(wfile->Tell(&pos)); EXPECT_EQ(9, pos); TF_EXPECT_OK(wfile->Append("content2")); TF_EXPECT_OK(wfile->Flush()); TF_EXPECT_OK(rfile->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); TF_EXPECT_OK(wfile->Flush()); TF_EXPECT_OK(wfile->Sync()); TF_EXPECT_OK(wfile->Close()); } TEST(GcsFileSystemTest, NewWritableFile_ResumeUploadSucceeds) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable.txt\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header Content-Range: bytes */17\n" "Put: yes\n", "", errors::Unavailable("308"), nullptr, {{"Range", "0-10"}}, 308), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 11-16/17\n" "Timeouts: 5 1 30\n" "Put body: ntent2\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header Content-Range: bytes */17\n" "Put: yes\n", "", errors::Unavailable("308"), nullptr, {{"Range", "bytes=0-12"}}, 308), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 13-16/17\n" "Timeouts: 5 1 30\n" "Put body: ent2\n", "", errors::Unavailable("308"), 308), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header Content-Range: bytes */17\n" "Put: yes\n", "", errors::Unavailable("308"), nullptr, {{"Range", "bytes=0-14"}}, 308), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 15-16/17\n" "Timeouts: 5 1 30\n" "Put body: t2\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> file; TF_EXPECT_OK( fs.NewWritableFile("gs: TF_EXPECT_OK(file->Append("content1,")); TF_EXPECT_OK(file->Append("content2")); TF_EXPECT_OK(file->Close()); } TEST(GcsFileSystemTest, NewWritableFile_ResumeUploadSucceedsOnGetStatus) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Fwriteable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"16\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-7\n" "Timeouts: 5 1 20\n", "01234567"), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header Content-Range: bytes */17\n" "Put: yes\n", "", absl::OkStatus(), nullptr, {}, 201), new FakeHttpRequest( "Uri: https: "path%2Fwriteable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"33\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:19:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-7\n" "Timeouts: 5 1 20\n", "01234567")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 8 , 8 , 3600 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> rfile; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char scratch[100]; absl::string_view result; TF_EXPECT_OK(rfile->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); std::unique_ptr<WritableFile> wfile; TF_EXPECT_OK( fs.NewWritableFile("gs: TF_EXPECT_OK(wfile->Append("content1,")); TF_EXPECT_OK(wfile->Append("content2")); TF_EXPECT_OK(rfile->Read(4, 4, &result, scratch)); EXPECT_EQ("4567", result); TF_EXPECT_OK(wfile->Close()); TF_EXPECT_OK(rfile->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); } TEST(GcsFileSystemTest, NewWritableFile_ResumeUploadAllAttemptsFail) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable.txt\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", "", errors::Unavailable("503"), 503)}); for (int i = 0; i < 10; i++) { requests.emplace_back( new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header Content-Range: bytes */17\n" "Put: yes\n", "", errors::Unavailable("important HTTP error 308"), nullptr, {{"Range", "0-10"}}, 308)); requests.emplace_back(new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 11-16/17\n" "Timeouts: 5 1 30\n" "Put body: ntent2\n", "", errors::Unavailable("important HTTP error 503"), 503)); } requests.emplace_back(new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable.txt\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: requests.emplace_back( new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", "")); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , RetryConfig(2 ), kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> file; TF_EXPECT_OK( fs.NewWritableFile("gs: TF_EXPECT_OK(file->Append("content1,")); TF_EXPECT_OK(file->Append("content2")); const auto& status = file->Close(); EXPECT_TRUE(errors::IsAborted(status)); EXPECT_TRUE( absl::StrContains(status.message(), "All 10 retry attempts failed. The last failure: " "important HTTP error 503")) << status; } TEST(GcsFileSystemTest, NewWritableFile_UploadReturns410) { std::vector<string> results; TF_EXPECT_OK( Env::Default()->GetMatchingPaths("/tmp/tmp_file_tensorflow*", &results)); const int64_t tmp_files_before = results.size(); std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable.txt\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", "", errors::NotFound("important HTTP error 410"), 410), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fwriteable.txt\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); { std::unique_ptr<WritableFile> file; TF_EXPECT_OK( fs.NewWritableFile("gs: TF_EXPECT_OK(file->Append("content1,")); TF_EXPECT_OK(file->Append("content2")); const auto& status = file->Close(); EXPECT_TRUE(errors::IsUnavailable(status)); EXPECT_TRUE( absl::StrContains(status.message(), "Upload to gs: "caused by: important HTTP error 410")) << status; EXPECT_TRUE(absl::StrContains( status.message(), "when uploading gs: << status; } results.clear(); TF_EXPECT_OK( Env::Default()->GetMatchingPaths("/tmp/tmp_file_tensorflow*", &results)); EXPECT_EQ(tmp_files_before, results.size()); } TEST(GcsFileSystemTest, NewWritableFile_NoObjectName) { std::vector<HttpRequest*> requests; GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> file; EXPECT_TRUE(errors::IsInvalidArgument( fs.NewWritableFile("gs: } TEST(GcsFileSystemTest, NewAppendableFile) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Fappendable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-1048575\n" "Timeouts: 5 1 20\n", "content1,"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-31\n" "Timeouts: 5 1 20\n", "content1,"), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fappendable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 17\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-16/17\n" "Timeouts: 5 1 30\n" "Put body: content1,content2\n", ""), new FakeHttpRequest( "Uri: https: "path%2Fappendable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:25:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-31\n" "Timeouts: 5 1 20\n", "01234567")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 32 , 32 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> wfile; TF_EXPECT_OK( fs.NewAppendableFile("gs: TF_EXPECT_OK(wfile->Append("content2")); std::unique_ptr<RandomAccessFile> rfile; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char scratch[100]; absl::string_view result; TF_EXPECT_OK(rfile->Read(0, 8, &result, scratch)); EXPECT_EQ("content1", result); TF_EXPECT_OK(wfile->Close()); TF_EXPECT_OK(rfile->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); } TEST(GcsFileSystemTest, NewAppendableFile_NoObjectName) { std::vector<HttpRequest*> requests; GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> file; EXPECT_TRUE(errors::IsInvalidArgument( fs.NewAppendableFile("gs: } TEST(GcsFileSystemTest, NewAppendableFile_ObjectDoesNotExist) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-1048575\n" "Timeouts: 5 1 20\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "?uploadType=resumable&name=filename\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 0\n" "Post: yes\n" "Timeouts: 5 1 10\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> file; TF_EXPECT_OK(fs.NewAppendableFile("gs: } TEST(GcsFileSystemTest, NewReadOnlyMemoryRegionFromFile) { const string content = "file content"; std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Frandom_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"", content.size(), "\"", ", \"generation\": \"1\"", ", \"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( strings::StrCat("Uri: https: "path%2Frandom_access.txt\n" "Auth Token: fake_token\n" "Range: 0-", content.size() - 1, "\n", "Timeouts: 5 1 20\n"), content)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<ReadOnlyMemoryRegion> region; TF_EXPECT_OK(fs.NewReadOnlyMemoryRegionFromFile( "gs: EXPECT_EQ(content, absl::string_view(reinterpret_cast<const char*>(region->data()), region->length())); } TEST(GcsFileSystemTest, NewReadOnlyMemoryRegionFromFile_NoObjectName) { std::vector<HttpRequest*> requests; GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<ReadOnlyMemoryRegion> region; EXPECT_TRUE(errors::IsInvalidArgument( fs.NewReadOnlyMemoryRegionFromFile("gs: } TEST(GcsFileSystemTest, FileExists_YesAsObject) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "path%2Ffile1.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.FileExists("gs: } TEST(GcsFileSystemTest, FileExists_YesAsFolder) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Fsubfolder?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsubfolder%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/subfolder/\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.FileExists("gs: } TEST(GcsFileSystemTest, FileExists_YesAsBucket) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"size\": \"100\"}"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"size\": \"100\"}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.FileExists("gs: TF_EXPECT_OK(fs.FileExists("gs: } TEST(GcsFileSystemTest, FileExists_NotAsObjectOrFolder) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Ffile1.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Ffile1.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": []}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_TRUE( errors::IsNotFound(fs.FileExists("gs: } TEST(GcsFileSystemTest, FileExists_NotAsBucket) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_TRUE(absl::IsNotFound(fs.FileExists("gs: EXPECT_TRUE(absl::IsNotFound(fs.FileExists("gs: } TEST(GcsFileSystemTest, FileExists_StatCache) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Ffile1.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "path%2Fsubfolder%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsubfolder%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/subfolder/\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); for (int i = 0; i < 10; i++) { TF_EXPECT_OK(fs.FileExists("gs: TF_EXPECT_OK(fs.FileExists("gs: } } TEST(GcsFileSystemTest, FileExists_DirectoryMark) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "dir%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"5\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.FileExists("gs: TF_EXPECT_OK(fs.IsDirectory("gs: } TEST(GcsFileSystemTest, GetChildren_NoItems) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&prefix=" "path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"prefixes\": [\"path/subpath/\"]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(std::vector<string>({"subpath/"}), children); } TEST(GcsFileSystemTest, GetChildren_ThreeFiles) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&prefix=" "path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }," " { \"name\": \"path/file3.txt\" }]," "\"prefixes\": [\"path/subpath/\"]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(std::vector<string>({"file1.txt", "file3.txt", "subpath/"}), children); } TEST(GcsFileSystemTest, GetChildren_SelfDirectoryMarker) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&prefix=" "path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/\" }," " { \"name\": \"path/file3.txt\" }]," "\"prefixes\": [\"path/subpath/\"]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(std::vector<string>({"file3.txt", "subpath/"}), children); } TEST(GcsFileSystemTest, GetChildren_ThreeFiles_NoSlash) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&prefix=" "path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }," " { \"name\": \"path/file3.txt\" }]," "\"prefixes\": [\"path/subpath/\"]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(std::vector<string>({"file1.txt", "file3.txt", "subpath/"}), children); } TEST(GcsFileSystemTest, GetChildren_Root) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(0, children.size()); } TEST(GcsFileSystemTest, GetChildren_Empty) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&prefix=" "path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(0, children.size()); } TEST(GcsFileSystemTest, GetChildren_Pagination) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&" "prefix=path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"nextPageToken\": \"ABCD==\", " "\"items\": [ " " { \"name\": \"path/file1.txt\" }," " { \"name\": \"path/file3.txt\" }]," "\"prefixes\": [\"path/subpath/\"]}"), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2Cprefixes%2CnextPageToken&delimiter=%2F&" "prefix=path%2F" "&pageToken=ABCD==\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file4.txt\" }," " { \"name\": \"path/file5.txt\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> children; TF_EXPECT_OK(fs.GetChildren("gs: EXPECT_EQ(std::vector<string>({"file1.txt", "file3.txt", "subpath/", "file4.txt", "file5.txt"}), children); } TEST(GcsFileSystemTest, GetMatchingPaths_NoWildcard) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsubpath%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/subpath/file2.txt\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: nullptr, &result)); EXPECT_EQ(std::vector<string>({"gs: result); } TEST(GcsFileSystemTest, GetMatchingPaths_BucketAndWildcard) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }," " { \"name\": \"path/subpath/file2.txt\" }," " { \"name\": \"path/file3.txt\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK( fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; TF_EXPECT_OK( fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::vector<string> result; EXPECT_TRUE(errors::IsInvalidArgument( fs.GetMatchingPaths("gs:/, 0 , 0 , 0 , 0 , 3600 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); for (int i = 0; i < 10; i++) { std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: nullptr, &result)); EXPECT_EQ(std::vector<string>({"gs: result); TF_EXPECT_OK(fs.GetMatchingPaths("gs: 0 , 0 , 0 , 0 , 3600 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); for (int i = 0; i < 10; i++) { std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: nullptr, &result)); EXPECT_EQ(std::vector<string>({"gs: result); } fs.FlushCaches(nullptr); for (int i = 0; i < 10; i++) { std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: nullptr, &result)); EXPECT_EQ(std::vector<string>({"gs: result); } } TEST(GcsFileSystemTest, DeleteFile) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Ffile1.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-15\n" "Timeouts: 5 1 20\n", "01234567"), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Ffile1.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "path%2Ffile1.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:19:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-15\n" "Timeouts: 5 1 20\n", "76543210")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 16 , 16 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; absl::string_view result; std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: TF_EXPECT_OK(file->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); TF_EXPECT_OK(fs.DeleteFile("gs: TF_EXPECT_OK(file->Read(0, 8, &result, scratch)); EXPECT_EQ("76543210", result); } TEST(GcsFileSystemTest, DeleteFile_NoObjectName) { std::vector<HttpRequest*> requests; GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_TRUE( errors::IsInvalidArgument(fs.DeleteFile("gs: } TEST(GcsFileSystemTest, DeleteFile_StatCacheRemoved) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest("Uri: https: "/bucket/o/file.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=file.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 16 , 16 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat_before_deletion; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(1010, stat_before_deletion.length); TF_EXPECT_OK(fs.DeleteFile("gs: FileStatistics stat_after_deletion; EXPECT_EQ( error::Code::NOT_FOUND, fs.Stat("gs: } TEST(GcsFileSystemTest, DeleteDir_Empty) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F&maxResults=2\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.DeleteDir("gs: } TEST(GcsFileSystemTest, DeleteDir_OnlyDirMarkerLeft) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F&maxResults=2\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/\" }]}"), new FakeHttpRequest("Uri: https: "/bucket/o/path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.DeleteDir("gs: } TEST(GcsFileSystemTest, DeleteDir_BucketOnly) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "name%2CnextPageToken&maxResults=2\nAuth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.DeleteDir("gs: } TEST(GcsFileSystemTest, DeleteDir_NonEmpty) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F&maxResults=2\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_EQ(error::Code::FAILED_PRECONDITION, fs.DeleteDir("gs: } TEST(GcsFileSystemTest, GetFileSize) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); uint64 size; TF_EXPECT_OK(fs.GetFileSize("gs: EXPECT_EQ(1010, size); } TEST(GcsFileSystemTest, GetFileSize_NoObjectName) { std::vector<HttpRequest*> requests; GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); uint64 size; EXPECT_TRUE(errors::IsInvalidArgument( fs.GetFileSize("gs: } TEST(GcsFileSystemTest, RenameFile_Folder) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path1%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path1/subfolder/file1.txt\" }]}"), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path1%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path1/\" }," " { \"name\": \"path1/subfolder/file1.txt\" }," " { \"name\": \"path1/file2.txt\" }]}"), new FakeHttpRequest( "Uri: https: "path1%2F/rewriteTo/b/bucket/o/path2%2F\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": true}"), new FakeHttpRequest( "Uri: https: "path1%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "path1%2Fsubfolder%2Ffile1.txt/rewriteTo/b/bucket/o/" "path2%2Fsubfolder%2Ffile1.txt\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": true}"), new FakeHttpRequest( "Uri: https: "path1%2Fsubfolder%2Ffile1.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "path1%2Ffile2.txt/rewriteTo/b/bucket/o/path2%2Ffile2.txt\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": true}"), new FakeHttpRequest( "Uri: https: "path1%2Ffile2.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK( fs.RenameFile("gs: } TEST(GcsFileSystemTest, RenameFile_Object) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-15\n" "Timeouts: 5 1 20\n", "01234567"), new FakeHttpRequest( "Uri: https: "path%2Fdst.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-15\n" "Timeouts: 5 1 20\n", "76543210"), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsrc.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt/rewriteTo/b/bucket/o/path%2Fdst.txt\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": true}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-15\n" "Timeouts: 5 1 20\n", "89abcdef"), new FakeHttpRequest( "Uri: https: "path%2Fdst.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"2\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-15\n" "Timeouts: 5 1 20\n", "fedcba98")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 16 , 64 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; absl::string_view result; std::unique_ptr<RandomAccessFile> src; std::unique_ptr<RandomAccessFile> dst; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: TF_EXPECT_OK(src->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); TF_EXPECT_OK( fs.NewRandomAccessFile("gs: TF_EXPECT_OK(dst->Read(0, 8, &result, scratch)); EXPECT_EQ("76543210", result); TF_EXPECT_OK(fs.RenameFile("gs: "gs: TF_EXPECT_OK(src->Read(0, 8, &result, scratch)); EXPECT_EQ("89abcdef", result); TF_EXPECT_OK(dst->Read(0, 8, &result, scratch)); EXPECT_EQ("fedcba98", result); } TEST(GcsFileSystemTest, RenameFile_Object_FlushTargetStatCache) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "path%2Fdst.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1000\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsrc.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt/rewriteTo/b/bucket/o/path%2Fdst.txt\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": true}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "path%2Fdst.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat_before_renaming; TF_EXPECT_OK( fs.Stat("gs: EXPECT_EQ(1000, stat_before_renaming.length); TF_EXPECT_OK(fs.RenameFile("gs: "gs: FileStatistics stat_after_renaming; TF_EXPECT_OK( fs.Stat("gs: EXPECT_EQ(1010, stat_after_renaming.length); } TEST(GcsFileSystemTest, RenameFile_Object_DeletionRetried) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsrc.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt/rewriteTo/b/bucket/o/path%2Fdst.txt\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": true}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.RenameFile("gs: "gs: } TEST(GcsFileSystemTest, RenameFile_Object_Incomplete) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsrc.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "path%2Fsrc.txt/rewriteTo/b/bucket/o/path%2Fdst.txt\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "{\"done\": false}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_TRUE(errors::IsUnimplemented(fs.RenameFile( "gs: } TEST(GcsFileSystemTest, Stat_Object) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(1010, stat.length); EXPECT_NEAR(1461971724896, stat.mtime_nsec / 1000 / 1000, 1); EXPECT_FALSE(stat.is_directory); } TEST(GcsFileSystemTest, Stat_Folder) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "subfolder?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=subfolder%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"subfolder/\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(0, stat.length); EXPECT_EQ(0, stat.mtime_nsec); EXPECT_TRUE(stat.is_directory); } TEST(GcsFileSystemTest, Stat_ObjectOrFolderNotFound) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "path?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; EXPECT_EQ(error::Code::NOT_FOUND, fs.Stat("gs: } TEST(GcsFileSystemTest, Stat_Bucket) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(0, stat.length); EXPECT_EQ(0, stat.mtime_nsec); EXPECT_TRUE(stat.is_directory); } TEST(GcsFileSystemTest, Stat_BucketNotFound) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; EXPECT_EQ(error::Code::NOT_FOUND, fs.Stat("gs: } TEST(GcsFileSystemTest, Stat_Cache) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "subfolder%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=subfolder%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"subfolder/\" }]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); for (int i = 0; i < 10; i++) { FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(1010, stat.length); EXPECT_NEAR(1461971724896, stat.mtime_nsec / 1000 / 1000, 1); EXPECT_FALSE(stat.is_directory); TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(0, stat.length); EXPECT_EQ(0, stat.mtime_nsec); EXPECT_TRUE(stat.is_directory); } } TEST(GcsFileSystemTest, Stat_Cache_Flush) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); for (int i = 0; i < 10; i++) { FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(1010, stat.length); EXPECT_NEAR(1461971724896, stat.mtime_nsec / 1000 / 1000, 1); EXPECT_FALSE(stat.is_directory); } fs.FlushCaches(nullptr); for (int i = 0; i < 10; i++) { FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(1010, stat.length); EXPECT_NEAR(1461971724896, stat.mtime_nsec / 1000 / 1000, 1); EXPECT_FALSE(stat.is_directory); } } TEST(GcsFileSystemTest, Stat_FilenameEndingWithSlash) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "dir%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"5\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(5, stat.length); EXPECT_TRUE(stat.is_directory); } TEST(GcsFileSystemTest, IsDirectory_NotFound) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=file.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_EQ(error::Code::NOT_FOUND, fs.IsDirectory("gs: } TEST(GcsFileSystemTest, IsDirectory_NotDirectoryButObject) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=file.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_EQ(error::Code::FAILED_PRECONDITION, fs.IsDirectory("gs: } TEST(GcsFileSystemTest, IsDirectory_Yes) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=subfolder%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [{\"name\": \"subfolder/\"}]}"), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=subfolder%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [{\"name\": \"subfolder/\"}]}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.IsDirectory("gs: TF_EXPECT_OK(fs.IsDirectory("gs: } TEST(GcsFileSystemTest, IsDirectory_Bucket) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.IsDirectory("gs: TF_EXPECT_OK(fs.IsDirectory("gs: } TEST(GcsFileSystemTest, IsDirectory_BucketNotFound) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); EXPECT_EQ(error::Code::NOT_FOUND, fs.IsDirectory("gs: } TEST(GcsFileSystemTest, CreateDir_Folder) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "subpath%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "uploadType=media&name=subpath%2F&ifGenerationMatch=0\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", ""), new FakeHttpRequest( "Uri: https: "subpath%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "subpath%2F?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "uploadType=media&name=subpath%2F&ifGenerationMatch=0\n" "Auth Token: fake_token\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", errors::FailedPrecondition("412"), 412), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.CreateDir("gs: EXPECT_EQ(errors::AlreadyExists("gs: fs.CreateDir("gs: EXPECT_EQ(errors::AlreadyExists("gs: fs.CreateDir("gs: } TEST(GcsFileSystemTest, CreateDir_Bucket) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", ""), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TF_EXPECT_OK(fs.CreateDir("gs: TF_EXPECT_OK(fs.CreateDir("gs: } TEST(GcsFileSystemTest, DeleteRecursively_Ok) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }]}"), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/\" }," " { \"name\": \"path/file1.txt\" }," " { \"name\": \"path/subpath/file2.txt\" }," " { \"name\": \"path/file3.txt\" }]}"), new FakeHttpRequest("Uri: https: "/bucket/o/path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Ffile1.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "", errors::Unavailable("500"), 500), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Ffile1.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Fsubpath%2Ffile2.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Ffile3.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); int64_t undeleted_files, undeleted_dirs; TF_EXPECT_OK(fs.DeleteRecursively("gs: &undeleted_files, &undeleted_dirs)); EXPECT_EQ(0, undeleted_files); EXPECT_EQ(0, undeleted_dirs); } TEST(GcsFileSystemTest, DeleteRecursively_DeletionErrors) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }]}"), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{\"items\": [ " " { \"name\": \"path/file1.txt\" }," " { \"name\": \"path/subpath/\" }," " { \"name\": \"path/subpath/file2.txt\" }," " { \"name\": \"path/file3.txt\" }]}"), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Ffile1.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Fsubpath%2F\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Fsubpath%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"items\": [ " " { \"name\": \"path/subpath/\" }]}")), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Fsubpath%2Ffile2.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest("Uri: https: "/bucket/o/path%2Ffile3.txt\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", "", errors::NotFound("404"), 404), new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2Ffile3.txt%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "path%2Ffile3.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); int64_t undeleted_files, undeleted_dirs; TF_EXPECT_OK(fs.DeleteRecursively("gs: &undeleted_files, &undeleted_dirs)); EXPECT_EQ(1, undeleted_files); EXPECT_EQ(1, undeleted_dirs); } TEST(GcsFileSystemTest, DeleteRecursively_NotAFolder) { std::vector<HttpRequest*> requests( { new FakeHttpRequest( "Uri: https: "fields=items%2Fname%2CnextPageToken&prefix=path%2F" "&maxResults=1\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "{}"), new FakeHttpRequest( "Uri: https: "path?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", "", errors::NotFound("404"), 404)}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); int64_t undeleted_files, undeleted_dirs; EXPECT_EQ(error::Code::NOT_FOUND, fs.DeleteRecursively("gs: &undeleted_dirs) .code()); EXPECT_EQ(0, undeleted_files); EXPECT_EQ(1, undeleted_dirs); } TEST(GcsFileSystemTest, NoConstraintsEnvironmentVariableTest) { unsetenv("GCS_ALLOWED_BUCKET_LOCATIONS"); GcsFileSystem fs1; EXPECT_EQ(*kAllowedLocationsDefault, fs1.allowed_locations()); fs1.FlushCaches(nullptr); } TEST(GcsFileSystemTest, BucketLocationConstraintEnvironmentVariableTest) { unsetenv("GCS_ALLOWED_BUCKET_LOCATIONS"); setenv("GCS_ALLOWED_BUCKET_LOCATIONS", "auto", 1); GcsFileSystem fs1; EXPECT_EQ(*kAllowedLocationsAuto, fs1.allowed_locations()); setenv("GCS_ALLOWED_BUCKET_LOCATIONS", "CUSTOM,list", 1); GcsFileSystem fs2; EXPECT_EQ(std::unordered_set<string>({"custom", "list"}), fs2.allowed_locations()); } TEST(GcsFileSystemTest, AdditionalRequestHeaderTest) { GcsFileSystem fs1; EXPECT_EQ("", fs1.additional_header_name()); EXPECT_EQ("", fs1.additional_header_value()); setenv("GCS_ADDITIONAL_REQUEST_HEADER", "X-Add-Header:My Additional Header Value", 1); GcsFileSystem fs2; EXPECT_EQ("X-Add-Header", fs2.additional_header_name()); EXPECT_EQ("My Additional Header Value", fs2.additional_header_value()); setenv("GCS_ADDITIONAL_REQUEST_HEADER", "Someinvalidheadervalue", 1); GcsFileSystem fs3; EXPECT_EQ("", fs3.additional_header_name()); EXPECT_EQ("", fs3.additional_header_value()); setenv("GCS_ADDITIONAL_REQUEST_HEADER", ":thisisinvalid", 1); GcsFileSystem fs4; EXPECT_EQ("", fs4.additional_header_name()); EXPECT_EQ("", fs4.additional_header_value()); setenv("GCS_ADDITIONAL_REQUEST_HEADER", "soisthis:", 1); GcsFileSystem fs5; EXPECT_EQ("", fs5.additional_header_name()); EXPECT_EQ("", fs5.additional_header_value()); setenv("GCS_ADDITIONAL_REQUEST_HEADER", "a:b", 1); GcsFileSystem fs6; EXPECT_EQ("a", fs6.additional_header_name()); EXPECT_EQ("b", fs6.additional_header_value()); auto* add_header = new std::pair<const string, const string>( "mynewheader", "newheadercontents"); std::vector<HttpRequest*> requests( { new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header mynewheader: newheadercontents\n" "Header Hello: world\n", "{}")}); GcsFileSystem fs7( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, add_header , false ); std::unique_ptr<HttpRequest> request; TF_EXPECT_OK(fs7.CreateHttpRequest(&request)); request->SetUri("https: request->AddHeader("Hello", "world"); TF_EXPECT_OK(request->Send()); } TEST(GcsFileSystemTest, OverrideCacheParameters) { setenv("GCS_READ_CACHE_BLOCK_SIZE_MB", "16", 1); setenv("GCS_READ_CACHE_MAX_SIZE_MB", "128", 1); GcsFileSystem fs1; EXPECT_EQ(16 * 1024 * 1024, fs1.block_size()); EXPECT_EQ(128 * 1024 * 1024, fs1.max_bytes()); EXPECT_EQ(0, fs1.max_staleness()); EXPECT_EQ(120, fs1.timeouts().connect); EXPECT_EQ(60, fs1.timeouts().idle); EXPECT_EQ(3600, fs1.timeouts().metadata); EXPECT_EQ(3600, fs1.timeouts().read); EXPECT_EQ(3600, fs1.timeouts().write); unsetenv("GCS_READ_CACHE_BLOCK_SIZE_MB"); setenv("GCS_READAHEAD_BUFFER_SIZE_BYTES", "123456789", 1); GcsFileSystem fs2; EXPECT_EQ(123456789L, fs2.block_size()); setenv("GCS_READ_CACHE_BLOCK_SIZE_MB", "1", 1); setenv("GCS_READ_CACHE_MAX_SIZE_MB", "16", 1); setenv("GCS_READ_CACHE_MAX_STALENESS", "60", 1); GcsFileSystem fs3; EXPECT_EQ(1048576L, fs3.block_size()); EXPECT_EQ(16 * 1024 * 1024, fs3.max_bytes()); EXPECT_EQ(60, fs3.max_staleness()); setenv("GCS_STAT_CACHE_MAX_AGE", "60", 1); setenv("GCS_STAT_CACHE_MAX_ENTRIES", "32", 1); setenv("GCS_MATCHING_PATHS_CACHE_MAX_AGE", "30", 1); setenv("GCS_MATCHING_PATHS_CACHE_MAX_ENTRIES", "64", 1); GcsFileSystem fs4; EXPECT_EQ(60, fs4.stat_cache_max_age()); EXPECT_EQ(32, fs4.stat_cache_max_entries()); EXPECT_EQ(30, fs4.matching_paths_cache_max_age()); EXPECT_EQ(64, fs4.matching_paths_cache_max_entries()); setenv("GCS_REQUEST_CONNECTION_TIMEOUT_SECS", "10", 1); setenv("GCS_REQUEST_IDLE_TIMEOUT_SECS", "5", 1); setenv("GCS_METADATA_REQUEST_TIMEOUT_SECS", "20", 1); setenv("GCS_READ_REQUEST_TIMEOUT_SECS", "30", 1); setenv("GCS_WRITE_REQUEST_TIMEOUT_SECS", "40", 1); GcsFileSystem fs5; EXPECT_EQ(10, fs5.timeouts().connect); EXPECT_EQ(5, fs5.timeouts().idle); EXPECT_EQ(20, fs5.timeouts().metadata); EXPECT_EQ(30, fs5.timeouts().read); EXPECT_EQ(40, fs5.timeouts().write); } TEST(GcsFileSystemTest, CreateHttpRequest) { std::vector<HttpRequest*> requests( { new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Header Hello: world\n", "{}")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<HttpRequest> request; TF_EXPECT_OK(fs.CreateHttpRequest(&request)); request->SetUri("https: request->AddHeader("Hello", "world"); TF_EXPECT_OK(request->Send()); } class TestGcsStats : public GcsStatsInterface { public: void Configure(GcsFileSystem* fs, GcsThrottle* throttle, const FileBlockCache* block_cache) override { CHECK(fs_ == nullptr); CHECK(throttle_ == nullptr); CHECK(block_cache_ == nullptr); fs_ = fs; throttle_ = throttle; block_cache_ = block_cache; } void RecordBlockLoadRequest(const string& file, size_t offset) override { block_load_request_file_ = file; } void RecordBlockRetrieved(const string& file, size_t offset, size_t bytes_transferred) override { block_retrieved_file_ = file; block_retrieved_bytes_transferred_ = bytes_transferred; } void RecordStatObjectRequest() override { stat_object_request_count_++; } HttpRequest::RequestStats* HttpStats() override { return nullptr; } GcsFileSystem* fs_ = nullptr; GcsThrottle* throttle_ = nullptr; const FileBlockCache* block_cache_ = nullptr; string block_load_request_file_; string block_retrieved_file_; size_t block_retrieved_bytes_transferred_ = 0; int stat_object_request_count_ = 0; }; TEST(GcsFileSystemTest, Stat_StatsRecording) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "file.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"1010\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}"))}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TestGcsStats stats; fs.SetStats(&stats); EXPECT_EQ(stats.fs_, &fs); FileStatistics stat; TF_EXPECT_OK(fs.Stat("gs: EXPECT_EQ(1, stats.stat_object_request_count_); } TEST(GcsFileSystemTest, NewRandomAccessFile_StatsRecording) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-5\n" "Timeouts: 5 1 20\n", "012345")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); TestGcsStats stats; fs.SetStats(&stats); EXPECT_EQ(stats.fs_, &fs); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char scratch[6]; absl::string_view result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("012345", result); EXPECT_EQ("gs: EXPECT_EQ("gs: EXPECT_EQ(6, stats.block_retrieved_bytes_transferred_); } TEST(GcsFileSystemTest, NewAppendableFile_MultipleFlushesWithCompose) { std::vector<string> contents( {"content0,", "content1,", "content2,", "content3,"}); std::vector<HttpRequest*> requests({ new FakeHttpRequest( "Uri: " "https: "some%2Fpath%2Fappendable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: " "https: "Auth Token: fake_token\n" "Range: 0-1048575\n" "Timeouts: 5 1 20\n", contents[0]), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=some%2Fpath%2Fappendable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 18\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest( strings::StrCat("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-17/18\n" "Timeouts: 5 1 30\n" "Put body: ", contents[0], contents[1], "\n"), ""), new FakeHttpRequest( "Uri: " "https: "o?uploadType=resumable&name=some%2Fpath%2F.tmpcompose%2Fappendable." "18\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 9\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: "location"}}), new FakeHttpRequest( strings::StrCat("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-8/9\n" "Timeouts: 5 1 30\n" "Put body: ", contents[2], "\n"), ""), new FakeHttpRequest( "Uri: " "https: "some%2Fpath%2Fappendable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1234\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest("Uri: " "https: "some%2Fpath%2Fappendable/compose\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header content-type: application/json\n" "Post body: {'sourceObjects': [{'name': " "'some/path/" "appendable','objectPrecondition':{'" "ifGenerationMatch':1234}},{'name': " "'some/path/.tmpcompose/appendable.18'}]}\n", ""), new FakeHttpRequest("Uri: " "https: "some%2Fpath%2F.tmpcompose%2Fappendable.18\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=some%2Fpath%2F.tmpcompose%2Fappendable." "27\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 9\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest( strings::StrCat("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-8/9\n" "Timeouts: 5 1 30\n" "Put body: ", contents[3], "\n"), ""), new FakeHttpRequest( "Uri: " "https: "some%2Fpath%2Fappendable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"4567\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest("Uri: " "https: "some%2Fpath%2Fappendable/compose\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Header content-type: application/json\n" "Post body: {'sourceObjects': [{'name': " "'some/path/" "appendable','objectPrecondition':{'" "ifGenerationMatch':4567}},{'name': " "'some/path/.tmpcompose/appendable.27'}]}\n", ""), new FakeHttpRequest("Uri: " "https: "some%2Fpath%2F.tmpcompose%2Fappendable." "27\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n" "Delete: yes\n", ""), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 32 , 32 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , true ); std::unique_ptr<WritableFile> wfile; TF_EXPECT_OK(fs.NewAppendableFile("gs: &wfile)); TF_EXPECT_OK(wfile->Append(contents[1])); TF_EXPECT_OK(wfile->Flush()); TF_EXPECT_OK(wfile->Append(contents[2])); TF_EXPECT_OK(wfile->Flush()); TF_EXPECT_OK(wfile->Append(contents[3])); TF_EXPECT_OK(wfile->Close()); } TEST(GcsFileSystemTest, NewAppendableFile_MultipleFlushesWithoutCompose) { std::vector<string> contents( {"content0,", "content1,", "content2,", "content3,"}); std::vector<HttpRequest*> requests({ new FakeHttpRequest( "Uri: https: "path%2Fappendable?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"8\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-1048575\n" "Timeouts: 5 1 20\n", contents[0]), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fappendable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 18\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest( strings::StrCat("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-17/18\n" "Timeouts: 5 1 30\n" "Put body: ", contents[0], contents[1], "\n"), ""), new FakeHttpRequest("Uri: " "https: "bucket/o?" "uploadType=resumable&name=path%2Fappendable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 27\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: "location"}}), new FakeHttpRequest( strings::StrCat("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-26/27\n" "Timeouts: 5 1 30\n" "Put body: ", contents[0], contents[1], contents[2], "\n"), ""), new FakeHttpRequest( "Uri: https: "uploadType=resumable&name=path%2Fappendable\n" "Auth Token: fake_token\n" "Header X-Upload-Content-Length: 36\n" "Post: yes\n" "Timeouts: 5 1 10\n", "", {{"Location", "https: new FakeHttpRequest( strings::StrCat("Uri: https: "Auth Token: fake_token\n" "Header Content-Range: bytes 0-35/36\n" "Timeouts: 5 1 30\n" "Put body: ", contents[0], contents[1], contents[2], contents[3], "\n"), ""), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 32 , 32 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<WritableFile> wfile; TF_EXPECT_OK( fs.NewAppendableFile("gs: TF_EXPECT_OK(wfile->Append(contents[1])); TF_EXPECT_OK(wfile->Flush()); TF_EXPECT_OK(wfile->Append(contents[2])); TF_EXPECT_OK(wfile->Flush()); TF_EXPECT_OK(wfile->Append(contents[3])); TF_EXPECT_OK(wfile->Close()); } TEST(GcsFileSystemTest, AppendModeCompose) { unsetenv("GCS_APPEND_MODE"); setenv("GCS_APPEND_MODE", "compose", 1); GcsFileSystem fs1; EXPECT_EQ(true, fs1.compose_append()); } TEST(GcsFileSystemTest, AppendModeDefault) { unsetenv("GCS_APPEND_MODE"); GcsFileSystem fs1; EXPECT_EQ(false, fs1.compose_append()); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/gcs_file_system.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/gcs_file_system_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
db30c870-4a02-4b6c-9779-ea72313933d7
cpp
google/tsl
gcs_throttle
tsl/platform/cloud/gcs_throttle.cc
tsl/platform/cloud/gcs_throttle_test.cc
#include "tsl/platform/cloud/gcs_throttle.h" #include <algorithm> namespace tsl { namespace { EnvTime* get_default_env_time() { static EnvTime* default_env_time = new EnvTime; return default_env_time; } } GcsThrottle::GcsThrottle(EnvTime* env_time) : last_updated_secs_(env_time ? env_time->GetOverridableNowSeconds() : EnvTime::NowSeconds()), available_tokens_(0), env_time_(env_time ? env_time : get_default_env_time()) {} bool GcsThrottle::AdmitRequest() { mutex_lock l(mu_); UpdateState(); if (available_tokens_ < config_.tokens_per_request) { return false || !config_.enabled; } available_tokens_ -= config_.tokens_per_request; return true; } void GcsThrottle::RecordResponse(size_t num_bytes) { mutex_lock l(mu_); UpdateState(); available_tokens_ -= request_bytes_to_tokens(num_bytes); } void GcsThrottle::SetConfig(GcsThrottleConfig config) { mutex_lock l(mu_); config_ = config; available_tokens_ = config.initial_tokens; last_updated_secs_ = env_time_->GetOverridableNowSeconds(); } void GcsThrottle::UpdateState() { int64_t now = env_time_->GetOverridableNowSeconds(); uint64 delta_secs = std::max(int64_t{0}, now - static_cast<int64_t>(last_updated_secs_)); available_tokens_ += delta_secs * config_.token_rate; available_tokens_ = std::min(available_tokens_, config_.bucket_size); last_updated_secs_ = now; } }
#include "tsl/platform/cloud/gcs_throttle.h" #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/str_util.h" #include "tsl/platform/test.h" namespace tsl { namespace { class TestTime : public EnvTime { public: uint64 GetOverridableNowNanos() const override { return now_micros_ * kMicrosToNanos; } void SetTime(uint64 now_micros) { now_micros_ = now_micros; } void AdvanceSeconds(int64_t secs) { now_micros_ += secs * kSecondsToMicros; } private: uint64 now_micros_ = 1234567890000000ULL; }; class GcsThrottleTest : public ::testing::Test { protected: GcsThrottleTest() : throttle_(&time_) { config_.enabled = true; throttle_.SetConfig(config_); } GcsThrottleConfig config_; TestTime time_; GcsThrottle throttle_; }; TEST_F(GcsThrottleTest, ReplenishTokens) { EXPECT_EQ(0, throttle_.available_tokens()); time_.AdvanceSeconds(1); EXPECT_EQ(100000, throttle_.available_tokens()); time_.AdvanceSeconds(2); EXPECT_EQ(300000, throttle_.available_tokens()); } TEST_F(GcsThrottleTest, RejectRequest) { EXPECT_EQ(0, throttle_.available_tokens()); time_.AdvanceSeconds(1); EXPECT_TRUE(throttle_.AdmitRequest()); EXPECT_EQ(99900, throttle_.available_tokens()); for (int i = 1; i < 1000; i++) { EXPECT_TRUE(throttle_.AdmitRequest()); } EXPECT_FALSE(throttle_.AdmitRequest()); } TEST_F(GcsThrottleTest, MarkResponses) { time_.AdvanceSeconds(1); EXPECT_TRUE(throttle_.AdmitRequest()); throttle_.RecordResponse(128000000); EXPECT_EQ(-25100, throttle_.available_tokens()); EXPECT_FALSE(throttle_.AdmitRequest()); time_.AdvanceSeconds(1); EXPECT_TRUE(throttle_.AdmitRequest()) << "Available tokens: " << throttle_.available_tokens(); } TEST_F(GcsThrottleTest, Skippingtime_) { EXPECT_EQ(0, throttle_.available_tokens()); time_.AdvanceSeconds(90); EXPECT_EQ(9000000, throttle_.available_tokens()); } TEST_F(GcsThrottleTest, BucketLimit) { time_.AdvanceSeconds(120); EXPECT_EQ(10000000, throttle_.available_tokens()); } TEST_F(GcsThrottleTest, ReverseTime) { time_.AdvanceSeconds(1); EXPECT_EQ(100000, throttle_.available_tokens()); time_.AdvanceSeconds(-3600); EXPECT_EQ(100000, throttle_.available_tokens()); time_.AdvanceSeconds(1); EXPECT_EQ(200000, throttle_.available_tokens()); } TEST(GcsThrottleDisabledTest, Disabled) { TestTime time; GcsThrottle throttle(&time); ASSERT_FALSE(throttle.is_enabled()); EXPECT_EQ(0, throttle.available_tokens()); time.AdvanceSeconds(1); EXPECT_EQ(100000, throttle.available_tokens()); EXPECT_TRUE(throttle.AdmitRequest()); EXPECT_EQ(99900, throttle.available_tokens()); time.AdvanceSeconds(1); EXPECT_EQ(199900, throttle.available_tokens()); throttle.RecordResponse(128000000); EXPECT_LT(0, throttle.available_tokens()); EXPECT_TRUE(throttle.AdmitRequest()); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/gcs_throttle.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/gcs_throttle_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
4273af3f-f205-4dcb-946a-0956d06dc284
cpp
google/tsl
ram_file_block_cache
tsl/platform/cloud/ram_file_block_cache.cc
tsl/platform/cloud/ram_file_block_cache_test.cc
#include "tsl/platform/cloud/ram_file_block_cache.h" #include <cstring> #include <memory> #include "absl/cleanup/cleanup.h" #include "tsl/platform/env.h" namespace tsl { bool RamFileBlockCache::BlockNotStale(const std::shared_ptr<Block>& block) { mutex_lock l(block->mu); if (block->state != FetchState::FINISHED) { return true; } if (max_staleness_ == 0) return true; return env_->NowSeconds() - block->timestamp <= max_staleness_; } std::shared_ptr<RamFileBlockCache::Block> RamFileBlockCache::Lookup( const Key& key) { mutex_lock lock(mu_); auto entry = block_map_.find(key); if (entry != block_map_.end()) { if (BlockNotStale(entry->second)) { if (cache_stats_ != nullptr) { cache_stats_->RecordCacheHitBlockSize(entry->second->data.size()); } return entry->second; } else { RemoveFile_Locked(key.first); } } auto new_entry = std::make_shared<Block>(); lru_list_.push_front(key); lra_list_.push_front(key); new_entry->lru_iterator = lru_list_.begin(); new_entry->lra_iterator = lra_list_.begin(); new_entry->timestamp = env_->NowSeconds(); block_map_.emplace(std::make_pair(key, new_entry)); return new_entry; } void RamFileBlockCache::Trim() { while (!lru_list_.empty() && cache_size_ > max_bytes_) { RemoveBlock(block_map_.find(lru_list_.back())); } } absl::Status RamFileBlockCache::UpdateLRU(const Key& key, const std::shared_ptr<Block>& block) { mutex_lock lock(mu_); if (block->timestamp == 0) { return absl::OkStatus(); } if (block->lru_iterator != lru_list_.begin()) { lru_list_.erase(block->lru_iterator); lru_list_.push_front(key); block->lru_iterator = lru_list_.begin(); } if (block->data.size() < block_size_) { Key fmax = std::make_pair(key.first, std::numeric_limits<size_t>::max()); auto fcmp = block_map_.upper_bound(fmax); if (fcmp != block_map_.begin() && key < (--fcmp)->first) { return errors::Internal("Block cache contents are inconsistent."); } } Trim(); return absl::OkStatus(); } absl::Status RamFileBlockCache::MaybeFetch( const Key& key, const std::shared_ptr<Block>& block) { bool downloaded_block = false; auto reconcile_state = absl::MakeCleanup([this, &downloaded_block, &key, &block] { if (downloaded_block) { mutex_lock l(mu_); if (block->timestamp != 0) { cache_size_ += block->data.capacity(); lra_list_.erase(block->lra_iterator); lra_list_.push_front(key); block->lra_iterator = lra_list_.begin(); block->timestamp = env_->NowSeconds(); } } }); mutex_lock l(block->mu); absl::Status status = absl::OkStatus(); while (true) { switch (block->state) { case FetchState::ERROR: TF_FALLTHROUGH_INTENDED; case FetchState::CREATED: block->state = FetchState::FETCHING; block->mu.unlock(); block->data.clear(); block->data.resize(block_size_, 0); size_t bytes_transferred; status.Update(block_fetcher_(key.first, key.second, block_size_, block->data.data(), &bytes_transferred)); if (cache_stats_ != nullptr) { cache_stats_->RecordCacheMissBlockSize(bytes_transferred); } block->mu.lock(); if (status.ok()) { block->data.resize(bytes_transferred, 0); std::vector<char>(block->data).swap(block->data); downloaded_block = true; block->state = FetchState::FINISHED; } else { block->state = FetchState::ERROR; } block->cond_var.notify_all(); return status; case FetchState::FETCHING: block->cond_var.wait_for(l, std::chrono::seconds(60)); if (block->state == FetchState::FINISHED) { return absl::OkStatus(); } break; case FetchState::FINISHED: return absl::OkStatus(); } } return errors::Internal( "Control flow should never reach the end of RamFileBlockCache::Fetch."); } absl::Status RamFileBlockCache::Read(const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { *bytes_transferred = 0; if (n == 0) { return absl::OkStatus(); } if (!IsCacheEnabled() || (n > max_bytes_)) { return block_fetcher_(filename, offset, n, buffer, bytes_transferred); } size_t start = block_size_ * (offset / block_size_); size_t finish = block_size_ * ((offset + n) / block_size_); if (finish < offset + n) { finish += block_size_; } size_t total_bytes_transferred = 0; for (size_t pos = start; pos < finish; pos += block_size_) { Key key = std::make_pair(filename, pos); std::shared_ptr<Block> block = Lookup(key); DCHECK(block) << "No block for key " << key.first << "@" << key.second; TF_RETURN_IF_ERROR(MaybeFetch(key, block)); TF_RETURN_IF_ERROR(UpdateLRU(key, block)); const auto& data = block->data; if (offset >= pos + data.size()) { *bytes_transferred = total_bytes_transferred; return errors::OutOfRange("EOF at offset ", offset, " in file ", filename, " at position ", pos, "with data size ", data.size()); } auto begin = data.begin(); if (offset > pos) { begin += offset - pos; } auto end = data.end(); if (pos + data.size() > offset + n) { end -= (pos + data.size()) - (offset + n); } if (begin < end) { size_t bytes_to_copy = end - begin; memcpy(&buffer[total_bytes_transferred], &*begin, bytes_to_copy); total_bytes_transferred += bytes_to_copy; } if (data.size() < block_size_) { break; } } *bytes_transferred = total_bytes_transferred; return absl::OkStatus(); } bool RamFileBlockCache::ValidateAndUpdateFileSignature(const string& filename, int64_t file_signature) { mutex_lock lock(mu_); auto it = file_signature_map_.find(filename); if (it != file_signature_map_.end()) { if (it->second == file_signature) { return true; } RemoveFile_Locked(filename); it->second = file_signature; return false; } file_signature_map_[filename] = file_signature; return true; } size_t RamFileBlockCache::CacheSize() const { mutex_lock lock(mu_); return cache_size_; } void RamFileBlockCache::Prune() { while (!WaitForNotificationWithTimeout(&stop_pruning_thread_, 1000000)) { mutex_lock lock(mu_); uint64 now = env_->NowSeconds(); while (!lra_list_.empty()) { auto it = block_map_.find(lra_list_.back()); if (now - it->second->timestamp <= max_staleness_) { break; } RemoveFile_Locked(std::string(it->first.first)); } } } void RamFileBlockCache::Flush() { mutex_lock lock(mu_); block_map_.clear(); lru_list_.clear(); lra_list_.clear(); cache_size_ = 0; } void RamFileBlockCache::RemoveFile(const string& filename) { mutex_lock lock(mu_); RemoveFile_Locked(filename); } void RamFileBlockCache::RemoveFile_Locked(const string& filename) { Key begin = std::make_pair(filename, 0); auto it = block_map_.lower_bound(begin); while (it != block_map_.end() && it->first.first == filename) { auto next = std::next(it); RemoveBlock(it); it = next; } } void RamFileBlockCache::RemoveBlock(BlockMap::iterator entry) { entry->second->timestamp = 0; lru_list_.erase(entry->second->lru_iterator); lra_list_.erase(entry->second->lra_iterator); cache_size_ -= entry->second->data.capacity(); block_map_.erase(entry); } }
#include "tsl/platform/cloud/ram_file_block_cache.h" #include <cstring> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/blocking_counter.h" #include "tsl/platform/cloud/now_seconds_env.h" #include "tsl/platform/env.h" #include "tsl/platform/notification.h" #include "tsl/platform/test.h" namespace tsl { namespace { absl::Status ReadCache(RamFileBlockCache* cache, const string& filename, size_t offset, size_t n, std::vector<char>* out) { out->clear(); out->resize(n, 0); size_t bytes_transferred = 0; absl::Status status = cache->Read(filename, offset, n, out->data(), &bytes_transferred); EXPECT_LE(bytes_transferred, n); out->resize(bytes_transferred, n); return status; } TEST(RamFileBlockCacheTest, IsCacheEnabled) { auto fetcher = [](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { return absl::OkStatus(); }; RamFileBlockCache cache1(0, 0, 0, fetcher); RamFileBlockCache cache2(16, 0, 0, fetcher); RamFileBlockCache cache3(0, 32, 0, fetcher); RamFileBlockCache cache4(16, 32, 0, fetcher); EXPECT_FALSE(cache1.IsCacheEnabled()); EXPECT_FALSE(cache2.IsCacheEnabled()); EXPECT_FALSE(cache3.IsCacheEnabled()); EXPECT_TRUE(cache4.IsCacheEnabled()); } TEST(RamFileBlockCacheTest, ValidateAndUpdateFileSignature) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; string filename = "file"; RamFileBlockCache cache(16, 32, 0, fetcher); std::vector<char> out; EXPECT_TRUE(cache.ValidateAndUpdateFileSignature(filename, 123)); TF_EXPECT_OK(ReadCache(&cache, filename, 0, 16, &out)); EXPECT_EQ(calls, 1); EXPECT_TRUE(cache.ValidateAndUpdateFileSignature(filename, 123)); TF_EXPECT_OK(ReadCache(&cache, filename, 0, 16, &out)); EXPECT_EQ(calls, 1); EXPECT_FALSE(cache.ValidateAndUpdateFileSignature(filename, 321)); TF_EXPECT_OK(ReadCache(&cache, filename, 0, 16, &out)); EXPECT_EQ(calls, 2); } TEST(RamFileBlockCacheTest, PassThrough) { const string want_filename = "foo/bar"; const size_t want_offset = 42; const size_t want_n = 1024; int calls = 0; auto fetcher = [&calls, want_filename, want_offset, want_n]( const string& got_filename, size_t got_offset, size_t got_n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(got_filename, want_filename); EXPECT_EQ(got_offset, want_offset); EXPECT_EQ(got_n, want_n); calls++; memset(buffer, 'x', got_n); *bytes_transferred = got_n; return absl::OkStatus(); }; RamFileBlockCache cache1(1, 0, 0, fetcher); RamFileBlockCache cache2(0, 1, 0, fetcher); RamFileBlockCache cache3(0, 0, 0, fetcher); RamFileBlockCache cache4(1000, 1000, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache1, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 1); TF_EXPECT_OK(ReadCache(&cache2, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 2); TF_EXPECT_OK(ReadCache(&cache3, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 3); TF_EXPECT_OK(ReadCache(&cache4, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 4); } TEST(RamFileBlockCacheTest, BlockAlignment) { const size_t size = 256; std::vector<char> buf; for (int i = 0; i < size; i++) { buf.push_back(i); } auto fetcher = [&buf](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { if (offset < buf.size()) { size_t bytes_to_copy = std::min<size_t>(buf.size() - offset, n); memcpy(buffer, buf.data() + offset, bytes_to_copy); *bytes_transferred = bytes_to_copy; } else { *bytes_transferred = 0; } return absl::OkStatus(); }; for (size_t block_size = 2; block_size <= 4; block_size++) { RamFileBlockCache cache(block_size, block_size, 0, fetcher); for (size_t offset = 0; offset < 10; offset++) { for (size_t n = block_size - 2; n <= block_size + 2; n++) { std::vector<char> got; TF_EXPECT_OK(ReadCache(&cache, "", offset, n, &got)); if (offset + n <= size) { EXPECT_EQ(got.size(), n) << "block size = " << block_size << ", offset = " << offset << ", n = " << n; } else { EXPECT_EQ(got.size(), size - offset) << "block size = " << block_size << ", offset = " << offset << ", n = " << n; } std::vector<char>::const_iterator begin = buf.begin() + offset; std::vector<char>::const_iterator end = offset + n > buf.size() ? buf.end() : begin + n; std::vector<char> want(begin, end); EXPECT_EQ(got, want) << "block size = " << block_size << ", offset = " << offset << ", n = " << n; } } } } TEST(RamFileBlockCacheTest, CacheHits) { const size_t block_size = 16; std::set<size_t> calls; auto fetcher = [&calls, block_size](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset % block_size, 0); EXPECT_EQ(calls.find(offset), calls.end()) << "at offset " << offset; calls.insert(offset); memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; const uint32 block_count = 256; RamFileBlockCache cache(block_size, block_count * block_size, 0, fetcher); std::vector<char> out; out.resize(block_count, 0); for (int i = 0; i < 2; i++) { for (int j = 0; j < block_count; j++) { TF_EXPECT_OK(ReadCache(&cache, "", block_size * j, block_size, &out)); } } } TEST(RamFileBlockCacheTest, OutOfRange) { const size_t block_size = 16; const size_t file_size = 24; bool first_block = false; bool second_block = false; auto fetcher = [block_size, file_size, &first_block, &second_block]( const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset % block_size, 0); size_t bytes_to_copy = 0; if (offset == 0) { memset(buffer, 'x', n); bytes_to_copy = n; first_block = true; } else if (offset == block_size) { bytes_to_copy = file_size - block_size; memset(buffer, 'x', bytes_to_copy); second_block = true; } *bytes_transferred = bytes_to_copy; return absl::OkStatus(); }; RamFileBlockCache cache(block_size, block_size, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", 0, block_size, &out)); EXPECT_TRUE(first_block); EXPECT_EQ(out.size(), block_size); absl::Status status = ReadCache(&cache, "", file_size + 4, 4, &out); EXPECT_EQ(status.code(), error::OUT_OF_RANGE); EXPECT_TRUE(second_block); second_block = false; TF_EXPECT_OK(ReadCache(&cache, "", block_size, block_size, &out)); EXPECT_FALSE(second_block); EXPECT_EQ(out.size(), file_size - block_size); } TEST(RamFileBlockCacheTest, Inconsistent) { const size_t block_size = 16; auto fetcher = [block_size](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset % block_size, 0); EXPECT_GE(n, 1); memset(buffer, 'x', 1); *bytes_transferred = 1; return absl::OkStatus(); }; RamFileBlockCache cache(block_size, 2 * block_size, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", block_size, block_size, &out)); EXPECT_EQ(out.size(), 1); absl::Status status = ReadCache(&cache, "", 0, block_size, &out); EXPECT_EQ(status.code(), error::INTERNAL); } TEST(RamFileBlockCacheTest, LRU) { const size_t block_size = 16; std::list<size_t> calls; auto fetcher = [&calls, block_size](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_FALSE(calls.empty()) << "at offset = " << offset; if (!calls.empty()) { EXPECT_EQ(offset, calls.front()); calls.pop_front(); } memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; const uint32 block_count = 2; RamFileBlockCache cache(block_size, block_count * block_size, 0, fetcher); std::vector<char> out; calls.push_back(0); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); calls.push_back(block_size); TF_EXPECT_OK(ReadCache(&cache, "", block_size, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", block_size, 1, &out)); calls.push_back(2 * block_size); TF_EXPECT_OK(ReadCache(&cache, "", 2 * block_size, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 2 * block_size, 1, &out)); calls.push_back(0); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 2 * block_size, 1, &out)); calls.push_back(block_size); TF_EXPECT_OK(ReadCache(&cache, "", block_size, 1, &out)); calls.push_back(0); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); } TEST(RamFileBlockCacheTest, MaxStaleness) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; std::vector<char> out; std::unique_ptr<NowSecondsEnv> env(new NowSecondsEnv); RamFileBlockCache cache1(8, 16, 2 , fetcher, env.get()); TF_EXPECT_OK(ReadCache(&cache1, "", 0, 1, &out)); EXPECT_EQ(calls, 1); for (int i = 1; i <= 10; i++) { env->SetNowSeconds(i + 1); TF_EXPECT_OK(ReadCache(&cache1, "", 0, 1, &out)); EXPECT_EQ(calls, 1 + i / 3); } calls = 0; env->SetNowSeconds(0); RamFileBlockCache cache2(8, 16, 0 , fetcher, env.get()); TF_EXPECT_OK(ReadCache(&cache2, "", 0, 1, &out)); EXPECT_EQ(calls, 1); env->SetNowSeconds(365 * 24 * 60 * 60); TF_EXPECT_OK(ReadCache(&cache2, "", 0, 1, &out)); EXPECT_EQ(calls, 1); } TEST(RamFileBlockCacheTest, RemoveFile) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; char c = (filename == "a") ? 'a' : (filename == "b") ? 'b' : 'x'; if (offset > 0) { c = toupper(c); } memset(buffer, c, n); *bytes_transferred = n; return absl::OkStatus(); }; const size_t n = 3; RamFileBlockCache cache(8, 32, 0, fetcher); std::vector<char> out; std::vector<char> a(n, 'a'); std::vector<char> b(n, 'b'); std::vector<char> A(n, 'A'); std::vector<char> B(n, 'B'); TF_EXPECT_OK(ReadCache(&cache, "a", 0, n, &out)); EXPECT_EQ(out, a); EXPECT_EQ(calls, 1); TF_EXPECT_OK(ReadCache(&cache, "a", 8, n, &out)); EXPECT_EQ(out, A); EXPECT_EQ(calls, 2); TF_EXPECT_OK(ReadCache(&cache, "b", 0, n, &out)); EXPECT_EQ(out, b); EXPECT_EQ(calls, 3); TF_EXPECT_OK(ReadCache(&cache, "b", 8, n, &out)); EXPECT_EQ(out, B); EXPECT_EQ(calls, 4); TF_EXPECT_OK(ReadCache(&cache, "a", 0, n, &out)); EXPECT_EQ(out, a); TF_EXPECT_OK(ReadCache(&cache, "a", 8, n, &out)); EXPECT_EQ(out, A); TF_EXPECT_OK(ReadCache(&cache, "b", 0, n, &out)); EXPECT_EQ(out, b); TF_EXPECT_OK(ReadCache(&cache, "b", 8, n, &out)); EXPECT_EQ(out, B); EXPECT_EQ(calls, 4); cache.RemoveFile("a"); TF_EXPECT_OK(ReadCache(&cache, "b", 0, n, &out)); EXPECT_EQ(out, b); TF_EXPECT_OK(ReadCache(&cache, "b", 8, n, &out)); EXPECT_EQ(out, B); EXPECT_EQ(calls, 4); TF_EXPECT_OK(ReadCache(&cache, "a", 0, n, &out)); EXPECT_EQ(out, a); EXPECT_EQ(calls, 5); TF_EXPECT_OK(ReadCache(&cache, "a", 8, n, &out)); EXPECT_EQ(out, A); EXPECT_EQ(calls, 6); } TEST(RamFileBlockCacheTest, Prune) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; std::vector<char> out; std::unique_ptr<NowSecondsEnv> env(new NowSecondsEnv); uint64 now = Env::Default()->NowSeconds(); env->SetNowSeconds(now); RamFileBlockCache cache(8, 32, 1 , fetcher, env.get()); TF_EXPECT_OK(ReadCache(&cache, "a", 0, 1, &out)); env->SetNowSeconds(now + 1); TF_EXPECT_OK(ReadCache(&cache, "b", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "a", 8, 1, &out)); EXPECT_EQ(cache.CacheSize(), 24); EXPECT_EQ(calls, 3); TF_EXPECT_OK(ReadCache(&cache, "a", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "b", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "a", 8, 1, &out)); EXPECT_EQ(calls, 3); env->SetNowSeconds(now + 2); uint64 start = Env::Default()->NowSeconds(); do { Env::Default()->SleepForMicroseconds(100000); } while (cache.CacheSize() == 24 && Env::Default()->NowSeconds() - start < 3); EXPECT_EQ(cache.CacheSize(), 8); TF_EXPECT_OK(ReadCache(&cache, "b", 0, 1, &out)); EXPECT_EQ(calls, 3); env->SetNowSeconds(now + 3); start = Env::Default()->NowSeconds(); do { Env::Default()->SleepForMicroseconds(100000); } while (cache.CacheSize() == 8 && Env::Default()->NowSeconds() - start < 3); EXPECT_EQ(cache.CacheSize(), 0); } TEST(RamFileBlockCacheTest, ParallelReads) { const int callers = 4; BlockingCounter counter(callers); auto fetcher = [&counter](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { counter.DecrementCount(); if (!counter.WaitFor(std::chrono::seconds(10))) { return errors::FailedPrecondition("desired concurrency not reached"); } memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; const int block_size = 8; RamFileBlockCache cache(block_size, 2 * callers * block_size, 0, fetcher); std::vector<std::unique_ptr<Thread>> threads; for (int i = 0; i < callers; i++) { threads.emplace_back( Env::Default()->StartThread({}, "caller", [&cache, i, block_size]() { std::vector<char> out; TF_EXPECT_OK( ReadCache(&cache, "a", i * block_size, block_size, &out)); std::vector<char> x(block_size, 'x'); EXPECT_EQ(out, x); })); } } TEST(RamFileBlockCacheTest, CoalesceConcurrentReads) { const size_t block_size = 16; int num_requests = 0; Notification notification; auto fetcher = [&num_requests, &notification, block_size]( const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset, 0); num_requests++; memset(buffer, 'x', n); *bytes_transferred = n; notification.Notify(); Env::Default()->SleepForMicroseconds(100000); return absl::OkStatus(); }; RamFileBlockCache cache(block_size, block_size, 0, fetcher); std::unique_ptr<Thread> concurrent( Env::Default()->StartThread({}, "concurrent", [&cache, block_size] { std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", 0, block_size / 2, &out)); EXPECT_EQ(out.size(), block_size / 2); })); notification.WaitForNotification(); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", block_size / 2, block_size / 2, &out)); EXPECT_EQ(out.size(), block_size / 2); EXPECT_EQ(1, num_requests); } TEST(RamFileBlockCacheTest, Flush) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return absl::OkStatus(); }; RamFileBlockCache cache(16, 32, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", 0, 16, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 0, 16, &out)); EXPECT_EQ(calls, 1); cache.Flush(); TF_EXPECT_OK(ReadCache(&cache, "", 0, 16, &out)); EXPECT_EQ(calls, 2); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/ram_file_block_cache.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/ram_file_block_cache_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
bdbf84ca-7758-46a6-aae4-144045d7cdef
cpp
google/tsl
google_auth_provider
tsl/platform/cloud/google_auth_provider.cc
tsl/platform/cloud/google_auth_provider_test.cc
#include "tsl/platform/cloud/google_auth_provider.h" #ifndef _WIN32 #include <pwd.h> #include <unistd.h> #else #include <sys/types.h> #endif #include <fstream> #include <utility> #include "absl/strings/match.h" #include "json/json.h" #include "tsl/platform/base64.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/path.h" #include "tsl/platform/retrying_utils.h" namespace tsl { namespace { constexpr char kGoogleApplicationCredentials[] = "GOOGLE_APPLICATION_CREDENTIALS"; constexpr char kGoogleAuthTokenForTesting[] = "GOOGLE_AUTH_TOKEN_FOR_TESTING"; constexpr char kCloudSdkConfig[] = "CLOUDSDK_CONFIG"; constexpr char kNoGceCheck[] = "NO_GCE_CHECK"; constexpr char kGCloudConfigFolder[] = ".config/gcloud/"; constexpr char kWellKnownCredentialsFile[] = "application_default_credentials.json"; constexpr int kExpirationTimeMarginSec = 60; constexpr char kOAuthV3Url[] = "https: constexpr char kOAuthV4Url[] = "https: constexpr char kGceTokenPath[] = "instance/service-accounts/default/token"; constexpr char kOAuthScope[] = "https: bool IsFile(const string& filename) { std::ifstream fstream(filename.c_str()); return fstream.good(); } absl::Status GetEnvironmentVariableFileName(string* filename) { if (!filename) { return errors::FailedPrecondition("'filename' cannot be nullptr."); } const char* result = std::getenv(kGoogleApplicationCredentials); if (!result || !IsFile(result)) { return errors::NotFound(strings::StrCat("$", kGoogleApplicationCredentials, " is not set or corrupt.")); } *filename = result; return absl::OkStatus(); } absl::Status GetWellKnownFileName(string* filename) { if (!filename) { return errors::FailedPrecondition("'filename' cannot be nullptr."); } string config_dir; const char* config_dir_override = std::getenv(kCloudSdkConfig); if (config_dir_override) { config_dir = config_dir_override; } else { const char* home_dir = std::getenv("HOME"); if (!home_dir) { return errors::FailedPrecondition("Could not read $HOME."); } config_dir = io::JoinPath(home_dir, kGCloudConfigFolder); } auto result = io::JoinPath(config_dir, kWellKnownCredentialsFile); if (!IsFile(result)) { return errors::NotFound( "Could not find the credentials file in the standard gcloud location."); } *filename = result; return absl::OkStatus(); } } GoogleAuthProvider::GoogleAuthProvider( std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client) : GoogleAuthProvider(std::unique_ptr<OAuthClient>(new OAuthClient()), std::move(compute_engine_metadata_client), Env::Default()) {} GoogleAuthProvider::GoogleAuthProvider( std::unique_ptr<OAuthClient> oauth_client, std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client, Env* env) : oauth_client_(std::move(oauth_client)), compute_engine_metadata_client_( std::move(compute_engine_metadata_client)), env_(env) {} absl::Status GoogleAuthProvider::GetToken(string* t) { mutex_lock lock(mu_); const uint64 now_sec = env_->NowSeconds(); if (now_sec + kExpirationTimeMarginSec < expiration_timestamp_sec_) { *t = current_token_; return absl::OkStatus(); } if (GetTokenForTesting().ok()) { *t = current_token_; return absl::OkStatus(); } auto token_from_files_status = GetTokenFromFiles(); if (token_from_files_status.ok()) { *t = current_token_; return absl::OkStatus(); } char* no_gce_check_var = std::getenv(kNoGceCheck); bool skip_gce_check = no_gce_check_var != nullptr && absl::EqualsIgnoreCase(no_gce_check_var, "true"); absl::Status token_from_gce_status; if (skip_gce_check) { token_from_gce_status = absl::Status(absl::StatusCode::kCancelled, strings::StrCat("GCE check skipped due to presence of $", kNoGceCheck, " environment variable.")); } else { token_from_gce_status = GetTokenFromGce(); } if (token_from_gce_status.ok()) { *t = current_token_; return absl::OkStatus(); } if (skip_gce_check) { LOG(INFO) << "Attempting an empty bearer token since no token was retrieved " << "from files, and GCE metadata check was skipped."; } else { LOG(WARNING) << "All attempts to get a Google authentication bearer token failed, " << "returning an empty token. Retrieving token from files failed with " "\"" << token_from_files_status.ToString() << "\"." << " Retrieving token from GCE failed with \"" << token_from_gce_status.ToString() << "\"."; } *t = ""; if (skip_gce_check) { expiration_timestamp_sec_ = 0; } else { expiration_timestamp_sec_ = UINT64_MAX; } current_token_ = ""; return absl::OkStatus(); } absl::Status GoogleAuthProvider::GetTokenFromFiles() { string credentials_filename; if (!GetEnvironmentVariableFileName(&credentials_filename).ok() && !GetWellKnownFileName(&credentials_filename).ok()) { return errors::NotFound("Could not locate the credentials file."); } Json::Value json; Json::Reader reader; std::ifstream credentials_fstream(credentials_filename); if (!reader.parse(credentials_fstream, json)) { return errors::FailedPrecondition( "Couldn't parse the JSON credentials file."); } if (json.isMember("refresh_token")) { TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromRefreshTokenJson( json, kOAuthV3Url, &current_token_, &expiration_timestamp_sec_)); } else if (json.isMember("private_key")) { TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromServiceAccountJson( json, kOAuthV4Url, kOAuthScope, &current_token_, &expiration_timestamp_sec_)); } else { return errors::FailedPrecondition( "Unexpected content of the JSON credentials file."); } return absl::OkStatus(); } absl::Status GoogleAuthProvider::GetTokenFromGce() { std::vector<char> response_buffer; const uint64 request_timestamp_sec = env_->NowSeconds(); TF_RETURN_IF_ERROR(compute_engine_metadata_client_->GetMetadata( kGceTokenPath, &response_buffer)); absl::string_view response = absl::string_view(&response_buffer[0], response_buffer.size()); TF_RETURN_IF_ERROR(oauth_client_->ParseOAuthResponse( response, request_timestamp_sec, &current_token_, &expiration_timestamp_sec_)); return absl::OkStatus(); } absl::Status GoogleAuthProvider::GetTokenForTesting() { const char* token = std::getenv(kGoogleAuthTokenForTesting); if (!token) { return errors::NotFound("The env variable for testing was not set."); } expiration_timestamp_sec_ = UINT64_MAX; current_token_ = token; return absl::OkStatus(); } }
#include "tsl/platform/cloud/google_auth_provider.h" #include <stdlib.h> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/path.h" #include "tsl/platform/test.h" namespace tsl { namespace { string TestData() { return io::JoinPath(testing::TslSrcRoot(), "platform", "cloud", "testdata"); } class FakeEnv : public EnvWrapper { public: FakeEnv() : EnvWrapper(Env::Default()) {} uint64 NowSeconds() const override { return now; } uint64 now = 10000; }; class FakeOAuthClient : public OAuthClient { public: absl::Status GetTokenFromServiceAccountJson( Json::Value json, absl::string_view oauth_server_uri, absl::string_view scope, string* token, uint64* expiration_timestamp_sec) override { provided_credentials_json = json; *token = return_token; *expiration_timestamp_sec = return_expiration_timestamp; return absl::OkStatus(); } absl::Status GetTokenFromRefreshTokenJson( Json::Value json, absl::string_view oauth_server_uri, string* token, uint64* expiration_timestamp_sec) override { provided_credentials_json = json; *token = return_token; *expiration_timestamp_sec = return_expiration_timestamp; return absl::OkStatus(); } string return_token; uint64 return_expiration_timestamp; Json::Value provided_credentials_json; }; } class GoogleAuthProviderTest : public ::testing::Test { protected: void SetUp() override { ClearEnvVars(); } void TearDown() override { ClearEnvVars(); } void ClearEnvVars() { unsetenv("CLOUDSDK_CONFIG"); unsetenv("GOOGLE_APPLICATION_CREDENTIALS"); unsetenv("GOOGLE_AUTH_TOKEN_FOR_TESTING"); unsetenv("NO_GCE_CHECK"); } }; TEST_F(GoogleAuthProviderTest, EnvironmentVariable_Caching) { setenv("GOOGLE_APPLICATION_CREDENTIALS", io::JoinPath(TestData(), "service_account_credentials.json").c_str(), 1); setenv("CLOUDSDK_CONFIG", TestData().c_str(), 1); auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests; FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); oauth_client->return_token = "fake-token"; oauth_client->return_expiration_timestamp = env.NowSeconds() + 3600; string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-token", token); EXPECT_EQ("fake_key_id", oauth_client->provided_credentials_json.get("private_key_id", "") .asString()); oauth_client->return_token = "new-fake-token"; env.now += 3000; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-token", token); env.now += 598; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("new-fake-token", token); } TEST_F(GoogleAuthProviderTest, GCloudRefreshToken) { setenv("CLOUDSDK_CONFIG", TestData().c_str(), 1); auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests; FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); oauth_client->return_token = "fake-token"; oauth_client->return_expiration_timestamp = env.NowSeconds() + 3600; string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-token", token); EXPECT_EQ("fake-refresh-token", oauth_client->provided_credentials_json.get("refresh_token", "") .asString()); } TEST_F(GoogleAuthProviderTest, RunningOnGCE) { auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", R"( { "access_token":"fake-gce-token", "expires_in": 3920, "token_type":"Bearer" })"), new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", R"( { "access_token":"new-fake-gce-token", "expires_in": 3920, "token_type":"Bearer" })")}); FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-gce-token", token); env.now += 3700; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-gce-token", token); env.now += 598; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("new-fake-gce-token", token); } TEST_F(GoogleAuthProviderTest, OverrideForTesting) { setenv("GOOGLE_AUTH_TOKEN_FOR_TESTING", "tokenForTesting", 1); auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> empty_requests; FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&empty_requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("tokenForTesting", token); } TEST_F(GoogleAuthProviderTest, NothingAvailable) { auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", "", errors::NotFound("404"), 404)}); FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("", token); } TEST_F(GoogleAuthProviderTest, NoGceCheckEnvironmentVariable) { setenv("NO_GCE_CHECK", "True", 1); auto oauth_client = new FakeOAuthClient; FakeEnv env; GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), nullptr, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("", token); setenv("NO_GCE_CHECK", "true", 1); TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("", token); setenv("GOOGLE_AUTH_TOKEN_FOR_TESTING", "newToken", 1); TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("newToken", token); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/google_auth_provider.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/google_auth_provider_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
e510e08c-cc79-4ffc-bf7b-dcf71c6c014e
cpp
google/tsl
curl_http_request
tsl/platform/cloud/curl_http_request.cc
tsl/platform/cloud/curl_http_request_test.cc
#include "tsl/platform/cloud/curl_http_request.h" #include <algorithm> #include "xla/tsl/lib/gtl/map_util.h" #include "xla/tsl/util/env_var.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" #include "tsl/platform/scanner.h" #include "tsl/platform/str_util.h" #include "tsl/platform/types.h" #define CHECK_CURL_OK(expr) CHECK_EQ(expr, CURLE_OK) namespace tsl { namespace { constexpr uint64 kVerboseOutput = 0; class LibCurlProxy : public LibCurl { public: static LibCurlProxy* Load() { static LibCurlProxy* libcurl = []() -> LibCurlProxy* { curl_global_init(CURL_GLOBAL_ALL); return new LibCurlProxy; }(); return libcurl; } CURL* curl_easy_init() override { return ::curl_easy_init(); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, uint64 param) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, const char* param) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, void* param) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(void*, size_t, size_t, FILE*)) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(const void*, size_t, size_t, void*)) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, int (*param)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_perform(CURL* curl) override { return ::curl_easy_perform(curl); } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, uint64* value) override { return ::curl_easy_getinfo(curl, info, value); } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, double* value) override { return ::curl_easy_getinfo(curl, info, value); } void curl_easy_cleanup(CURL* curl) override { return ::curl_easy_cleanup(curl); } char* curl_easy_escape(CURL* curl, const char* str, int length) override { return ::curl_easy_escape(curl, str, length); } curl_slist* curl_slist_append(curl_slist* list, const char* str) override { return ::curl_slist_append(list, str); } void curl_slist_free_all(curl_slist* list) override { return ::curl_slist_free_all(list); } void curl_free(void* p) override { ::curl_free(p); } }; } CurlHttpRequest::CurlHttpRequest() : CurlHttpRequest(LibCurlProxy::Load()) {} CurlHttpRequest::CurlHttpRequest(LibCurl* libcurl, Env* env) : libcurl_(libcurl), env_(env) { default_response_buffer_.reserve(CURL_MAX_WRITE_SIZE); curl_ = libcurl_->curl_easy_init(); CHECK(curl_ != nullptr) << "Couldn't initialize a curl session."; std::string value = ""; TF_CHECK_OK(ReadStringFromEnvVar("CURL_CA_BUNDLE", "", &value)); if (!value.empty()) { CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_CAINFO, value.c_str())); } CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_VERBOSE, kVerboseOutput)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_USERAGENT, "TSL")); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1L)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)); CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, uint64{0})); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_XFERINFODATA, this)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_XFERINFOFUNCTION, &CurlHttpRequest::ProgressCallback)); SetResultBuffer(&default_response_buffer_); } CurlHttpRequest::~CurlHttpRequest() { if (curl_headers_) { libcurl_->curl_slist_free_all(curl_headers_); } if (resolve_list_) { libcurl_->curl_slist_free_all(resolve_list_); } if (put_body_) { if (fclose(put_body_) != 0) { LOG(ERROR) << "fclose() failed: " << strerror(errno); } } if (curl_) { libcurl_->curl_easy_cleanup(curl_); } } string CurlHttpRequest::EscapeString(const string& str) { char* out_char_str = libcurl_->curl_easy_escape(curl_, str.c_str(), 0); string out_str(out_char_str); libcurl_->curl_free(out_char_str); return out_str; } void CurlHttpRequest::SetUri(const string& uri) { CheckNotSent(); is_uri_set_ = true; uri_ = uri; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_URL, uri.c_str())); } void CurlHttpRequest::SetRange(uint64 start, uint64 end) { CheckNotSent(); CHECK_CURL_OK(libcurl_->curl_easy_setopt( curl_, CURLOPT_RANGE, strings::StrCat(start, "-", end).c_str())); } void CurlHttpRequest::AddHeader(const string& name, const string& value) { CheckNotSent(); curl_headers_ = libcurl_->curl_slist_append( curl_headers_, strings::StrCat(name, ": ", value).c_str()); } void CurlHttpRequest::AddResolveOverride(const string& hostname, int64_t port, const string& ip_addr) { CheckNotSent(); resolve_list_ = libcurl_->curl_slist_append( resolve_list_, strings::StrCat(hostname, ":", port, ":", ip_addr).c_str()); } void CurlHttpRequest::AddAuthBearerHeader(const string& auth_token) { CheckNotSent(); if (!auth_token.empty()) { AddHeader("Authorization", strings::StrCat("Bearer ", auth_token)); } } void CurlHttpRequest::SetRequestStats(RequestStats* stats) { CheckNotSent(); CHECK(stats_ == nullptr) << "SetRequestStats already called"; stats_ = stats; } void CurlHttpRequest::SetDeleteRequest() { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kDelete; CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "DELETE")); } absl::Status CurlHttpRequest::SetPutFromFile(const string& body_filepath, size_t offset) { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPut; if (put_body_) { if (fclose(put_body_) != 0) { LOG(ERROR) << "fclose() failed: " << strerror(errno); } } put_body_ = fopen(body_filepath.c_str(), "r"); if (!put_body_) { return errors::InvalidArgument("Couldn't open the specified file: " + body_filepath); } fseek(put_body_, 0, SEEK_END); const auto size = ftell(put_body_) - offset; fseek(put_body_, offset, SEEK_SET); curl_headers_ = libcurl_->curl_slist_append( curl_headers_, strings::StrCat("Content-Length: ", size).c_str()); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(put_body_))); return absl::OkStatus(); } void CurlHttpRequest::SetPutEmptyBody() { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPut; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1)); AddHeader("Content-Length", "0"); AddHeader("Transfer-Encoding", "identity"); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION, &CurlHttpRequest::ReadCallback)); } void CurlHttpRequest::SetPostFromBuffer(const char* buffer, size_t size) { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPost; curl_headers_ = libcurl_->curl_slist_append( curl_headers_, strings::StrCat("Content-Length: ", size).c_str()); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION, &CurlHttpRequest::ReadCallback)); post_body_buffer_ = absl::string_view(buffer, size); } void CurlHttpRequest::SetPostEmptyBody() { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPost; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1)); AddHeader("Content-Length", "0"); AddHeader("Transfer-Encoding", "identity"); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION, &CurlHttpRequest::ReadCallback)); } void CurlHttpRequest::SetResultBuffer(std::vector<char>* out_buffer) { CheckNotSent(); CHECK(out_buffer != nullptr); out_buffer->clear(); response_buffer_ = out_buffer; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, &CurlHttpRequest::WriteCallback)); } void CurlHttpRequest::SetResultBufferDirect(char* buffer, size_t size) { CHECK(buffer != nullptr); CheckNotSent(); direct_response_ = DirectResponseState{buffer, size, 0, 0}; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt( curl_, CURLOPT_WRITEFUNCTION, &CurlHttpRequest::WriteCallbackDirect)); } bool CurlHttpRequest::IsDirectResponse() const { return direct_response_.buffer_ != nullptr; } size_t CurlHttpRequest::WriteCallbackDirect(const void* ptr, size_t size, size_t nmemb, void* userdata) { CHECK(ptr != nullptr); auto that = reinterpret_cast<CurlHttpRequest*>(userdata); DirectResponseState* state = &that->direct_response_; CHECK(state->buffer_ != nullptr); CHECK(state->bytes_transferred_ <= state->buffer_size_); size_t curl_bytes_received = size * nmemb; size_t user_buffer_bytes_available = state->buffer_size_ - state->bytes_transferred_; size_t bytes_to_copy = std::min<size_t>(curl_bytes_received, user_buffer_bytes_available); memcpy(&state->buffer_[state->bytes_transferred_], ptr, bytes_to_copy); state->bytes_transferred_ += bytes_to_copy; state->bytes_received_ += curl_bytes_received; return bytes_to_copy; } size_t CurlHttpRequest::GetResultBufferDirectBytesTransferred() { CHECK(direct_response_.buffer_ != nullptr); return direct_response_.bytes_transferred_; } void CurlHttpRequest::SetTimeouts(uint32 connection, uint32 inactivity, uint32 total) { CheckNotSent(); connect_timeout_secs_ = connection; inactivity_timeout_secs_ = inactivity; request_timeout_secs_ = total; } size_t CurlHttpRequest::WriteCallback(const void* ptr, size_t size, size_t nmemb, void* this_object) { CHECK(ptr); auto that = reinterpret_cast<CurlHttpRequest*>(this_object); CHECK(that->response_buffer_); const size_t bytes_to_copy = size * nmemb; that->response_buffer_->insert( that->response_buffer_->end(), reinterpret_cast<const char*>(ptr), reinterpret_cast<const char*>(ptr) + bytes_to_copy); return bytes_to_copy; } size_t CurlHttpRequest::ReadCallback(void* ptr, size_t size, size_t nmemb, FILE* this_object) { CHECK(ptr); auto that = reinterpret_cast<CurlHttpRequest*>(this_object); CHECK(that->post_body_read_ <= that->post_body_buffer_.size()); const size_t bytes_to_copy = std::min( size * nmemb, that->post_body_buffer_.size() - that->post_body_read_); memcpy(ptr, that->post_body_buffer_.data() + that->post_body_read_, bytes_to_copy); that->post_body_read_ += bytes_to_copy; return bytes_to_copy; } size_t CurlHttpRequest::HeaderCallback(const void* ptr, size_t size, size_t nmemb, void* this_object) { CHECK(ptr); auto that = reinterpret_cast<CurlHttpRequest*>(this_object); absl::string_view header(reinterpret_cast<const char*>(ptr), size * nmemb); absl::string_view name, value; if (strings::Scanner(header) .ScanEscapedUntil(':') .StopCapture() .OneLiteral(": ") .GetResult(&value, &name)) { string str_value(value); absl::StripTrailingAsciiWhitespace(&str_value); that->response_headers_[string(name)] = str_value; } return size * nmemb; } absl::Status CurlHttpRequest::Send() { CheckNotSent(); CHECK(is_uri_set_) << "URI has not been set."; is_sent_ = true; if (curl_headers_) { CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers_)); } if (resolve_list_) { CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_RESOLVE, resolve_list_)); } CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERFUNCTION, &CurlHttpRequest::HeaderCallback)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_TIMEOUT, request_timeout_secs_)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, connect_timeout_secs_)); char error_buffer[CURL_ERROR_SIZE] = {0}; CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buffer)); if (stats_ != nullptr) { stats_->RecordRequest(this, uri_, method_); } const CURLcode curl_result = libcurl_->curl_easy_perform(curl_); TF_RETURN_IF_ERROR(CURLcodeToStatus(curl_result, error_buffer)); double written_size = 0; CHECK_CURL_OK(libcurl_->curl_easy_getinfo(curl_, CURLINFO_SIZE_DOWNLOAD, &written_size)); CHECK_CURL_OK(libcurl_->curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &response_code_)); auto get_error_message = [this]() -> string { string error_message = strings::StrCat( "Error executing an HTTP request: HTTP response code ", response_code_); absl::string_view body = GetResponse(); if (!body.empty()) { return strings::StrCat( error_message, " with body '", body.substr(0, std::min(body.size(), response_to_error_limit_)), "'"); } return error_message; }; absl::Status result; switch (response_code_) { case 200: case 201: case 204: case 206: result = absl::OkStatus(); break; case 416: response_buffer_->clear(); if (IsDirectResponse()) { direct_response_.bytes_transferred_ = 0; } result = absl::OkStatus(); break; case 400: case 406: case 411: case 414: result = errors::InvalidArgument(get_error_message()); break; case 401: case 403: case 407: result = errors::PermissionDenied(get_error_message()); break; case 404: case 410: result = errors::NotFound(get_error_message()); break; case 302: case 303: case 304: case 307: case 412: case 413: result = errors::FailedPrecondition(get_error_message()); break; case 308: case 409: case 429: case 500: case 502: case 503: default: result = errors::Unavailable(get_error_message()); break; } if (!result.ok()) { response_buffer_->clear(); } if (stats_ != nullptr) { stats_->RecordResponse(this, uri_, method_, result); } return result; } void CurlHttpRequest::CheckMethodNotSet() const { CHECK(!is_method_set_) << "HTTP method has been already set."; } void CurlHttpRequest::CheckNotSent() const { CHECK(!is_sent_) << "The request has already been sent."; } absl::string_view CurlHttpRequest::GetResponse() const { absl::string_view response; if (IsDirectResponse()) { response = absl::string_view(direct_response_.buffer_, direct_response_.bytes_transferred_); } else { response = absl::string_view(response_buffer_->data(), response_buffer_->size()); } return response; } string CurlHttpRequest::GetResponseHeader(const string& name) const { const auto& header = response_headers_.find(name); return header != response_headers_.end() ? header->second : ""; } uint64 CurlHttpRequest::GetResponseCode() const { return response_code_; } int CurlHttpRequest::ProgressCallback(void* this_object, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { auto that = reinterpret_cast<CurlHttpRequest*>(this_object); const auto now = that->env_->NowSeconds(); const auto current_progress = dlnow + ulnow; if (that->last_progress_timestamp_ == 0 || current_progress > that->last_progress_bytes_) { that->last_progress_timestamp_ = now; that->last_progress_bytes_ = current_progress; return 0; } if (now - that->last_progress_timestamp_ > that->inactivity_timeout_secs_) { double lookup_time = -1; const auto lookup_time_status = that->libcurl_->curl_easy_getinfo( that->curl_, CURLINFO_NAMELOOKUP_TIME, &lookup_time); double connect_time = -1; const auto connect_time_status = that->libcurl_->curl_easy_getinfo( that->curl_, CURLINFO_CONNECT_TIME, &connect_time); double pretransfer_time = -1; const auto pretransfer_time_status = that->libcurl_->curl_easy_getinfo( that->curl_, CURLINFO_PRETRANSFER_TIME, &pretransfer_time); double starttransfer_time = -1; const auto starttransfer_time_status = that->libcurl_->curl_easy_getinfo( that->curl_, CURLINFO_STARTTRANSFER_TIME, &starttransfer_time); LOG(ERROR) << "The transmission of request " << this_object << " (URI: " << that->uri_ << ") has been stuck at " << current_progress << " of " << dltotal + ultotal << " bytes for " << now - that->last_progress_timestamp_ << " seconds and will be aborted. CURL timing information: " << "lookup time: " << lookup_time << " (" << curl_easy_strerror(lookup_time_status) << "), connect time: " << connect_time << " (" << curl_easy_strerror(connect_time_status) << "), pre-transfer time: " << pretransfer_time << " (" << curl_easy_strerror(pretransfer_time_status) << "), start-transfer time: " << starttransfer_time << " (" << curl_easy_strerror(starttransfer_time_status) << ")"; return 1; } return 0; } absl::Status CurlHttpRequest::CURLcodeToStatus(CURLcode code, const char* error_buffer) { if (code == CURLE_OK) { return absl::OkStatus(); } string error_message = strings::StrCat( "Error executing an HTTP request: libcurl code ", code, " meaning '", curl_easy_strerror(code), "', error details: "); if (code == CURLE_WRITE_ERROR && IsDirectResponse() && direct_response_.bytes_received_ > direct_response_.buffer_size_) { string overflow_message = strings::StrCat( "Received ", direct_response_.bytes_received_, " response bytes ", "for a ", direct_response_.buffer_size_, "-byte buffer"); uint64 response_code = 0; const CURLcode get_response_result = libcurl_->curl_easy_getinfo( curl_, CURLINFO_RESPONSE_CODE, &response_code); if (get_response_result == CURLE_OK && response_code == 416) { return absl::OkStatus(); } return errors::FailedPrecondition( strings::StrCat(error_message, overflow_message)); } if (code == CURLE_COULDNT_RESOLVE_HOST || code == CURLE_SSL_CACERT_BADFILE) { return errors::FailedPrecondition( strings::StrCat(error_message, error_buffer)); } return errors::Unavailable( strings::StrCat(error_message, *error_buffer ? error_buffer : "(none)")); } }
#include "tsl/platform/cloud/curl_http_request.h" #include <fstream> #include <string> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/mem.h" #include "tsl/platform/path.h" #include "tsl/platform/platform.h" #include "tsl/platform/test.h" namespace tsl { namespace { const string kTestContent = "random original scratch content"; class FakeEnv : public EnvWrapper { public: FakeEnv() : EnvWrapper(Env::Default()) {} uint64 NowSeconds() const override { return now_; } uint64 now_ = 10000; }; class FakeLibCurl : public LibCurl { public: FakeLibCurl(const string& response_content, uint64 response_code) : response_content_(response_content), response_code_(response_code) {} FakeLibCurl(const string& response_content, uint64 response_code, std::vector<std::tuple<uint64, curl_off_t>> progress_ticks, FakeEnv* env) : response_content_(response_content), response_code_(response_code), progress_ticks_(std::move(progress_ticks)), env_(env) {} FakeLibCurl(const string& response_content, uint64 response_code, const std::vector<string>& response_headers) : response_content_(response_content), response_code_(response_code), response_headers_(response_headers) {} CURL* curl_easy_init() override { is_initialized_ = true; return reinterpret_cast<CURL*>(this); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, uint64 param) override { switch (option) { case CURLOPT_POST: is_post_ = param; break; case CURLOPT_PUT: is_put_ = param; break; default: break; } return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, const char* param) override { return curl_easy_setopt(curl, option, reinterpret_cast<void*>(const_cast<char*>(param))); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, void* param) override { switch (option) { case CURLOPT_URL: url_ = reinterpret_cast<char*>(param); break; case CURLOPT_RANGE: range_ = reinterpret_cast<char*>(param); break; case CURLOPT_CUSTOMREQUEST: custom_request_ = reinterpret_cast<char*>(param); break; case CURLOPT_HTTPHEADER: headers_ = reinterpret_cast<std::vector<string>*>(param); break; case CURLOPT_ERRORBUFFER: error_buffer_ = reinterpret_cast<char*>(param); break; case CURLOPT_CAINFO: ca_info_ = reinterpret_cast<char*>(param); break; case CURLOPT_WRITEDATA: write_data_ = reinterpret_cast<FILE*>(param); break; case CURLOPT_HEADERDATA: header_data_ = reinterpret_cast<FILE*>(param); break; case CURLOPT_READDATA: read_data_ = reinterpret_cast<FILE*>(param); break; case CURLOPT_XFERINFODATA: progress_data_ = param; break; default: break; } return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(void*, size_t, size_t, FILE*)) override { read_callback_ = param; return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(const void*, size_t, size_t, void*)) override { switch (option) { case CURLOPT_WRITEFUNCTION: write_callback_ = param; break; case CURLOPT_HEADERFUNCTION: header_callback_ = param; break; default: break; } return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, int (*param)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)) override { progress_callback_ = param; return CURLE_OK; } CURLcode curl_easy_perform(CURL* curl) override { if (is_post_ || is_put_) { char buffer[3]; int bytes_read; posted_content_ = ""; do { bytes_read = read_callback_(buffer, 1, sizeof(buffer), read_data_); posted_content_ = strings::StrCat( posted_content_, absl::string_view(buffer, bytes_read)); } while (bytes_read > 0); } if (write_data_ || write_callback_) { size_t bytes_handled = write_callback_( response_content_.c_str(), 1, response_content_.size(), write_data_); if (bytes_handled != response_content_.size()) { curl_easy_perform_result_ = CURLE_WRITE_ERROR; } } for (const auto& header : response_headers_) { header_callback_(header.c_str(), 1, header.size(), header_data_); } if (error_buffer_) { strncpy(error_buffer_, curl_easy_perform_error_message_.c_str(), curl_easy_perform_error_message_.size() + 1); } for (const auto& tick : progress_ticks_) { env_->now_ = std::get<0>(tick); if (progress_callback_(progress_data_, 0, std::get<1>(tick), 0, 0)) { return CURLE_ABORTED_BY_CALLBACK; } } return curl_easy_perform_result_; } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, uint64* value) override { switch (info) { case CURLINFO_RESPONSE_CODE: *value = response_code_; break; default: break; } return CURLE_OK; } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, double* value) override { switch (info) { case CURLINFO_SIZE_DOWNLOAD: *value = response_content_.size(); break; default: break; } return CURLE_OK; } void curl_easy_cleanup(CURL* curl) override { is_cleaned_up_ = true; } curl_slist* curl_slist_append(curl_slist* list, const char* str) override { std::vector<string>* v = list ? reinterpret_cast<std::vector<string>*>(list) : new std::vector<string>(); v->push_back(str); return reinterpret_cast<curl_slist*>(v); } char* curl_easy_escape(CURL* curl, const char* str, int length) override { const string victim = "/"; const string encoded = "%2F"; string temp_str = str; std::string::size_type n = 0; while ((n = temp_str.find(victim, n)) != std::string::npos) { temp_str.replace(n, victim.size(), encoded); n += encoded.size(); } char* out_char_str = reinterpret_cast<char*>( port::Malloc(sizeof(char) * temp_str.size() + 1)); std::copy(temp_str.begin(), temp_str.end(), out_char_str); out_char_str[temp_str.size()] = '\0'; return out_char_str; } void curl_slist_free_all(curl_slist* list) override { delete reinterpret_cast<std::vector<string>*>(list); } void curl_free(void* p) override { port::Free(p); } string response_content_; uint64 response_code_; std::vector<string> response_headers_; string url_; string range_; string custom_request_; string ca_info_; char* error_buffer_ = nullptr; bool is_initialized_ = false; bool is_cleaned_up_ = false; std::vector<string>* headers_ = nullptr; bool is_post_ = false; bool is_put_ = false; void* write_data_ = nullptr; size_t (*write_callback_)(const void* ptr, size_t size, size_t nmemb, void* userdata) = nullptr; void* header_data_ = nullptr; size_t (*header_callback_)(const void* ptr, size_t size, size_t nmemb, void* userdata) = nullptr; FILE* read_data_ = nullptr; size_t (*read_callback_)(void* ptr, size_t size, size_t nmemb, FILE* userdata) = &fread; int (*progress_callback_)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) = nullptr; void* progress_data_ = nullptr; string posted_content_; CURLcode curl_easy_perform_result_ = CURLE_OK; string curl_easy_perform_error_message_; std::vector<std::tuple<uint64, curl_off_t>> progress_ticks_; FakeEnv* env_ = nullptr; }; TEST(CurlHttpRequestTest, GetRequest) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("get response", string(scratch.begin(), scratch.end())); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ("", libcurl.ca_info_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_Direct) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch(100, 0); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBufferDirect(scratch.data(), scratch.capacity()); TF_EXPECT_OK(http_request.Send()); string expected_response = "get response"; size_t response_bytes_transferred = http_request.GetResultBufferDirectBytesTransferred(); EXPECT_EQ(expected_response.size(), response_bytes_transferred); EXPECT_EQ( "get response", string(scratch.begin(), scratch.begin() + response_bytes_transferred)); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ("", libcurl.ca_info_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_CustomCaInfoFlag) { static char set_var[] = "CURL_CA_BUNDLE=test"; putenv(set_var); FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("get response", string(scratch.begin(), scratch.end())); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ("test", libcurl.ca_info_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_Direct_ResponseTooLarge) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch(5, 0); http_request.SetUri("http: http_request.SetResultBufferDirect(scratch.data(), scratch.size()); const absl::Status& status = http_request.Send(); EXPECT_EQ(error::FAILED_PRECONDITION, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 23 meaning " "'Failed writing received data to disk/application', error details: " "Received 12 response bytes for a 5-byte buffer", status.message()); EXPECT_EQ(5, http_request.GetResultBufferDirectBytesTransferred()); EXPECT_EQ("get r", string(scratch.begin(), scratch.begin() + 5)); } TEST(CurlHttpRequestTest, GetRequest_Direct_RangeOutOfBound) { FakeLibCurl libcurl("get response", 416); CurlHttpRequest http_request(&libcurl); const string initialScratch = "abcde"; std::vector<char> scratch; scratch.insert(scratch.end(), initialScratch.begin(), initialScratch.end()); http_request.SetUri("http: http_request.SetRange(0, 4); http_request.SetResultBufferDirect(scratch.data(), scratch.size()); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ(416, http_request.GetResponseCode()); EXPECT_EQ(0, http_request.GetResultBufferDirectBytesTransferred()); EXPECT_EQ("get r", string(scratch.begin(), scratch.end())); } TEST(CurlHttpRequestTest, GetRequest_Empty) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.resize(0); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(scratch.empty()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_RangeOutOfBound) { FakeLibCurl libcurl("get response", 416); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(scratch.empty()); EXPECT_EQ(416, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_503) { FakeLibCurl libcurl("get response", 503); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: http_request.SetResultBuffer(&scratch); const auto& status = http_request.Send(); EXPECT_EQ(error::UNAVAILABLE, status.code()); EXPECT_EQ( "Error executing an HTTP request: HTTP response code 503 with body " "'get response'", status.message()); } TEST(CurlHttpRequestTest, GetRequest_HttpCode0) { FakeLibCurl libcurl("get response", 0); libcurl.curl_easy_perform_result_ = CURLE_OPERATION_TIMEDOUT; libcurl.curl_easy_perform_error_message_ = "Operation timed out"; CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: const auto& status = http_request.Send(); EXPECT_EQ(error::UNAVAILABLE, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 28 meaning " "'Timeout was reached', error details: Operation timed out", status.message()); EXPECT_EQ(0, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_CouldntResolveHost) { FakeLibCurl libcurl("get response", 0); libcurl.curl_easy_perform_result_ = CURLE_COULDNT_RESOLVE_HOST; libcurl.curl_easy_perform_error_message_ = "Could not resolve host 'metadata'"; CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: const auto& status = http_request.Send(); EXPECT_EQ(error::FAILED_PRECONDITION, status.code()); EXPECT_EQ( absl::StrCat( "Error executing an HTTP request: libcurl code 6 meaning ", (kIsOpenSource ? "'Couldn't resolve host name', error details: " : "'Could not resolve hostname', error details: "), "Could not resolve host ", "'metadata'"), status.message()); EXPECT_EQ(0, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_SslBadCertfile) { FakeLibCurl libcurl("get response", 0); libcurl.curl_easy_perform_result_ = CURLE_SSL_CACERT_BADFILE; libcurl.curl_easy_perform_error_message_ = "error setting certificate verify locations:"; CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: const auto& status = http_request.Send(); EXPECT_EQ(error::FAILED_PRECONDITION, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 77 meaning " "'Problem with the SSL CA cert (path? access rights?)', error details: " "error setting certificate verify locations:", status.message()); EXPECT_EQ(0, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, ResponseHeaders) { FakeLibCurl libcurl( "get response", 200, {"Location: abcd", "Content-Type: text", "unparsable header"}); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("abcd", http_request.GetResponseHeader("Location")); EXPECT_EQ("text", http_request.GetResponseHeader("Content-Type")); EXPECT_EQ("", http_request.GetResponseHeader("Not-Seen-Header")); } TEST(CurlHttpRequestTest, PutRequest_WithBody_FromFile) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); auto content_filename = io::JoinPath(testing::TmpDir(), "content"); std::ofstream content(content_filename, std::ofstream::binary); content << "post body content"; content.close(); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); TF_EXPECT_OK(http_request.SetPutFromFile(content_filename, 0)); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(2, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 17", (*libcurl.headers_)[1]); EXPECT_TRUE(libcurl.is_put_); EXPECT_EQ("post body content", libcurl.posted_content_); std::remove(content_filename.c_str()); } TEST(CurlHttpRequestTest, PutRequest_WithBody_FromFile_NonZeroOffset) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); auto content_filename = io::JoinPath(testing::TmpDir(), "content"); std::ofstream content(content_filename, std::ofstream::binary); content << "post body content"; content.close(); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); TF_EXPECT_OK(http_request.SetPutFromFile(content_filename, 7)); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("dy content", libcurl.posted_content_); std::remove(content_filename.c_str()); } TEST(CurlHttpRequestTest, PutRequest_WithoutBody) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPutEmptyBody(); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(3, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 0", (*libcurl.headers_)[1]); EXPECT_EQ("Transfer-Encoding: identity", (*libcurl.headers_)[2]); EXPECT_TRUE(libcurl.is_put_); EXPECT_EQ("", libcurl.posted_content_); } TEST(CurlHttpRequestTest, PostRequest_WithBody_FromMemory) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); string content = "post body content"; http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPostFromBuffer(content.c_str(), content.size()); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(2, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 17", (*libcurl.headers_)[1]); EXPECT_TRUE(libcurl.is_post_); EXPECT_EQ("post body content", libcurl.posted_content_); } TEST(CurlHttpRequestTest, PostRequest_WithoutBody) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPostEmptyBody(); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(3, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 0", (*libcurl.headers_)[1]); EXPECT_EQ("Transfer-Encoding: identity", (*libcurl.headers_)[2]); EXPECT_TRUE(libcurl.is_post_); EXPECT_EQ("", libcurl.posted_content_); } TEST(CurlHttpRequestTest, DeleteRequest) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetDeleteRequest(); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("DELETE", libcurl.custom_request_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_NoUri) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); ASSERT_DEATH((void)http_request.Send(), "URI has not been set"); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_TwoSends) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); ASSERT_DEATH((void)http_request.Send(), "The request has already been sent"); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_ReusingAfterSend) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); ASSERT_DEATH(http_request.SetUri("http: "The request has already been sent"); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_SettingMethodTwice) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetDeleteRequest(); ASSERT_DEATH(http_request.SetPostEmptyBody(), "HTTP method has been already set"); } TEST(CurlHttpRequestTest, EscapeString) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); const string test_string = "a/b/c"; EXPECT_EQ("a%2Fb%2Fc", http_request.EscapeString(test_string)); } TEST(CurlHttpRequestTest, ErrorReturnsNoResponse) { FakeLibCurl libcurl("get response", 500); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); EXPECT_EQ(error::UNAVAILABLE, http_request.Send().code()); EXPECT_EQ("", string(scratch.begin(), scratch.end())); } TEST(CurlHttpRequestTest, ProgressIsOk) { FakeEnv env; FakeLibCurl libcurl( "test", 200, { std::make_tuple(100, 0) , std::make_tuple(110, 0) , std::make_tuple(200, 100) }, &env); CurlHttpRequest http_request(&libcurl, &env); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); } TEST(CurlHttpRequestTest, ProgressIsStuck) { FakeEnv env; FakeLibCurl libcurl( "test", 200, { std::make_tuple(100, 10) , std::make_tuple(130, 10) , std::make_tuple(170, 10) }, &env); CurlHttpRequest http_request(&libcurl, &env); http_request.SetUri("http: auto status = http_request.Send(); EXPECT_EQ(error::UNAVAILABLE, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 42 meaning 'Operation " "was aborted by an application callback', error details: (none)", status.message()); } class TestStats : public HttpRequest::RequestStats { public: ~TestStats() override = default; void RecordRequest(const HttpRequest* request, const string& uri, HttpRequest::RequestMethod method) override { has_recorded_request_ = true; record_request_request_ = request; record_request_uri_ = uri; record_request_method_ = method; } void RecordResponse(const HttpRequest* request, const string& uri, HttpRequest::RequestMethod method, const absl::Status& result) override { has_recorded_response_ = true; record_response_request_ = request; record_response_uri_ = uri; record_response_method_ = method; record_response_result_ = result; } const HttpRequest* record_request_request_ = nullptr; string record_request_uri_ = "http: HttpRequest::RequestMethod record_request_method_ = HttpRequest::RequestMethod::kGet; const HttpRequest* record_response_request_ = nullptr; string record_response_uri_ = "http: HttpRequest::RequestMethod record_response_method_ = HttpRequest::RequestMethod::kGet; absl::Status record_response_result_; bool has_recorded_request_ = false; bool has_recorded_response_ = false; }; class StatsTestFakeLibCurl : public FakeLibCurl { public: StatsTestFakeLibCurl(TestStats* stats, const string& response_content, uint64 response_code) : FakeLibCurl(response_content, response_code), stats_(stats) {} CURLcode curl_easy_perform(CURL* curl) override { CHECK(!performed_request_); performed_request_ = true; stats_had_recorded_request_ = stats_->has_recorded_request_; stats_had_recorded_response_ = stats_->has_recorded_response_; return FakeLibCurl::curl_easy_perform(curl); }; TestStats* stats_; bool performed_request_ = false; bool stats_had_recorded_request_; bool stats_had_recorded_response_; }; TEST(CurlHttpRequestTest, StatsGetSuccessful) { TestStats stats; StatsTestFakeLibCurl libcurl(&stats, "get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetRequestStats(&stats); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("get response", string(scratch.begin(), scratch.end())); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_response_method_); TF_EXPECT_OK(stats.record_response_result_); EXPECT_TRUE(libcurl.performed_request_); EXPECT_TRUE(libcurl.stats_had_recorded_request_); EXPECT_FALSE(libcurl.stats_had_recorded_response_); } TEST(CurlHttpRequestTest, StatsGetNotFound) { TestStats stats; StatsTestFakeLibCurl libcurl(&stats, "get other response", 404); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetRequestStats(&stats); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); absl::Status s = http_request.Send(); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_response_method_); EXPECT_TRUE(absl::IsNotFound(stats.record_response_result_)); EXPECT_EQ(s, stats.record_response_result_); EXPECT_TRUE(libcurl.performed_request_); EXPECT_TRUE(libcurl.stats_had_recorded_request_); EXPECT_FALSE(libcurl.stats_had_recorded_response_); } TEST(CurlHttpRequestTest, StatsPost) { TestStats stats; FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetRequestStats(&stats); string content = "post body content"; http_request.SetUri("http: http_request.SetPostFromBuffer(content.c_str(), content.size()); TF_EXPECT_OK(http_request.Send()); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kPost, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kPost, stats.record_response_method_); TF_EXPECT_OK(stats.record_response_result_); } TEST(CurlHttpRequestTest, StatsDelete) { TestStats stats; FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetRequestStats(&stats); http_request.SetUri("http: http_request.SetDeleteRequest(); TF_EXPECT_OK(http_request.Send()); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kDelete, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kDelete, stats.record_response_method_); TF_EXPECT_OK(stats.record_response_result_); } TEST(CurlHttpRequestTest, StatsPut) { TestStats stats; FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetRequestStats(&stats); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPutEmptyBody(); TF_EXPECT_OK(http_request.Send()); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kPut, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kPut, stats.record_response_method_); TF_EXPECT_OK(stats.record_response_result_); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/curl_http_request.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/curl_http_request_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
12baf40e-b534-4352-b6aa-687b3a4cd554
cpp
google/tsl
oauth_client
tsl/platform/cloud/oauth_client.cc
tsl/platform/cloud/oauth_client_test.cc
#include "tsl/platform/cloud/oauth_client.h" #ifndef _WIN32 #include <pwd.h> #include <sys/types.h> #include <unistd.h> #else #include <sys/types.h> #endif #include <fstream> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include "tsl/platform/base64.h" #include "tsl/platform/cloud/curl_http_request.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" namespace tsl { namespace { constexpr int kRequestedTokenLifetimeSec = 3600; constexpr char kCryptoAlgorithm[] = "RS256"; constexpr char kJwtType[] = "JWT"; constexpr char kGrantType[] = "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer"; absl::Status ReadJsonValue(const Json::Value& json, const string& name, Json::Value* value) { if (!value) { return errors::FailedPrecondition("'value' cannot be nullptr."); } *value = json.get(name, Json::Value::null); if (*value == Json::Value::null) { return errors::FailedPrecondition( strings::StrCat("Couldn't read a JSON value '", name, "'.")); } return absl::OkStatus(); } absl::Status ReadJsonString(const Json::Value& json, const string& name, string* value) { Json::Value json_value; TF_RETURN_IF_ERROR(ReadJsonValue(json, name, &json_value)); if (!json_value.isString()) { return errors::FailedPrecondition( strings::StrCat("JSON value '", name, "' is not string.")); } *value = json_value.asString(); return absl::OkStatus(); } absl::Status ReadJsonInt(const Json::Value& json, const string& name, int64_t* value) { Json::Value json_value; TF_RETURN_IF_ERROR(ReadJsonValue(json, name, &json_value)); if (!json_value.isIntegral()) { return errors::FailedPrecondition( strings::StrCat("JSON value '", name, "' is not integer.")); } *value = json_value.asInt64(); return absl::OkStatus(); } absl::Status CreateSignature(RSA* private_key, absl::string_view to_sign, string* signature) { if (!private_key || !signature) { return errors::FailedPrecondition( "'private_key' and 'signature' cannot be nullptr."); } const auto md = EVP_sha256(); if (!md) { return errors::Internal("Could not get a sha256 encryptor."); } std::unique_ptr<EVP_MD_CTX, std::function<void(EVP_MD_CTX*)>> md_ctx( EVP_MD_CTX_create(), [](EVP_MD_CTX* ptr) { EVP_MD_CTX_destroy(ptr); }); if (!md_ctx) { return errors::Internal("Could not create MD_CTX."); } std::unique_ptr<EVP_PKEY, std::function<void(EVP_PKEY*)>> key( EVP_PKEY_new(), [](EVP_PKEY* ptr) { EVP_PKEY_free(ptr); }); EVP_PKEY_set1_RSA(key.get(), private_key); if (EVP_DigestSignInit(md_ctx.get(), nullptr, md, nullptr, key.get()) != 1) { return errors::Internal("DigestInit failed."); } if (EVP_DigestSignUpdate(md_ctx.get(), to_sign.data(), to_sign.size()) != 1) { return errors::Internal("DigestUpdate failed."); } size_t sig_len = 0; if (EVP_DigestSignFinal(md_ctx.get(), nullptr, &sig_len) != 1) { return errors::Internal("DigestFinal (get signature length) failed."); } std::unique_ptr<unsigned char[]> sig(new unsigned char[sig_len]); if (EVP_DigestSignFinal(md_ctx.get(), sig.get(), &sig_len) != 1) { return errors::Internal("DigestFinal (signature compute) failed."); } return Base64Encode( absl::string_view(reinterpret_cast<char*>(sig.get()), sig_len), signature); } absl::Status EncodeJwtClaim(absl::string_view client_email, absl::string_view scope, absl::string_view audience, uint64 request_timestamp_sec, string* encoded) { Json::Value root; root["iss"] = Json::Value(client_email.data(), client_email.data() + client_email.size()); root["scope"] = Json::Value(scope.data(), scope.data() + scope.size()); root["aud"] = Json::Value(audience.data(), audience.data() + audience.size()); const auto expiration_timestamp_sec = request_timestamp_sec + kRequestedTokenLifetimeSec; root["iat"] = Json::Value::UInt64(request_timestamp_sec); root["exp"] = Json::Value::UInt64(expiration_timestamp_sec); string claim = root.toStyledString(); return Base64Encode(claim, encoded); } absl::Status EncodeJwtHeader(absl::string_view key_id, string* encoded) { Json::Value root; root["alg"] = kCryptoAlgorithm; root["typ"] = kJwtType; root["kid"] = Json::Value(key_id.data(), key_id.data() + key_id.size()); const string header = root.toStyledString(); return Base64Encode(header, encoded); } } OAuthClient::OAuthClient() : OAuthClient( std::unique_ptr<HttpRequest::Factory>(new CurlHttpRequest::Factory()), Env::Default()) {} OAuthClient::OAuthClient( std::unique_ptr<HttpRequest::Factory> http_request_factory, Env* env) : http_request_factory_(std::move(http_request_factory)), env_(env) {} absl::Status OAuthClient::GetTokenFromServiceAccountJson( Json::Value json, absl::string_view oauth_server_uri, absl::string_view scope, string* token, uint64* expiration_timestamp_sec) { if (!token || !expiration_timestamp_sec) { return errors::FailedPrecondition( "'token' and 'expiration_timestamp_sec' cannot be nullptr."); } string private_key_serialized, private_key_id, client_id, client_email; TF_RETURN_IF_ERROR( ReadJsonString(json, "private_key", &private_key_serialized)); TF_RETURN_IF_ERROR(ReadJsonString(json, "private_key_id", &private_key_id)); TF_RETURN_IF_ERROR(ReadJsonString(json, "client_id", &client_id)); TF_RETURN_IF_ERROR(ReadJsonString(json, "client_email", &client_email)); std::unique_ptr<BIO, std::function<void(BIO*)>> bio( BIO_new(BIO_s_mem()), [](BIO* ptr) { BIO_free_all(ptr); }); if (BIO_puts(bio.get(), private_key_serialized.c_str()) != static_cast<int>(private_key_serialized.size())) { return errors::Internal("Could not load the private key."); } std::unique_ptr<RSA, std::function<void(RSA*)>> private_key( PEM_read_bio_RSAPrivateKey(bio.get(), nullptr, nullptr, nullptr), [](RSA* ptr) { RSA_free(ptr); }); if (!private_key) { return errors::Internal("Could not deserialize the private key."); } const uint64 request_timestamp_sec = env_->NowSeconds(); string encoded_claim, encoded_header; TF_RETURN_IF_ERROR(EncodeJwtHeader(private_key_id, &encoded_header)); TF_RETURN_IF_ERROR(EncodeJwtClaim(client_email, scope, oauth_server_uri, request_timestamp_sec, &encoded_claim)); const string to_sign = encoded_header + "." + encoded_claim; string signature; TF_RETURN_IF_ERROR(CreateSignature(private_key.get(), to_sign, &signature)); const string jwt = to_sign + "." + signature; const string request_body = strings::StrCat("grant_type=", kGrantType, "&assertion=", jwt); std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); std::vector<char> response_buffer; request->SetUri(string(oauth_server_uri)); request->SetPostFromBuffer(request_body.c_str(), request_body.size()); request->SetResultBuffer(&response_buffer); TF_RETURN_IF_ERROR(request->Send()); absl::string_view response = absl::string_view(response_buffer.data(), response_buffer.size()); TF_RETURN_IF_ERROR(ParseOAuthResponse(response, request_timestamp_sec, token, expiration_timestamp_sec)); return absl::OkStatus(); } absl::Status OAuthClient::GetTokenFromRefreshTokenJson( Json::Value json, absl::string_view oauth_server_uri, string* token, uint64* expiration_timestamp_sec) { if (!token || !expiration_timestamp_sec) { return errors::FailedPrecondition( "'token' and 'expiration_timestamp_sec' cannot be nullptr."); } string client_id, client_secret, refresh_token; TF_RETURN_IF_ERROR(ReadJsonString(json, "client_id", &client_id)); TF_RETURN_IF_ERROR(ReadJsonString(json, "client_secret", &client_secret)); TF_RETURN_IF_ERROR(ReadJsonString(json, "refresh_token", &refresh_token)); const auto request_body = strings::StrCat( "client_id=", client_id, "&client_secret=", client_secret, "&refresh_token=", refresh_token, "&grant_type=refresh_token"); const uint64 request_timestamp_sec = env_->NowSeconds(); std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); std::vector<char> response_buffer; request->SetUri(string(oauth_server_uri)); request->SetPostFromBuffer(request_body.c_str(), request_body.size()); request->SetResultBuffer(&response_buffer); TF_RETURN_IF_ERROR(request->Send()); absl::string_view response = absl::string_view(response_buffer.data(), response_buffer.size()); TF_RETURN_IF_ERROR(ParseOAuthResponse(response, request_timestamp_sec, token, expiration_timestamp_sec)); return absl::OkStatus(); } absl::Status OAuthClient::ParseOAuthResponse(absl::string_view response, uint64 request_timestamp_sec, string* token, uint64* expiration_timestamp_sec) { if (!token || !expiration_timestamp_sec) { return errors::FailedPrecondition( "'token' and 'expiration_timestamp_sec' cannot be nullptr."); } Json::Value root; Json::Reader reader; if (!reader.parse(response.data(), response.data() + response.size(), root)) { return errors::Internal("Couldn't parse JSON response from OAuth server."); } string token_type; TF_RETURN_IF_ERROR(ReadJsonString(root, "token_type", &token_type)); if (token_type != "Bearer") { return errors::FailedPrecondition("Unexpected Oauth token type: " + token_type); } int64_t expires_in = 0; TF_RETURN_IF_ERROR(ReadJsonInt(root, "expires_in", &expires_in)); *expiration_timestamp_sec = request_timestamp_sec + expires_in; TF_RETURN_IF_ERROR(ReadJsonString(root, "access_token", token)); return absl::OkStatus(); } }
#include "tsl/platform/cloud/oauth_client.h" #include <fstream> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/pem.h> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/base64.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/env.h" #include "tsl/platform/path.h" #include "tsl/platform/scanner.h" #include "tsl/platform/test.h" namespace tsl { namespace { string TestData() { return io::JoinPath(testing::TslSrcRoot(), "platform", "cloud", "testdata"); } constexpr char kTokenJson[] = R"( { "access_token":"WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", "expires_in":3920, "token_type":"Bearer" })"; class FakeEnv : public EnvWrapper { public: FakeEnv() : EnvWrapper(Env::Default()) {} uint64 NowSeconds() const override { return now; } uint64 now = 10000; }; } TEST(OAuthClientTest, ParseOAuthResponse) { const uint64 request_timestamp = 100; string token; uint64 expiration_timestamp; TF_EXPECT_OK(OAuthClient().ParseOAuthResponse(kTokenJson, request_timestamp, &token, &expiration_timestamp)); EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token); EXPECT_EQ(4020, expiration_timestamp); } TEST(OAuthClientTest, GetTokenFromRefreshTokenJson) { const string credentials_json = R"( { "client_id": "test_client_id", "client_secret": "@@@test_client_secret@@@", "refresh_token": "test_refresh_token", "type": "authorized_user" })"; Json::Value json; Json::Reader reader; ASSERT_TRUE(reader.parse(credentials_json, json)); std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Post body: client_id=test_client_id&" "client_secret=@@@test_client_secret@@@&" "refresh_token=test_refresh_token&grant_type=refresh_token\n", kTokenJson)}); FakeEnv env; OAuthClient client(std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), &env); string token; uint64 expiration_timestamp; TF_EXPECT_OK(client.GetTokenFromRefreshTokenJson( json, "https: &expiration_timestamp)); EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token); EXPECT_EQ(13920, expiration_timestamp); } TEST(OAuthClientTest, GetTokenFromServiceAccountJson) { std::ifstream credentials( io::JoinPath(TestData(), "service_account_credentials.json")); ASSERT_TRUE(credentials.is_open()); Json::Value json; Json::Reader reader; ASSERT_TRUE(reader.parse(credentials, json)); string post_body; std::vector<HttpRequest*> requests( {new FakeHttpRequest("Uri: https: kTokenJson, &post_body)}); FakeEnv env; OAuthClient client(std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), &env); string token; uint64 expiration_timestamp; TF_EXPECT_OK(client.GetTokenFromServiceAccountJson( json, "https: "https: EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token); EXPECT_EQ(13920, expiration_timestamp); absl::string_view grant_type, assertion; ASSERT_TRUE(strings::Scanner(post_body) .OneLiteral("grant_type=") .RestartCapture() .ScanEscapedUntil('&') .StopCapture() .OneLiteral("&assertion=") .GetResult(&assertion, &grant_type)); EXPECT_EQ("urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer", grant_type); int last_dot = assertion.rfind('.'); string header_dot_claim(assertion.substr(0, last_dot)); string signature_encoded(assertion.substr(last_dot + 1)); std::ifstream public_key_stream( io::JoinPath(TestData(), "service_account_public_key.txt")); string public_key_serialized( (std::istreambuf_iterator<char>(public_key_stream)), (std::istreambuf_iterator<char>())); auto bio = BIO_new(BIO_s_mem()); RSA* public_key = nullptr; EXPECT_EQ(public_key_serialized.size(), BIO_puts(bio, public_key_serialized.c_str())); public_key = PEM_read_bio_RSA_PUBKEY(bio, nullptr, nullptr, nullptr); EXPECT_TRUE(public_key) << "Could not load the public key from testdata."; string signature; TF_EXPECT_OK(Base64Decode(signature_encoded, &signature)); const auto md = EVP_sha256(); auto md_ctx = EVP_MD_CTX_create(); auto key = EVP_PKEY_new(); EVP_PKEY_set1_RSA(key, public_key); ASSERT_EQ(1, EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key)); ASSERT_EQ(1, EVP_DigestVerifyUpdate(md_ctx, header_dot_claim.c_str(), header_dot_claim.size())); ASSERT_EQ(1, EVP_DigestVerifyFinal( md_ctx, const_cast<unsigned char*>( reinterpret_cast<const unsigned char*>(signature.data())), signature.size())); EVP_PKEY_free(key); EVP_MD_CTX_destroy(md_ctx); RSA_free(public_key); BIO_free_all(bio); int dot = header_dot_claim.find_last_of('.'); string header_encoded = header_dot_claim.substr(0, dot); string claim_encoded = header_dot_claim.substr(dot + 1); string header, claim; TF_EXPECT_OK(Base64Decode(header_encoded, &header)); TF_EXPECT_OK(Base64Decode(claim_encoded, &claim)); Json::Value header_json, claim_json; EXPECT_TRUE(reader.parse(header, header_json)); EXPECT_EQ("RS256", header_json.get("alg", Json::Value::null).asString()); EXPECT_EQ("JWT", header_json.get("typ", Json::Value::null).asString()); EXPECT_EQ("fake_key_id", header_json.get("kid", Json::Value::null).asString()); EXPECT_TRUE(reader.parse(claim, claim_json)); EXPECT_EQ("fake-test-project.iam.gserviceaccount.com", claim_json.get("iss", Json::Value::null).asString()); EXPECT_EQ("https: claim_json.get("scope", Json::Value::null).asString()); EXPECT_EQ("https: claim_json.get("aud", Json::Value::null).asString()); EXPECT_EQ(10000, claim_json.get("iat", Json::Value::null).asInt64()); EXPECT_EQ(13600, claim_json.get("exp", Json::Value::null).asInt64()); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/oauth_client.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/oauth_client_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
61b557ea-0031-4b41-95a5-59c75cafefa9
cpp
google/tsl
stacktrace
tsl/platform/windows/stacktrace.cc
tsl/platform/stacktrace_test.cc
#include "tsl/platform/windows/stacktrace.h" #include <windows.h> #include <dbghelp.h> #include <string> #include "tsl/platform/mutex.h" #pragma comment(lib, "dbghelp.lib") namespace tsl { static bool SymbolsAreAvailableInit() { SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS); return SymInitialize(GetCurrentProcess(), NULL, true); } static bool SymbolsAreAvailable() { static bool kSymbolsAvailable = SymbolsAreAvailableInit(); return kSymbolsAvailable; } std::string CurrentStackTrace() { HANDLE current_process = GetCurrentProcess(); static constexpr int kMaxStackFrames = 64; void* trace[kMaxStackFrames]; int num_frames = CaptureStackBackTrace(0, kMaxStackFrames, trace, NULL); static mutex mu(tsl::LINKER_INITIALIZED); std::string stacktrace; for (int i = 0; i < num_frames; ++i) { const char* symbol = "(unknown)"; if (SymbolsAreAvailable()) { char symbol_info_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; SYMBOL_INFO* symbol_ptr = reinterpret_cast<SYMBOL_INFO*>(symbol_info_buffer); symbol_ptr->SizeOfStruct = sizeof(SYMBOL_INFO); symbol_ptr->MaxNameLen = MAX_SYM_NAME; mutex_lock lock(mu); if (SymFromAddr(current_process, reinterpret_cast<DWORD64>(trace[i]), 0, symbol_ptr)) { symbol = symbol_ptr->Name; } } char buffer[256]; snprintf(buffer, sizeof(buffer), "0x%p\t%s", trace[i], symbol); stacktrace += buffer; stacktrace += "\n"; } return stacktrace; } }
#include "tsl/platform/stacktrace.h" #include <string> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace { #if defined(TF_HAS_STACKTRACE) TEST(StacktraceTest, StacktraceWorks) { std::string stacktrace = CurrentStackTrace(); LOG(INFO) << "CurrentStackTrace():\n" << stacktrace; std::string expected_frame = "testing::internal::UnitTestImpl::RunAllTests"; EXPECT_NE(stacktrace.find(expected_frame), std::string::npos); } #endif } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/windows/stacktrace.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/stacktrace_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
f77f6e8b-a1cc-4173-9990-9cc19dbace1f
cpp
google/tsl
profiler_factory
tsl/profiler/lib/profiler_factory.cc
tsl/profiler/lib/profiler_factory_test.cc
#include "tsl/profiler/lib/profiler_factory.h" #include <memory> #include <utility> #include <vector> #include "tsl/platform/mutex.h" #include "tsl/profiler/lib/profiler_controller.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { namespace { mutex mu(LINKER_INITIALIZED); std::vector<ProfilerFactory>* GetFactories() { static auto factories = new std::vector<ProfilerFactory>(); return factories; } } void RegisterProfilerFactory(ProfilerFactory factory) { mutex_lock lock(mu); GetFactories()->push_back(std::move(factory)); } std::vector<std::unique_ptr<profiler::ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options) { std::vector<std::unique_ptr<profiler::ProfilerInterface>> result; mutex_lock lock(mu); for (const auto& factory : *GetFactories()) { auto profiler = factory(options); if (profiler == nullptr) continue; result.emplace_back( std::make_unique<ProfilerController>(std::move(profiler))); } return result; } void ClearRegisteredProfilersForTest() { mutex_lock lock(mu); GetFactories()->clear(); } } }
#include "tsl/profiler/lib/profiler_factory.h" #include <functional> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { namespace { class TestProfiler : public ProfilerInterface { public: absl::Status Start() override { return absl::OkStatus(); } absl::Status Stop() override { return absl::OkStatus(); } absl::Status CollectData(tensorflow::profiler::XSpace*) override { return absl::OkStatus(); } }; std::unique_ptr<ProfilerInterface> TestFactoryFunction( const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); } TEST(ProfilerFactoryTest, FactoryFunctionPointer) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&TestFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } TEST(ProfilerFactoryTest, FactoryLambda) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory([](const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } std::unique_ptr<ProfilerInterface> NullFactoryFunction( const tensorflow::ProfileOptions& options) { return nullptr; } TEST(ProfilerFactoryTest, FactoryReturnsNull) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&NullFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_TRUE(profilers.empty()); } class FactoryClass { public: explicit FactoryClass(void* ptr) : ptr_(ptr) {} FactoryClass(const FactoryClass&) = default; FactoryClass(FactoryClass&&) = default; std::unique_ptr<ProfilerInterface> CreateProfiler( const tensorflow::ProfileOptions& options) const { return absl::make_unique<TestProfiler>(); } private: void* ptr_ TF_ATTRIBUTE_UNUSED = nullptr; }; TEST(ProfilerFactoryTest, FactoryClassCapturedByLambda) { ClearRegisteredProfilersForTest(); static int token = 42; FactoryClass factory(&token); RegisterProfilerFactory([factory = std::move(factory)]( const tensorflow::ProfileOptions& options) { return factory.CreateProfiler(options); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/profiler_factory.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/profiler_factory_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
5d2f5fb7-de86-458c-82b0-78cdc36d7eeb
cpp
google/tsl
profiler_lock
tsl/profiler/lib/profiler_lock.cc
tsl/profiler/lib/profiler_lock_test.cc
#include "tsl/profiler/lib/profiler_lock.h" #include <atomic> #include "absl/status/statusor.h" #include "xla/tsl/util/env_var.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { namespace { std::atomic<int> g_session_active = ATOMIC_VAR_INIT(0); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } bool ProfilerLock::HasActiveSession() { return g_session_active.load(std::memory_order_relaxed) != 0; } absl::StatusOr<ProfilerLock> ProfilerLock::Acquire() { static bool tf_profiler_disabled = [] { bool disabled = false; ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError(); return disabled; }(); if (TF_PREDICT_FALSE(tf_profiler_disabled)) { return errors::AlreadyExists( "TensorFlow Profiler is permanently disabled by env var " "TF_DISABLE_PROFILING."); } int already_active = g_session_active.exchange(1, std::memory_order_acq_rel); if (already_active) { return errors::AlreadyExists(kProfilerLockContention); } return ProfilerLock(true); } void ProfilerLock::ReleaseIfActive() { if (active_) { g_session_active.store(0, std::memory_order_release); active_ = false; } } } }
#include "tsl/profiler/lib/profiler_lock.h" #include <utility> #include "absl/status/statusor.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(ProfilerLockTest, DefaultConstructorCreatesInactiveInstance) { ProfilerLock profiler_lock; EXPECT_FALSE(profiler_lock.Active()); } TEST(ProfilerLockTest, AcquireAndReleaseExplicitly) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); profiler_lock->ReleaseIfActive(); EXPECT_FALSE(profiler_lock->Active()); } TEST(ProfilerLockTest, AcquireAndReleaseOnDestruction) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); } TEST(ProfilerLockTest, ReacquireWithoutReleaseFails) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); absl::StatusOr<ProfilerLock> profiler_lock_2 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); EXPECT_TRUE(profiler_lock_1->Active()); EXPECT_FALSE(profiler_lock_2.ok()); } TEST(ProfilerLockTest, ReacquireAfterReleaseSucceeds) { auto profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); profiler_lock_1->ReleaseIfActive(); ASSERT_FALSE(profiler_lock_1->Active()); auto profiler_lock_2 = ProfilerLock::Acquire(); EXPECT_TRUE(profiler_lock_2.ok()); EXPECT_TRUE(profiler_lock_2->Active()); } TEST(ProfilerLockTest, InactiveAfterMove) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); ProfilerLock profiler_lock_2 = std::move(*profiler_lock_1); EXPECT_FALSE(profiler_lock_1->Active()); EXPECT_TRUE(profiler_lock_2.Active()); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/profiler_lock.cc
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/profiler_lock_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
eb2df994-4722-456c-b7b4-40583fe8b690
cpp
google/tsl
stringpiece
tsl/platform/stringpiece.h
tsl/platform/stringpiece_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_STRINGPIECE_H_ #define TENSORFLOW_TSL_PLATFORM_STRINGPIECE_H_ #include "absl/base/macros.h" #include "absl/strings/string_view.h" #ifndef ABSL_DEPRECATE_AND_INLINE #define ABSL_DEPRECATE_AND_INLINE() #endif namespace tsl { using StringPiece ABSL_DEPRECATE_AND_INLINE() = absl::string_view; } #endif
#include "tsl/platform/stringpiece.h" #include <unordered_map> #include "tsl/platform/test.h" namespace tsl { TEST(StringPiece, Ctor) { { const char* hello = "hello"; absl::string_view s20(hello); EXPECT_TRUE(s20.data() == hello); EXPECT_EQ(5, s20.size()); absl::string_view s21(hello, 4); EXPECT_TRUE(s21.data() == hello); EXPECT_EQ(4, s21.size()); absl::string_view s22(hello, 6); EXPECT_TRUE(s22.data() == hello); EXPECT_EQ(6, s22.size()); } { string hola = "hola"; absl::string_view s30(hola); EXPECT_TRUE(s30.data() == hola.data()); EXPECT_EQ(4, s30.size()); hola.push_back('\0'); hola.append("h2"); hola.push_back('\0'); absl::string_view s31(hola); EXPECT_TRUE(s31.data() == hola.data()); EXPECT_EQ(8, s31.size()); } } TEST(StringPiece, ConversionToString) { EXPECT_EQ("", string(absl::string_view(""))); EXPECT_EQ("foo", string(absl::string_view("foo"))); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/stringpiece.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/stringpiece_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
ad98af36-7b78-4dc3-9d69-3e4820bc3231
cpp
google/tsl
intrusive_ptr
tsl/platform/intrusive_ptr.h
tsl/platform/intrusive_ptr_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_INTRUSIVE_PTR_H_ #define TENSORFLOW_TSL_PLATFORM_INTRUSIVE_PTR_H_ #include <algorithm> namespace tsl { namespace core { template <class T> class IntrusivePtr { public: IntrusivePtr(T* h, bool add_ref) { reset(h, add_ref); } IntrusivePtr(const IntrusivePtr& o) { reset(o.handle_, true); } IntrusivePtr(IntrusivePtr&& o) noexcept { *this = std::move(o); } IntrusivePtr() {} void reset(T* h, bool add_ref) { if (h != handle_) { if (add_ref && h) h->Ref(); if (handle_) handle_->Unref(); handle_ = h; } } IntrusivePtr& operator=(const IntrusivePtr& o) { reset(o.handle_, true); return *this; } IntrusivePtr& operator=(IntrusivePtr&& o) noexcept { if (handle_ != o.handle_) { reset(o.detach(), false); } return *this; } bool operator==(const IntrusivePtr& o) const { return handle_ == o.handle_; } T* operator->() const { return handle_; } T& operator*() const { return *handle_; } explicit operator bool() const noexcept { return get(); } T* get() const { return handle_; } T* detach() { T* handle = handle_; handle_ = nullptr; return handle; } ~IntrusivePtr() { if (handle_) handle_->Unref(); } private: T* handle_ = nullptr; }; } } #endif
#include "tsl/platform/intrusive_ptr.h" #include "tsl/platform/refcount.h" #include "tsl/platform/test.h" namespace tsl { namespace core { namespace { TEST(IntrusivePtr, ConstructorAddRefFalse) { auto ptr = IntrusivePtr<RefCounted>(new RefCounted(), false); ASSERT_TRUE(ptr->RefCountIsOne()); } TEST(IntrusivePtr, ConstructorAddRefTrue) { auto raw = new RefCounted(); auto ptr = IntrusivePtr<RefCounted>(raw, true); ASSERT_FALSE(raw->RefCountIsOne()); raw->Unref(); ASSERT_TRUE(raw->RefCountIsOne()); } TEST(IntrusivePtr, CopyConstructor) { auto ptr1 = IntrusivePtr<RefCounted>(new RefCounted(), false); auto ptr2 = IntrusivePtr<RefCounted>(ptr1); ASSERT_FALSE(ptr2->RefCountIsOne()); } TEST(IntrusivePtr, CopyAssignment) { auto ptr1 = IntrusivePtr<RefCounted>(new RefCounted(), false); auto raw = new RefCounted(); auto ptr2 = IntrusivePtr<RefCounted>(raw, true); ptr2 = ptr1; ASSERT_EQ(ptr1.get(), ptr2.get()); ASSERT_FALSE(ptr2->RefCountIsOne()); ASSERT_TRUE(raw->RefCountIsOne()); raw->Unref(); } TEST(IntrusivePtr, CopyAssignmentIntoEmpty) { auto ptr1 = IntrusivePtr<RefCounted>(new RefCounted(), false); auto ptr2 = IntrusivePtr<RefCounted>(); ptr2 = ptr1; ASSERT_FALSE(ptr2->RefCountIsOne()); } TEST(IntrusivePtr, MoveConstructor) { auto ptr1 = IntrusivePtr<RefCounted>(new RefCounted(), false); auto ptr2 = IntrusivePtr<RefCounted>(std::move(ptr1)); ASSERT_TRUE(ptr2->RefCountIsOne()); ASSERT_EQ(ptr1.get(), nullptr); } TEST(IntrusivePtr, MoveAssignment) { auto ptr1 = IntrusivePtr<RefCounted>(new RefCounted(), false); auto ptr2 = IntrusivePtr<RefCounted>(new RefCounted(), false); ptr2 = std::move(ptr1); ASSERT_TRUE(ptr2->RefCountIsOne()); ASSERT_EQ(ptr1.get(), nullptr); } TEST(IntrusivePtr, MoveAssignmentIntoEmpty) { auto ptr1 = IntrusivePtr<RefCounted>(new RefCounted(), false); auto ptr2 = IntrusivePtr<RefCounted>(); ptr2 = std::move(ptr1); ASSERT_TRUE(ptr2->RefCountIsOne()); ASSERT_EQ(ptr1.get(), nullptr); } TEST(IntrusivePtr, MoveAssignmentAlias) { auto ptr = IntrusivePtr<RefCounted>(new RefCounted(), false); auto& ptr_alias = ptr; ptr = std::move(ptr_alias); ASSERT_TRUE(ptr->RefCountIsOne()); } TEST(IntrusivePtr, Reset) { auto ptr = IntrusivePtr<RefCounted>(new RefCounted(), false); ptr.reset(new RefCounted(), false); ASSERT_TRUE(ptr->RefCountIsOne()); } TEST(IntrusivePtr, ResetIntoEmpty) { auto ptr = IntrusivePtr<RefCounted>(); ptr.reset(new RefCounted(), false); ASSERT_TRUE(ptr->RefCountIsOne()); } TEST(IntrusivePtr, ResetAlias) { auto ptr = IntrusivePtr<RefCounted>(new RefCounted(), false); ASSERT_TRUE(ptr->RefCountIsOne()); ptr.reset(ptr.get(), false); ASSERT_TRUE(ptr->RefCountIsOne()); } TEST(IntrusivePtr, ResetRefBeforeUnref) { class Foo : public RefCounted { public: explicit Foo(char label, Foo* ptr = nullptr) : label_(label), ptr_(ptr, false) {} char label_; IntrusivePtr<Foo> ptr_; }; IntrusivePtr<Foo> x(new Foo{'a', new Foo{'b', new Foo{'c'}}}, false); x->ptr_ = x->ptr_->ptr_; } TEST(IntrusivePtr, ResetStealPtrBeforeUnref) { class Foo : public RefCounted { public: explicit Foo(char label, Foo* ptr = nullptr) : label_(label), ptr_(ptr, false) {} char label_; IntrusivePtr<Foo> ptr_; }; IntrusivePtr<Foo> x(new Foo{'a', new Foo{'b', new Foo{'c'}}}, false); x->ptr_ = std::move(x->ptr_->ptr_); } TEST(IntrusivePtr, Detach) { auto ptr = IntrusivePtr<RefCounted>(new RefCounted(), false); ASSERT_TRUE(ptr->RefCountIsOne()); auto raw = ptr.detach(); ASSERT_TRUE(raw->RefCountIsOne()); raw->Unref(); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/intrusive_ptr.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/intrusive_ptr_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
cc3ff74c-5d7d-4122-8c0c-2ae4c13a0a4d
cpp
google/tsl
tstring
tsl/platform/tstring.h
tsl/platform/tstring_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_TSTRING_H_ #define TENSORFLOW_TSL_PLATFORM_TSTRING_H_ #include <assert.h> #include <ostream> #include <string> #include "tsl/platform/cord.h" #include "tsl/platform/ctstring.h" #include "tsl/platform/platform.h" #include "tsl/platform/stringpiece.h" namespace tsl { class tstring { TF_TString tstr_; public: enum Type { SMALL = TF_TSTR_SMALL, LARGE = TF_TSTR_LARGE, OFFSET = TF_TSTR_OFFSET, VIEW = TF_TSTR_VIEW, }; class view { const char* data_; size_t size_; public: explicit view(const char* data, size_t size) : data_(data), size_(size) {} explicit view(const char* data) : data_(data), size_(::strlen(data)) {} const char* data() const { return data_; } size_t size() const { return size_; } view() = delete; view(const view&) = delete; view& operator=(const view&) = delete; }; typedef const char* const_iterator; tstring(); tstring(const std::string& str); tstring(const char* str, size_t len); tstring(const char* str); tstring(size_t n, char c); explicit tstring(const absl::string_view str); #ifdef PLATFORM_GOOGLE explicit tstring(const absl::Cord& cord); #endif tstring(const tstring& str); tstring(tstring&& str) noexcept; ~tstring(); tstring& operator=(const tstring& str); tstring& operator=(const std::string& str); tstring& operator=(const char* str); tstring& operator=(char ch); tstring& operator=(const absl::string_view str); #ifdef PLATFORM_GOOGLE tstring& operator=(const absl::Cord& cord); #endif tstring& operator=(const view& tsv); tstring& operator=(tstring&& str) noexcept; int compare(const char* str, size_t len) const; bool operator<(const tstring& o) const; bool operator>(const tstring& o) const; bool operator==(const char* str) const; bool operator==(const tstring& o) const; bool operator!=(const char* str) const; bool operator!=(const tstring& o) const; operator std::string() const; operator absl::string_view() const; #ifdef PLATFORM_GOOGLE template <typename T, typename std::enable_if<std::is_same<T, absl::AlphaNum>::value, T>::type* = nullptr> operator T() const; #endif size_t size() const; size_t length() const; size_t capacity() const; bool empty() const; Type type() const; void resize(size_t new_size, char c = 0); void resize_uninitialized(size_t new_size); void clear() noexcept; void reserve(size_t n); const_iterator begin() const; const_iterator end() const; const char* c_str() const; const char* data() const; const char& operator[](size_t i) const; const char& back() const; char* mdata(); char* data(); char& operator[](size_t i); tstring& assign(const char* str, size_t len); tstring& assign(const char* str); tstring& assign_as_view(const tstring& str); tstring& assign_as_view(const std::string& str); tstring& assign_as_view(const absl::string_view str); tstring& assign_as_view(const char* str, size_t len); tstring& assign_as_view(const char* str); tstring& append(const tstring& str); tstring& append(const char* str, size_t len); tstring& append(const char* str); tstring& append(size_t n, char c); tstring& erase(size_t pos, size_t len); tstring& insert(size_t pos, const tstring& str, size_t subpos, size_t sublen); tstring& insert(size_t pos, size_t n, char c); void swap(tstring& str) noexcept; void push_back(char ch); friend bool operator==(const char* a, const tstring& b); friend bool operator==(const std::string& a, const tstring& b); friend tstring operator+(const tstring& a, const tstring& b); friend std::ostream& operator<<(std::ostream& o, const tstring& str); friend std::hash<tstring>; }; bool operator==(const char* a, const tstring& b); bool operator==(const std::string& a, const tstring& b); tstring operator+(const tstring& a, const tstring& b); std::ostream& operator<<(std::ostream& o, const tstring& str); inline tstring::tstring() { TF_TString_Init(&tstr_); } inline tstring::tstring(const char* str, size_t len) { TF_TString_Init(&tstr_); TF_TString_Copy(&tstr_, str, len); } inline tstring::tstring(const char* str) : tstring(str, ::strlen(str)) {} inline tstring::tstring(size_t n, char c) { TF_TString_Init(&tstr_); TF_TString_Resize(&tstr_, n, c); } inline tstring::tstring(const std::string& str) : tstring(str.data(), str.size()) {} inline tstring::tstring(const absl::string_view str) : tstring(str.data(), str.size()) {} #ifdef PLATFORM_GOOGLE inline tstring::tstring(const absl::Cord& cord) { TF_TString_Init(&tstr_); TF_TString_ResizeUninitialized(&tstr_, cord.size()); cord.CopyToArray(data()); } #endif inline tstring::tstring(const tstring& str) { TF_TString_Init(&tstr_); TF_TString_Assign(&tstr_, &str.tstr_); } inline tstring::tstring(tstring&& str) noexcept { TF_TString_Init(&tstr_); TF_TString_Move(&tstr_, &str.tstr_); } inline tstring::~tstring() { TF_TString_Dealloc(&tstr_); } inline tstring& tstring::operator=(const tstring& str) { TF_TString_Assign(&tstr_, &str.tstr_); return *this; } inline tstring& tstring::operator=(const std::string& str) { TF_TString_Copy(&tstr_, str.data(), str.size()); return *this; } inline tstring& tstring::operator=(const char* str) { TF_TString_Copy(&tstr_, str, ::strlen(str)); return *this; } inline tstring& tstring::operator=(char c) { resize_uninitialized(1); (*this)[0] = c; return *this; } inline tstring& tstring::operator=(const absl::string_view str) { TF_TString_Copy(&tstr_, str.data(), str.size()); return *this; } #ifdef PLATFORM_GOOGLE inline tstring& tstring::operator=(const absl::Cord& cord) { TF_TString_ResizeUninitialized(&tstr_, cord.size()); cord.CopyToArray(data()); return *this; } #endif inline tstring& tstring::operator=(const tstring::view& tsv) { assign_as_view(tsv.data(), tsv.size()); return *this; } inline tstring& tstring::operator=(tstring&& str) noexcept { TF_TString_Move(&tstr_, &str.tstr_); return *this; } inline int tstring::compare(const char* str, size_t len) const { int ret = ::memcmp(data(), str, std::min(len, size())); if (ret < 0) return -1; if (ret > 0) return +1; if (size() < len) return -1; if (size() > len) return +1; return 0; } inline bool tstring::operator<(const tstring& o) const { return compare(o.data(), o.size()) < 0; } inline bool tstring::operator>(const tstring& o) const { return compare(o.data(), o.size()) > 0; } inline bool tstring::operator==(const char* str) const { return ::strlen(str) == size() && ::memcmp(data(), str, size()) == 0; } inline bool tstring::operator==(const tstring& o) const { return o.size() == size() && ::memcmp(data(), o.data(), size()) == 0; } inline bool tstring::operator!=(const char* str) const { return !(*this == str); } inline bool tstring::operator!=(const tstring& o) const { return !(*this == o); } inline tstring::operator std::string() const { return std::string(data(), size()); } inline tstring::operator absl::string_view() const { return absl::string_view(data(), size()); } #ifdef PLATFORM_GOOGLE template <typename T, typename std::enable_if< std::is_same<T, absl::AlphaNum>::value, T>::type*> inline tstring::operator T() const { return T(absl::string_view(*this)); } #endif inline size_t tstring::size() const { return TF_TString_GetSize(&tstr_); } inline size_t tstring::length() const { return size(); } inline size_t tstring::capacity() const { return TF_TString_GetCapacity(&tstr_); } inline bool tstring::empty() const { return size() == 0; } inline tstring::Type tstring::type() const { return static_cast<tstring::Type>(TF_TString_GetType(&tstr_)); } inline void tstring::resize(size_t new_size, char c) { TF_TString_Resize(&tstr_, new_size, c); } inline void tstring::resize_uninitialized(size_t new_size) { TF_TString_ResizeUninitialized(&tstr_, new_size); } inline void tstring::clear() noexcept { TF_TString_ResizeUninitialized(&tstr_, 0); } inline void tstring::reserve(size_t n) { TF_TString_Reserve(&tstr_, n); } inline tstring::const_iterator tstring::begin() const { return &(*this)[0]; } inline tstring::const_iterator tstring::end() const { return &(*this)[size()]; } inline const char* tstring::c_str() const { return data(); } inline const char* tstring::data() const { return TF_TString_GetDataPointer(&tstr_); } inline const char& tstring::operator[](size_t i) const { return data()[i]; } inline const char& tstring::back() const { return (*this)[size() - 1]; } inline char* tstring::mdata() { return TF_TString_GetMutableDataPointer(&tstr_); } inline char* tstring::data() { return mdata(); } inline char& tstring::operator[](size_t i) { return mdata()[i]; } inline tstring& tstring::assign(const char* str, size_t len) { TF_TString_Copy(&tstr_, str, len); return *this; } inline tstring& tstring::assign(const char* str) { assign(str, ::strlen(str)); return *this; } inline tstring& tstring::assign_as_view(const tstring& str) { assign_as_view(str.data(), str.size()); return *this; } inline tstring& tstring::assign_as_view(const std::string& str) { assign_as_view(str.data(), str.size()); return *this; } inline tstring& tstring::assign_as_view(const absl::string_view str) { assign_as_view(str.data(), str.size()); return *this; } inline tstring& tstring::assign_as_view(const char* str, size_t len) { TF_TString_AssignView(&tstr_, str, len); return *this; } inline tstring& tstring::assign_as_view(const char* str) { assign_as_view(str, ::strlen(str)); return *this; } inline tstring& tstring::append(const tstring& str) { TF_TString_Append(&tstr_, &str.tstr_); return *this; } inline tstring& tstring::append(const char* str, size_t len) { TF_TString_AppendN(&tstr_, str, len); return *this; } inline tstring& tstring::append(const char* str) { append(str, ::strlen(str)); return *this; } inline tstring& tstring::append(size_t n, char c) { const size_t new_size = size() + n; TF_TString_ReserveAmortized(&tstr_, new_size); resize(new_size, c); return *this; } inline tstring& tstring::erase(size_t pos, size_t len) { memmove(mdata() + pos, data() + pos + len, size() - len - pos); resize(size() - len); return *this; } inline tstring& tstring::insert(size_t pos, const tstring& str, size_t subpos, size_t sublen) { size_t orig_size = size(); TF_TString_ResizeUninitialized(&tstr_, orig_size + sublen); memmove(mdata() + pos + sublen, data() + pos, orig_size - pos); memmove(mdata() + pos, str.data() + subpos, sublen); return *this; } inline tstring& tstring::insert(size_t pos, size_t n, char c) { size_t size_ = size(); TF_TString_ResizeUninitialized(&tstr_, size_ + n); memmove(mdata() + pos + n, data() + pos, size_ - pos); memset(mdata() + pos, c, n); return *this; } inline void tstring::swap(tstring& str) noexcept { std::swap(tstr_, str.tstr_); } inline void tstring::push_back(char ch) { append(1, ch); } inline bool operator==(const char* a, const tstring& b) { return ::strlen(a) == b.size() && ::memcmp(a, b.data(), b.size()) == 0; } inline bool operator==(const std::string& a, const tstring& b) { return a.size() == b.size() && ::memcmp(a.data(), b.data(), b.size()) == 0; } inline tstring operator+(const tstring& a, const tstring& b) { tstring r; r.reserve(a.size() + b.size()); r.append(a); r.append(b); return r; } inline std::ostream& operator<<(std::ostream& o, const tstring& str) { return o.write(str.data(), str.size()); } } #endif
#include "tsl/platform/tstring.h" #include <memory> #include <string> #include "tsl/platform/cord.h" #include "tsl/platform/platform.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/test.h" using ::tsl::tstring; static const char kLongString[] = "abcdefghij" "klmnopqrst" "uvwxyz0123" "456789ABCD" "EFGHIKLMNO"; const size_t kLongStringLen = sizeof(kLongString) / sizeof(char) - sizeof(char); TEST(TF_TStringTest, Construction) { tstring s10; tstring s11("a\0a", 3); tstring s12(kLongString); tstring s13(3, 'b'); tstring s14(absl::string_view("hi")); tstring s15(std::string("bye")); EXPECT_EQ("", s10); EXPECT_TRUE(s10.empty()); EXPECT_EQ(tstring::Type::SMALL, s10.type()); EXPECT_EQ(0, s10.size()); EXPECT_EQ(0, s10.length()); EXPECT_EQ(TF_TString_SmallCapacity, s10.capacity()); EXPECT_EQ(std::string("a\0a", 3), s11); EXPECT_FALSE(s11.empty()); EXPECT_EQ(3, s11.size()); EXPECT_EQ(3, s11.length()); EXPECT_EQ(kLongString, s12); EXPECT_EQ(kLongStringLen, s12.size()); EXPECT_EQ(tstring::Type::LARGE, s12.type()); EXPECT_LT(TF_TString_SmallCapacity, s12.capacity()); EXPECT_EQ("bbb", s13); EXPECT_EQ("hi", s14); EXPECT_EQ(tstring::Type::SMALL, s14.type()); EXPECT_EQ("bye", s15); } TEST(TF_TStringTest, CopyMove) { tstring s20(kLongString); tstring s21(s20); tstring s22; EXPECT_EQ(s20, s21); s22 = std::move(s21); EXPECT_EQ(s20, s22); EXPECT_EQ("", s21); EXPECT_EQ(tstring::Type::SMALL, s21.type()); } TEST(TF_TStringTest, Assignment) { tstring s30("123456789012345678901234567890"); tstring s31; tstring s32; s31 = s30; EXPECT_EQ(s30, s31); EXPECT_EQ(tstring::Type::LARGE, s31.type()); EXPECT_EQ(s30.size(), s31.size()); s32 = std::move(s30); EXPECT_EQ(s31, s32); EXPECT_EQ("", s30); EXPECT_EQ(tstring::Type::SMALL, s30.type()); EXPECT_EQ(tstring::Type::LARGE, s32.type()); s32 = tstring::view(kLongString); EXPECT_EQ(kLongString, s32); EXPECT_EQ(tstring::Type::VIEW, s32.type()); EXPECT_EQ(kLongStringLen, s32.size()); EXPECT_EQ(0, s32.capacity()); tstring s33(std::move(s32)); EXPECT_EQ(kLongString, s33); EXPECT_EQ(tstring::Type::VIEW, s33.type()); EXPECT_EQ(kLongStringLen, s33.size()); s32 = std::string(kLongString); EXPECT_EQ(kLongString, s32); EXPECT_EQ(tstring::Type::LARGE, s32.type()); EXPECT_EQ(kLongStringLen, s32.size()); s32 = "hello"; EXPECT_EQ("hello", s32); EXPECT_EQ(tstring::Type::SMALL, s32.type()); EXPECT_EQ(5, s32.size()); s33 = 'a'; EXPECT_EQ("a", s33); EXPECT_EQ(tstring::Type::SMALL, s33.type()); EXPECT_EQ(1, s33.size()); s32 = absl::string_view(kLongString); EXPECT_EQ(kLongString, s32); EXPECT_EQ(tstring::Type::LARGE, s32.type()); EXPECT_EQ(kLongStringLen, s32.size()); s32.resize(TF_TString_SmallCapacity * 2); EXPECT_EQ(absl::string_view(kLongString, TF_TString_SmallCapacity * 2), s32); EXPECT_EQ(tstring::Type::LARGE, s32.type()); EXPECT_EQ(TF_TString_SmallCapacity * 2, s32.size()); s32 = tstring::view(kLongString, kLongStringLen); EXPECT_EQ(kLongString, s32); EXPECT_EQ(tstring::Type::VIEW, s32.type()); EXPECT_EQ(kLongStringLen, s32.size()); s32.assign("hello1"); EXPECT_EQ("hello1", s32); s32.assign("hello2", 5); EXPECT_EQ("hello", s32); s30.assign_as_view(kLongString); EXPECT_EQ(tstring::Type::VIEW, s30.type()); s31.assign_as_view(s30); EXPECT_EQ(tstring::Type::VIEW, s31.type()); EXPECT_EQ(kLongString, s30.c_str()); EXPECT_EQ(kLongString, s31.c_str()); std::string tmp(kLongString); s32.assign_as_view(tmp); EXPECT_EQ(tstring::Type::VIEW, s32.type()); EXPECT_STREQ(kLongString, s32.c_str()); s33.assign_as_view(kLongString, 2); EXPECT_EQ(2, s33.size()); s32.assign_as_view(absl::string_view(kLongString)); EXPECT_EQ(tstring::Type::VIEW, s32.type()); EXPECT_EQ(kLongString, s32.c_str()); #ifdef PLATFORM_GOOGLE s33 = absl::Cord(kLongString); EXPECT_EQ(kLongString, s33); EXPECT_EQ(tstring::Type::LARGE, s33.type()); EXPECT_EQ(kLongStringLen, s33.size()); tstring s34((absl::Cord(kLongString))); EXPECT_EQ(kLongString, s34); EXPECT_EQ(tstring::Type::LARGE, s34.type()); EXPECT_EQ(kLongStringLen, s34.size()); #endif } TEST(TF_TStringTest, Comparison) { tstring empty(""); tstring a("a"); tstring aa("aa"); tstring a_("a"); tstring b("b"); const char c[] = "c"; tstring nulla("\0a", 2); tstring nullb("\0b", 2); tstring nullaa("\0aa", 3); EXPECT_TRUE(a < b); EXPECT_TRUE(a != b); EXPECT_FALSE(a > b); EXPECT_FALSE(a == b); EXPECT_TRUE(a < aa); EXPECT_TRUE(a != aa); EXPECT_FALSE(a > aa); EXPECT_FALSE(a == aa); EXPECT_TRUE(b > a); EXPECT_TRUE(b != a); EXPECT_FALSE(b < a); EXPECT_FALSE(b == a); EXPECT_FALSE(a == b); EXPECT_FALSE(b == c); EXPECT_TRUE(b != c); EXPECT_TRUE(empty < a); EXPECT_TRUE(empty != a); EXPECT_FALSE(empty > a); EXPECT_FALSE(empty == a); EXPECT_TRUE(a > empty); EXPECT_TRUE(a != empty); EXPECT_FALSE(a < empty); EXPECT_FALSE(a == empty); EXPECT_FALSE(a < a_); EXPECT_FALSE(a != a_); EXPECT_FALSE(a > a_); EXPECT_TRUE(a == a_); EXPECT_TRUE(nulla < nullaa); EXPECT_TRUE(nulla != nullaa); EXPECT_FALSE(nulla > nullaa); EXPECT_FALSE(nulla == nullaa); EXPECT_TRUE(nulla < nullb); EXPECT_TRUE(nullaa > nulla); EXPECT_TRUE(nullaa != nulla); EXPECT_FALSE(nullaa < nulla); EXPECT_FALSE(nullaa == nulla); } TEST(TF_TStringTest, Conversion) { tstring s50(kLongString); std::string s51(s50); absl::string_view s52(s50); EXPECT_EQ(kLongString, s51); EXPECT_EQ(kLongStringLen, s51.size()); EXPECT_EQ(kLongString, s52); EXPECT_EQ(kLongStringLen, s52.size()); #ifdef PLATFORM_GOOGLE absl::AlphaNum s53(s50); EXPECT_STREQ(kLongString, s53.data()); EXPECT_EQ(kLongStringLen, s53.size()); #endif } TEST(TF_TStringTest, Allocation) { tstring s60; s60.resize(2); EXPECT_EQ(std::string("\0\0", 2), s60); EXPECT_EQ(2, s60.size()); EXPECT_EQ(2, s60.length()); s60.resize(6, 'a'); EXPECT_EQ(std::string("\0\0aaaa", 6), s60); EXPECT_EQ(6, s60.size()); EXPECT_EQ(6, s60.length()); s60.resize(3, 'b'); EXPECT_EQ(std::string("\0\0a", 3), s60); EXPECT_EQ(3, s60.size()); EXPECT_EQ(3, s60.length()); s60.clear(); EXPECT_EQ("", s60); EXPECT_TRUE(s60.empty()); EXPECT_EQ(0, s60.size()); EXPECT_EQ(0, s60.length()); s60.reserve(100); EXPECT_EQ(111, s60.capacity()); s60.reserve(100); } TEST(TF_TStringTest, ElementAccess) { tstring s70(kLongString); EXPECT_STREQ(kLongString, s70.data()); EXPECT_EQ(s70.data(), s70.c_str()); for (size_t i = 0; i < s70.size(); i++) { EXPECT_EQ(kLongString[i], s70.data()[i]); } tstring::const_iterator i = s70.begin(); const char* j = kLongString; for (; *j != '\0'; i++, j++) { EXPECT_EQ(*j, *i); } EXPECT_EQ('\0', *s70.end()); EXPECT_EQ(*i, *s70.end()); EXPECT_EQ(*(i - 1), s70.back()); } TEST(TF_TStringTest, Modifiers) { tstring s80("ba"); tstring s81; tstring s82(kLongString); s81.append(s80); EXPECT_EQ("ba", s81); s81.append(s80); EXPECT_EQ("baba", s81); s81.append("\0c", 2); EXPECT_EQ(std::string("baba\0c", 6), s81); s81.append("dd"); EXPECT_EQ(std::string("baba\0cdd", 8), s81); s81.append(3, 'z'); EXPECT_EQ(tstring("baba\0cddzzz", 11), s81); s81.append(0, 'z'); s81.append("dd", 0); s81.append(""); s81.append(tstring()); EXPECT_EQ(std::string("baba\0cddzzz", 11), s81); s81.erase(0, 1); EXPECT_EQ(std::string("aba\0cddzzz", 10), s81); s81.erase(4, 6); EXPECT_EQ(std::string("aba\0", 4), s81); s81.insert(1, tstring("\0moo\0", 5), 1, 4); EXPECT_EQ(std::string("amoo\0ba\0", 8), s81); s81.insert(0, 2, '\0'); s81.insert(s81.size() - 1, 1, 'q'); EXPECT_EQ(std::string("\0\0amoo\0baq\0", 11), s81); s81.erase(0, s81.size()); EXPECT_EQ(tstring(), s81); s80.swap(s82); EXPECT_EQ(kLongString, s80); EXPECT_EQ("ba", s82); s82.push_back('\0'); s82.push_back('q'); EXPECT_EQ(std::string("ba\0q", 4), s82); } TEST(TF_TStringTest, Friends) { tstring s90("b"); tstring s91("\0a\0", 3); tstring s92; EXPECT_EQ("b", s90 + s92); EXPECT_EQ("b", s92 + s90); EXPECT_EQ(std::string("\0a\0", 3), s92 + s91); EXPECT_EQ(std::string("\0a\0", 3), s91 + s92); EXPECT_EQ(std::string("b\0a\0", 4), s90 + s91); EXPECT_EQ(std::string("\0a\0b", 4), s91 + s90); std::stringstream ss; ss << s91; EXPECT_EQ(std::string("\0a\0", 3), ss.str()); }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/tstring.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/tstring_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
42c31d9c-0a29-4261-90d1-949253c6fe45
cpp
google/tsl
ctstring
tsl/platform/ctstring.h
tsl/platform/ctstring_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CTSTRING_H_ #define TENSORFLOW_TSL_PLATFORM_CTSTRING_H_ #include <stdint.h> #include <stdlib.h> #include "tsl/platform/ctstring_internal.h" inline void TF_TString_Init(TF_TString *str); inline void TF_TString_Dealloc(TF_TString *str); inline char *TF_TString_Resize(TF_TString *str, size_t new_size, char c); inline char *TF_TString_ResizeUninitialized(TF_TString *str, size_t new_size); inline void TF_TString_Reserve(TF_TString *str, size_t new_cap); inline void TF_TString_ReserveAmortized(TF_TString *str, size_t new_cap); inline size_t TF_TString_GetSize(const TF_TString *str); inline size_t TF_TString_GetCapacity(const TF_TString *str); inline TF_TString_Type TF_TString_GetType(const TF_TString *str); inline const char *TF_TString_GetDataPointer(const TF_TString *str); inline char *TF_TString_GetMutableDataPointer(TF_TString *str); inline void TF_TString_AssignView(TF_TString *dst, const char *src, size_t size); inline void TF_TString_Append(TF_TString *dst, const TF_TString *src); inline void TF_TString_AppendN(TF_TString *dst, const char *src, size_t size); inline void TF_TString_Copy(TF_TString *dst, const char *src, size_t size); inline void TF_TString_Assign(TF_TString *dst, const TF_TString *src); inline void TF_TString_Move(TF_TString *dst, TF_TString *src); #endif
#include "tsl/platform/ctstring.h" #include <memory> #include <string> #include "tsl/platform/ctstring_internal.h" #include "tsl/platform/test.h" static const char kLongString[] = "abcdefghij" "klmnopqrst" "uvwxyz0123" "456789ABCD" "EFGHIKLMNO"; const size_t kLongStringLen = sizeof(kLongString) / sizeof(char) - sizeof(char); TEST(TF_CTStringTest, InitAssignMoveDealloc) { EXPECT_GT(::strlen(kLongString), TF_TString_SmallCapacity); { TF_TString s10, s11, s12; TF_TString_Init(&s10); TF_TString_Init(&s11); TF_TString_Init(&s12); EXPECT_EQ(0, TF_TString_GetSize(&s10)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s10)); EXPECT_STREQ("", TF_TString_GetDataPointer(&s10)); EXPECT_STREQ("", TF_TString_GetMutableDataPointer(&s10)); TF_TString_Assign(&s11, &s10); EXPECT_EQ(0, TF_TString_GetSize(&s11)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s10)); EXPECT_STREQ("", TF_TString_GetDataPointer(&s11)); EXPECT_STREQ("", TF_TString_GetMutableDataPointer(&s11)); TF_TString_Move(&s12, &s11); EXPECT_EQ(0, TF_TString_GetSize(&s11)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s10)); EXPECT_STREQ("", TF_TString_GetDataPointer(&s11)); EXPECT_STREQ("", TF_TString_GetMutableDataPointer(&s11)); EXPECT_EQ(0, TF_TString_GetSize(&s12)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s10)); EXPECT_STREQ("", TF_TString_GetDataPointer(&s12)); EXPECT_STREQ("", TF_TString_GetMutableDataPointer(&s12)); TF_TString_Dealloc(&s10); TF_TString_Dealloc(&s11); TF_TString_Dealloc(&s12); } { TF_TString s20, s21, s22; TF_TString_Init(&s20); TF_TString_Init(&s21); TF_TString_Init(&s22); TF_TString_Copy(&s20, "a", 1); EXPECT_EQ(1, TF_TString_GetSize(&s20)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s20)); EXPECT_STREQ("a", TF_TString_GetDataPointer(&s20)); EXPECT_STREQ("a", TF_TString_GetMutableDataPointer(&s20)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s20)); TF_TString_Assign(&s21, &s20); EXPECT_EQ(1, TF_TString_GetSize(&s21)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s21)); EXPECT_STREQ("a", TF_TString_GetDataPointer(&s21)); EXPECT_STREQ("a", TF_TString_GetMutableDataPointer(&s21)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s21)); TF_TString_Move(&s22, &s21); EXPECT_EQ(1, TF_TString_GetSize(&s22)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s22)); EXPECT_STREQ("a", TF_TString_GetDataPointer(&s22)); EXPECT_STREQ("a", TF_TString_GetMutableDataPointer(&s22)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s22)); TF_TString_Dealloc(&s20); TF_TString_Dealloc(&s21); TF_TString_Dealloc(&s22); } { TF_TString s30, s31; TF_TString_Init(&s30); TF_TString_Init(&s31); size_t s = TF_TString_SmallCapacity - 1; EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s30)); TF_TString_Copy(&s30, kLongString, s); EXPECT_STREQ(std::string(kLongString, s).data(), TF_TString_GetDataPointer(&s30)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s30)); EXPECT_GT(TF_TString_SmallCapacity, TF_TString_GetSize(&s30)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s30)); TF_TString_AppendN(&s30, &kLongString[s++], 1); EXPECT_STREQ(std::string(kLongString, s).data(), TF_TString_GetDataPointer(&s30)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s30)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetSize(&s30)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s30)); TF_TString_AppendN(&s30, &kLongString[s++], 1); EXPECT_STREQ(std::string(kLongString, s).data(), TF_TString_GetDataPointer(&s30)); EXPECT_STREQ(std::string(kLongString, s).data(), TF_TString_GetMutableDataPointer(&s30)); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s30)); EXPECT_EQ(s, TF_TString_GetSize(&s30)); EXPECT_LT(TF_TString_SmallCapacity, TF_TString_GetSize(&s30)); EXPECT_LT(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s30)); TF_TString_Move(&s31, &s30); EXPECT_STREQ("", TF_TString_GetDataPointer(&s30)); EXPECT_STREQ("", TF_TString_GetMutableDataPointer(&s30)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s30)); EXPECT_EQ(0, TF_TString_GetSize(&s30)); EXPECT_STREQ(std::string(kLongString, s).data(), TF_TString_GetDataPointer(&s31)); EXPECT_STREQ(std::string(kLongString, s).data(), TF_TString_GetMutableDataPointer(&s31)); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s31)); EXPECT_EQ(s, TF_TString_GetSize(&s31)); EXPECT_LT(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s31)); TF_TString_Dealloc(&s30); TF_TString_Dealloc(&s31); } { const char kStr[] = "abcdef"; const char kStrLen = sizeof(kStr) / sizeof(char) - sizeof(char); TF_TString s40, s41; TF_TString_Init(&s40); TF_TString_Init(&s41); TF_TString_Copy(&s40, kLongString, kLongStringLen); EXPECT_EQ(kLongStringLen, TF_TString_GetSize(&s40)); TF_TString_Assign(&s41, &s40); EXPECT_STREQ(kLongString, TF_TString_GetDataPointer(&s40)); EXPECT_STREQ(kLongString, TF_TString_GetMutableDataPointer(&s40)); EXPECT_EQ(kLongStringLen, TF_TString_GetSize(&s41)); TF_TString_AppendN(&s40, kLongString, kLongStringLen); TF_TString_Append(&s40, &s41); std::string longerString(kLongString); longerString += kLongString; longerString += kLongString; EXPECT_STREQ(longerString.data(), TF_TString_GetDataPointer(&s40)); EXPECT_STREQ(longerString.data(), TF_TString_GetMutableDataPointer(&s40)); EXPECT_EQ(longerString.size(), TF_TString_GetSize(&s40)); TF_TString_AssignView(&s40, kStr, kStrLen); EXPECT_EQ(TF_TSTR_VIEW, TF_TString_GetType(&s40)); EXPECT_EQ(kStr, TF_TString_GetDataPointer(&s40)); EXPECT_EQ(6, TF_TString_GetSize(&s40)); EXPECT_EQ(0, TF_TString_GetCapacity(&s40)); EXPECT_NE(kStr, TF_TString_GetMutableDataPointer(&s40)); EXPECT_STREQ(kStr, TF_TString_GetMutableDataPointer(&s40)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s40)); EXPECT_EQ(6, TF_TString_GetSize(&s40)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s40)); TF_TString_Dealloc(&s40); TF_TString_Dealloc(&s41); } { TF_TString s50; TF_TString_Init(&s50); TF_TString_Copy(&s50, "a", 1); EXPECT_STREQ("a", TF_TString_GetDataPointer(&s50)); EXPECT_STREQ("a", TF_TString_GetMutableDataPointer(&s50)); EXPECT_EQ(1, TF_TString_GetSize(&s50)); TF_TString_Copy(&s50, kLongString, kLongStringLen); EXPECT_STREQ(kLongString, TF_TString_GetDataPointer(&s50)); EXPECT_STREQ(kLongString, TF_TString_GetMutableDataPointer(&s50)); EXPECT_EQ(kLongStringLen, TF_TString_GetSize(&s50)); size_t cap1 = TF_TString_GetCapacity(&s50); TF_TString_Copy(&s50, kLongString, TF_TString_SmallCapacity + 1); size_t cap2 = TF_TString_GetCapacity(&s50); EXPECT_STREQ(std::string(kLongString, TF_TString_SmallCapacity + 1).data(), TF_TString_GetMutableDataPointer(&s50)); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s50)); EXPECT_GT(cap1, cap2); TF_TString_Copy(&s50, "c", 1); EXPECT_STREQ("c", TF_TString_GetDataPointer(&s50)); EXPECT_STREQ("c", TF_TString_GetMutableDataPointer(&s50)); EXPECT_EQ(1, TF_TString_GetSize(&s50)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s50)); TF_TString_Dealloc(&s50); } } TEST(TF_CTStringTest, ResizeReserve) { { TF_TString s60; TF_TString_Init(&s60); TF_TString_Resize(&s60, 2, 'a'); EXPECT_EQ(0, ::memcmp("aa", TF_TString_GetDataPointer(&s60), 2)); TF_TString_Resize(&s60, 4, '\0'); EXPECT_EQ(0, ::memcmp("aa\0\0", TF_TString_GetDataPointer(&s60), 4)); TF_TString_Resize(&s60, 6, 'b'); EXPECT_EQ(0, ::memcmp("aa\0\0bb", TF_TString_GetDataPointer(&s60), 6)); TF_TString_Resize(&s60, 2, 'c'); EXPECT_EQ(0, ::memcmp("aa", TF_TString_GetDataPointer(&s60), 2)); TF_TString_Dealloc(&s60); } { TF_TString s70; TF_TString_Init(&s70); TF_TString_Reserve(&s70, TF_TString_SmallCapacity - 1); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s70)); EXPECT_EQ(0, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s70)); TF_TString_Reserve(&s70, TF_TString_SmallCapacity); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s70)); EXPECT_EQ(0, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s70)); TF_TString_Copy(&s70, "hello", 5); EXPECT_EQ(5, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s70)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s70)); TF_TString_Reserve(&s70, 100); EXPECT_EQ(111, TF_TString_GetCapacity(&s70)); EXPECT_EQ(5, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s70)); TF_TString_AssignView(&s70, kLongString, kLongStringLen); TF_TString_Reserve(&s70, 10); EXPECT_EQ(TF_TSTR_VIEW, TF_TString_GetType(&s70)); EXPECT_EQ(0, TF_TString_GetCapacity(&s70)); TF_TString_Reserve(&s70, 100); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s70)); EXPECT_EQ(111, TF_TString_GetCapacity(&s70)); TF_TString_Reserve(&s70, 200); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s70)); EXPECT_EQ(207, TF_TString_GetCapacity(&s70)); TF_TString_Dealloc(&s70); } { TF_TString s70; TF_TString_Init(&s70); TF_TString_ReserveAmortized(&s70, TF_TString_SmallCapacity - 1); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s70)); EXPECT_EQ(0, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s70)); TF_TString_ReserveAmortized(&s70, TF_TString_SmallCapacity); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s70)); EXPECT_EQ(0, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s70)); TF_TString_Copy(&s70, "hello", 5); EXPECT_EQ(5, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TString_SmallCapacity, TF_TString_GetCapacity(&s70)); EXPECT_EQ(TF_TSTR_SMALL, TF_TString_GetType(&s70)); TF_TString_ReserveAmortized(&s70, 100); EXPECT_EQ(111, TF_TString_GetCapacity(&s70)); EXPECT_EQ(5, TF_TString_GetSize(&s70)); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s70)); TF_TString_AssignView(&s70, kLongString, kLongStringLen); TF_TString_ReserveAmortized(&s70, 10); EXPECT_EQ(TF_TSTR_VIEW, TF_TString_GetType(&s70)); EXPECT_EQ(0, TF_TString_GetCapacity(&s70)); TF_TString_ReserveAmortized(&s70, 100); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s70)); EXPECT_EQ(111, TF_TString_GetCapacity(&s70)); TF_TString_ReserveAmortized(&s70, 200); EXPECT_EQ(TF_TSTR_LARGE, TF_TString_GetType(&s70)); EXPECT_EQ(223, TF_TString_GetCapacity(&s70)); TF_TString_Dealloc(&s70); } } TEST(TF_CTStringTest, OffsetType) { { uint8_t str[] = "test"; constexpr size_t str_size = sizeof(str) / sizeof(str[0]); uint8_t buf[sizeof(TF_TString) + str_size]; memcpy(buf + sizeof(TF_TString), str, str_size); TF_TString *offsets = (TF_TString *)buf; TF_TString_Init(offsets); offsets[0].u.offset.size = TF_le32toh(str_size << 2 | TF_TSTR_OFFSET); offsets[0].u.offset.offset = TF_le32toh(sizeof(TF_TString)); offsets[0].u.offset.count = TF_le32toh(1); EXPECT_EQ(str_size, TF_TString_GetSize(offsets)); EXPECT_EQ(TF_TSTR_OFFSET, TF_TString_GetType(offsets)); EXPECT_EQ(0, ::memcmp(str, TF_TString_GetDataPointer(offsets), str_size)); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/ctstring.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/ctstring_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
fbc0f9e3-a934-4f25-b2af-dbb74096c5a7
cpp
google/tsl
numa
tsl/platform/numa.h
tsl/platform/numa_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_NUMA_H_ #define TENSORFLOW_TSL_PLATFORM_NUMA_H_ #include "tsl/platform/platform.h" #include "tsl/platform/types.h" namespace tsl { namespace port { bool NUMAEnabled(); int NUMANumNodes(); static const int kNUMANoAffinity = -1; void NUMASetThreadNodeAffinity(int node); int NUMAGetThreadNodeAffinity(); void* NUMAMalloc(int node, size_t size, int minimum_alignment); void NUMAFree(void* ptr, size_t size); int NUMAGetMemAffinity(const void* ptr); } } #endif
#include "tsl/platform/numa.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace internal { TEST(Numa, NumNodes) { if (port::NUMAEnabled()) { EXPECT_GE(port::NUMANumNodes(), 1); } } TEST(Numa, Malloc) { if (port::NUMAEnabled()) { int num_nodes = port::NUMANumNodes(); for (int request_node = 0; request_node < num_nodes; ++request_node) { void* ptr = port::NUMAMalloc(request_node, 8, 0); EXPECT_NE(ptr, nullptr); *(reinterpret_cast<int*>(ptr)) = 0; int affinity_node = port::NUMAGetMemAffinity(ptr); EXPECT_EQ(affinity_node, request_node); port::NUMAFree(ptr, 8); } } } TEST(Numa, SetNodeAffinity) { EXPECT_EQ(-1, port::NUMAGetThreadNodeAffinity()); if (port::NUMAEnabled()) { int num_nodes = port::NUMANumNodes(); for (int request_node = 0; request_node < num_nodes; ++request_node) { port::NUMASetThreadNodeAffinity(request_node); int affinity_node = port::NUMAGetThreadNodeAffinity(); EXPECT_EQ(affinity_node, request_node); } } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/numa.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/numa_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
568d4113-9530-4715-a653-8c08fbdd2dff
cpp
google/tsl
statusor
tsl/platform/default/statusor.h
tsl/platform/statusor_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_STATUSOR_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_STATUSOR_H_ #include "absl/status/statusor.h" #include "tsl/platform/macros.h" #include "tsl/platform/status.h" #define TF_ASSIGN_OR_RETURN(lhs, rexpr) \ TF_ASSIGN_OR_RETURN_IMPL( \ TF_STATUS_MACROS_CONCAT_NAME(_status_or_value, __COUNTER__), lhs, rexpr) #define TF_ASSIGN_OR_RETURN_IMPL(statusor, lhs, rexpr) \ auto statusor = (rexpr); \ if (TF_PREDICT_FALSE(!statusor.ok())) { \ return statusor.status(); \ } \ lhs = std::move(statusor).value() #endif
#include "tsl/platform/statusor.h" #include <memory> #include <type_traits> #include <utility> #include <vector> #include "absl/base/config.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { namespace { class Base1 { public: virtual ~Base1() {} int pad_; }; class Base2 { public: virtual ~Base2() {} int yetotherpad_; }; class Derived : public Base1, public Base2 { public: ~Derived() override {} int evenmorepad_; }; class CopyNoAssign { public: explicit CopyNoAssign(int value) : foo_(value) {} CopyNoAssign(const CopyNoAssign& other) : foo_(other.foo_) {} int foo_; private: const CopyNoAssign& operator=(const CopyNoAssign&); }; class NoDefaultConstructor { public: explicit NoDefaultConstructor(int foo); }; static_assert(!std::is_default_constructible<NoDefaultConstructor>(), "Should not be default-constructible."); absl::StatusOr<std::unique_ptr<int>> ReturnUniquePtr() { return std::unique_ptr<int>(new int(0)); } TEST(StatusOr, NullPointerStatusOr) { absl::StatusOr<int*> null_status(nullptr); EXPECT_TRUE(null_status.ok()); EXPECT_EQ(null_status.value(), nullptr); } TEST(StatusOr, TestNoDefaultConstructorInitialization) { absl::StatusOr<NoDefaultConstructor> statusor(errors::Cancelled("")); EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status().code(), absl::StatusCode::kCancelled); absl::StatusOr<NoDefaultConstructor> statusor2; EXPECT_FALSE(statusor2.ok()); EXPECT_EQ(statusor2.status().code(), absl::StatusCode::kUnknown); } TEST(StatusOr, TestMoveOnlyInitialization) { absl::StatusOr<std::unique_ptr<int>> thing(ReturnUniquePtr()); ASSERT_TRUE(thing.ok()); EXPECT_EQ(0, *thing.value()); int* previous = thing.value().get(); thing = ReturnUniquePtr(); EXPECT_TRUE(thing.ok()); EXPECT_EQ(0, *thing.value()); EXPECT_NE(previous, thing.value().get()); } TEST(StatusOr, TestMoveOnlyStatusCtr) { absl::StatusOr<std::unique_ptr<int>> thing(errors::Cancelled("")); ASSERT_FALSE(thing.ok()); } TEST(StatusOr, TestMoveOnlyValueExtraction) { absl::StatusOr<std::unique_ptr<int>> thing(ReturnUniquePtr()); ASSERT_TRUE(thing.ok()); std::unique_ptr<int> ptr = std::move(thing).value(); EXPECT_EQ(0, *ptr); thing = std::move(ptr); ptr = std::move(thing.value()); EXPECT_EQ(0, *ptr); } TEST(StatusOr, TestMoveOnlyConversion) { absl::StatusOr<std::unique_ptr<const int>> const_thing(ReturnUniquePtr()); EXPECT_TRUE(const_thing.ok()); EXPECT_EQ(0, *const_thing.value()); const int* const_previous = const_thing.value().get(); const_thing = ReturnUniquePtr(); EXPECT_TRUE(const_thing.ok()); EXPECT_EQ(0, *const_thing.value()); EXPECT_NE(const_previous, const_thing.value().get()); } TEST(StatusOr, TestMoveOnlyVector) { std::vector<absl::StatusOr<std::unique_ptr<int>>> vec; vec.push_back(ReturnUniquePtr()); vec.resize(2); auto another_vec = std::move(vec); EXPECT_EQ(0, *another_vec[0].value()); EXPECT_EQ(absl::StatusCode::kUnknown, another_vec[1].status().code()); } TEST(StatusOr, TestMoveWithValuesAndErrors) { absl::StatusOr<std::string> status_or(std::string(1000, '0')); absl::StatusOr<std::string> value1(std::string(1000, '1')); absl::StatusOr<std::string> value2(std::string(1000, '2')); absl::StatusOr<std::string> error1( absl::Status(absl::StatusCode::kUnknown, "error1")); absl::StatusOr<std::string> error2( absl::Status(absl::StatusCode::kUnknown, "error2")); ASSERT_TRUE(status_or.ok()); EXPECT_EQ(std::string(1000, '0'), status_or.value()); status_or = std::move(value1); ASSERT_TRUE(status_or.ok()); EXPECT_EQ(std::string(1000, '1'), status_or.value()); status_or = std::move(error1); ASSERT_FALSE(status_or.ok()); EXPECT_EQ("error1", status_or.status().message()); status_or = std::move(error2); ASSERT_FALSE(status_or.ok()); EXPECT_EQ("error2", status_or.status().message()); status_or = std::move(value2); ASSERT_TRUE(status_or.ok()); EXPECT_EQ(std::string(1000, '2'), status_or.value()); } TEST(StatusOr, TestCopyWithValuesAndErrors) { absl::StatusOr<std::string> status_or(std::string(1000, '0')); absl::StatusOr<std::string> value1(std::string(1000, '1')); absl::StatusOr<std::string> value2(std::string(1000, '2')); absl::StatusOr<std::string> error1( absl::Status(absl::StatusCode::kUnknown, "error1")); absl::StatusOr<std::string> error2( absl::Status(absl::StatusCode::kUnknown, "error2")); ASSERT_TRUE(status_or.ok()); EXPECT_EQ(std::string(1000, '0'), status_or.value()); status_or = value1; ASSERT_TRUE(status_or.ok()); EXPECT_EQ(std::string(1000, '1'), status_or.value()); status_or = error1; ASSERT_FALSE(status_or.ok()); EXPECT_EQ("error1", status_or.status().message()); status_or = error2; ASSERT_FALSE(status_or.ok()); EXPECT_EQ("error2", status_or.status().message()); status_or = value2; ASSERT_TRUE(status_or.ok()); EXPECT_EQ(std::string(1000, '2'), status_or.value()); EXPECT_EQ(std::string(1000, '1'), value1.value()); EXPECT_EQ("error1", error1.status().message()); EXPECT_EQ("error2", error2.status().message()); EXPECT_EQ(std::string(1000, '2'), value2.value()); } TEST(StatusOr, TestDefaultCtor) { absl::StatusOr<int> thing; EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kUnknown); } TEST(StatusOrDeathTest, TestDefaultCtorValue) { absl::StatusOr<int> thing; #ifdef ABSL_HAVE_EXCEPTIONS try { thing.value(); ADD_FAILURE() << "value() returned successfully while the access is illegal"; } catch (absl::BadStatusOrAccess& ex) { } #else EXPECT_DEATH(thing.value(), ""); #endif const absl::StatusOr<int> thing2; #ifdef ABSL_HAVE_EXCEPTIONS try { thing.value(); ADD_FAILURE() << "value() returned successfully while the access is illegal"; } catch (absl::BadStatusOrAccess& ex) { } #else EXPECT_DEATH(thing.value(), ""); #endif } TEST(StatusOr, TestStatusCtor) { absl::StatusOr<int> thing(absl::Status(absl::StatusCode::kCancelled, "")); EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestValueCtor) { const int kI = 4; const absl::StatusOr<int> thing(kI); EXPECT_TRUE(thing.ok()); EXPECT_EQ(kI, thing.value()); } TEST(StatusOr, TestCopyCtorStatusOk) { const int kI = 4; const absl::StatusOr<int> original(kI); const absl::StatusOr<int> copy(original); EXPECT_EQ(copy.status(), original.status()); EXPECT_EQ(original.value(), copy.value()); } TEST(StatusOr, TestCopyCtorStatusNotOk) { absl::StatusOr<int> original(absl::Status(absl::StatusCode::kCancelled, "")); absl::StatusOr<int> copy(original); EXPECT_EQ(copy.status(), original.status()); } TEST(StatusOr, TestCopyCtorNonAssignable) { const int kI = 4; CopyNoAssign value(kI); absl::StatusOr<CopyNoAssign> original(value); absl::StatusOr<CopyNoAssign> copy(original); EXPECT_EQ(copy.status(), original.status()); EXPECT_EQ(original.value().foo_, copy.value().foo_); } TEST(StatusOr, TestCopyCtorStatusOKConverting) { const int kI = 4; absl::StatusOr<int> original(kI); absl::StatusOr<double> copy(original); EXPECT_EQ(copy.status(), original.status()); EXPECT_DOUBLE_EQ(original.value(), copy.value()); } TEST(StatusOr, TestCopyCtorStatusNotOkConverting) { absl::StatusOr<int> original(absl::Status(absl::StatusCode::kCancelled, "")); absl::StatusOr<double> copy(original); EXPECT_EQ(copy.status(), original.status()); } TEST(StatusOr, TestAssignmentStatusOk) { const int kI = 4; absl::StatusOr<int> source(kI); absl::StatusOr<int> target; target = source; EXPECT_EQ(target.status(), source.status()); EXPECT_EQ(source.value(), target.value()); } TEST(StatusOr, TestAssignmentStatusNotOk) { absl::StatusOr<int> source(absl::Status(absl::StatusCode::kCancelled, "")); absl::StatusOr<int> target; target = source; EXPECT_EQ(target.status(), source.status()); } TEST(StatusOr, TestStatus) { absl::StatusOr<int> good(4); EXPECT_TRUE(good.ok()); absl::StatusOr<int> bad(absl::Status(absl::StatusCode::kCancelled, "")); EXPECT_FALSE(bad.ok()); EXPECT_EQ(bad.status(), absl::Status(absl::StatusCode::kCancelled, "")); } TEST(StatusOr, TestValue) { const int kI = 4; absl::StatusOr<int> thing(kI); EXPECT_EQ(kI, thing.value()); } TEST(StatusOr, TestValueConst) { const int kI = 4; const absl::StatusOr<int> thing(kI); EXPECT_EQ(kI, thing.value()); } TEST(StatusOrDeathTest, TestValueNotOk) { absl::StatusOr<int> thing( absl::Status(absl::StatusCode::kCancelled, "cancelled")); #ifdef ABSL_HAVE_EXCEPTIONS try { thing.value(); ADD_FAILURE() << "value() returned successfully while the access is illegal"; } catch (absl::BadStatusOrAccess& ex) { } #else EXPECT_DEATH(thing.value(), "cancelled"); #endif } TEST(StatusOrDeathTest, TestValueNotOkConst) { const absl::StatusOr<int> thing(absl::Status(absl::StatusCode::kUnknown, "")); #ifdef ABSL_HAVE_EXCEPTIONS try { thing.value(); ADD_FAILURE() << "value() returned successfully while the access is illegal"; } catch (absl::BadStatusOrAccess& ex) { } #else EXPECT_DEATH(thing.value(), ""); #endif } TEST(StatusOr, TestPointerDefaultCtor) { absl::StatusOr<int*> thing; EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kUnknown); } TEST(StatusOrDeathTest, TestPointerDefaultCtorValue) { absl::StatusOr<int*> thing; #ifdef ABSL_HAVE_EXCEPTIONS try { thing.value(); ADD_FAILURE() << "value() returned successfully while the access is illegal"; } catch (absl::BadStatusOrAccess& ex) { } #else EXPECT_DEATH(thing.value(), ""); #endif } TEST(StatusOr, TestPointerStatusCtor) { absl::StatusOr<int*> thing(absl::Status(absl::StatusCode::kCancelled, "")); EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status(), absl::Status(absl::StatusCode::kCancelled, "")); } TEST(StatusOr, TestPointerValueCtor) { const int kI = 4; absl::StatusOr<const int*> thing(&kI); EXPECT_TRUE(thing.ok()); EXPECT_EQ(&kI, thing.value()); } TEST(StatusOr, TestPointerCopyCtorStatusOk) { const int kI = 0; absl::StatusOr<const int*> original(&kI); absl::StatusOr<const int*> copy(original); EXPECT_EQ(copy.status(), original.status()); EXPECT_EQ(original.value(), copy.value()); } TEST(StatusOr, TestPointerCopyCtorStatusNotOk) { absl::StatusOr<int*> original(absl::Status(absl::StatusCode::kCancelled, "")); absl::StatusOr<int*> copy(original); EXPECT_EQ(copy.status(), original.status()); } TEST(StatusOr, TestPointerCopyCtorStatusOKConverting) { Derived derived; absl::StatusOr<Derived*> original(&derived); absl::StatusOr<Base2*> copy(original); EXPECT_EQ(copy.status(), original.status()); EXPECT_EQ(static_cast<const Base2*>(original.value()), copy.value()); } TEST(StatusOr, TestPointerCopyCtorStatusNotOkConverting) { absl::StatusOr<Derived*> original( absl::Status(absl::StatusCode::kCancelled, "")); absl::StatusOr<Base2*> copy(original); EXPECT_EQ(copy.status(), original.status()); } TEST(StatusOr, TestPointerAssignmentStatusOk) { const int kI = 0; absl::StatusOr<const int*> source(&kI); absl::StatusOr<const int*> target; target = source; EXPECT_EQ(target.status(), source.status()); EXPECT_EQ(source.value(), target.value()); } TEST(StatusOr, TestPointerAssignmentStatusNotOk) { absl::StatusOr<int*> source(absl::Status(absl::StatusCode::kCancelled, "")); absl::StatusOr<int*> target; target = source; EXPECT_EQ(target.status(), source.status()); } TEST(StatusOr, TestPointerStatus) { const int kI = 0; absl::StatusOr<const int*> good(&kI); EXPECT_TRUE(good.ok()); absl::StatusOr<const int*> bad( absl::Status(absl::StatusCode::kCancelled, "")); EXPECT_EQ(bad.status(), absl::Status(absl::StatusCode::kCancelled, "")); } TEST(StatusOr, TestPointerValue) { const int kI = 0; absl::StatusOr<const int*> thing(&kI); EXPECT_EQ(&kI, thing.value()); } TEST(StatusOr, TestPointerValueConst) { const int kI = 0; const absl::StatusOr<const int*> thing(&kI); EXPECT_EQ(&kI, thing.value()); } TEST(StatusOr, TestArrowOperator) { absl::StatusOr<std::unique_ptr<int>> uptr = ReturnUniquePtr(); EXPECT_EQ(*uptr->get(), 0); } TEST(StatusOr, TestStarOperator) { absl::StatusOr<std::unique_ptr<int>> uptr = ReturnUniquePtr(); EXPECT_EQ(**uptr, 0); } TEST(StatusOr, TestStarOperatorDeath) { absl::StatusOr<Base1> error( absl::Status(absl::StatusCode::kCancelled, "cancelled")); EXPECT_DEATH(*error, "cancelled"); } static absl::StatusOr<int> MakeStatus() { return 100; } template <typename T> class BenchmarkFactory { public: BenchmarkFactory() : value_(new T) {} ~BenchmarkFactory() { delete value_; } T* TrivialFactory() TF_ATTRIBUTE_NOINLINE { return value_; } absl::Status ArgumentFactory(T** result) TF_ATTRIBUTE_NOINLINE { *result = value_; return absl::OkStatus(); } absl::Status ArgumentFactoryFail(T** result) TF_ATTRIBUTE_NOINLINE { *result = nullptr; return absl::Status(absl::StatusCode::kCancelled, ""); } absl::Status ArgumentFactoryFailShortMsg(T** result) TF_ATTRIBUTE_NOINLINE { *result = nullptr; return absl::Status(absl::StatusCode::kInternal, ""); } absl::Status ArgumentFactoryFailLongMsg(T** result) TF_ATTRIBUTE_NOINLINE { *result = nullptr; return absl::Status(absl::StatusCode::kInternal, "a big string of message junk that will never be read"); } StatusOr<T*> StatusOrFactory() TF_ATTRIBUTE_NOINLINE { return static_cast<T*>(value_); } StatusOr<T*> StatusOrFactoryFail() TF_ATTRIBUTE_NOINLINE { return absl::Status(absl::StatusCode::kCancelled, ""); } StatusOr<T*> StatusOrFactoryFailShortMsg() TF_ATTRIBUTE_NOINLINE { return absl::Status(absl::StatusCode::kInternal, ""); } StatusOr<T*> StatusOrFactoryFailLongMsg() TF_ATTRIBUTE_NOINLINE { return absl::Status(absl::StatusCode::kInternal, "a big string of message junk that will never be read"); } private: T* volatile value_; BenchmarkFactory(const BenchmarkFactory&) = delete; void operator=(const BenchmarkFactory&) = delete; }; class BenchmarkType { public: BenchmarkType() {} virtual ~BenchmarkType() {} virtual void DoWork() TF_ATTRIBUTE_NOINLINE {} private: BenchmarkType(const BenchmarkType&) = delete; void operator=(const BenchmarkType&) = delete; }; void BM_CalibrateWorkLoop(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; BenchmarkType* result = factory.TrivialFactory(); for (auto s : state) { if (result != nullptr) { result->DoWork(); } } } BENCHMARK(BM_CalibrateWorkLoop); void BM_TrivialFactory(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { BenchmarkType* result = factory.TrivialFactory(); if (result != nullptr) { result->DoWork(); } } } BENCHMARK(BM_TrivialFactory); void BM_ArgumentFactory(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { BenchmarkType* result = nullptr; absl::Status status = factory.ArgumentFactory(&result); if (status.ok() && result != nullptr) { result->DoWork(); } } } BENCHMARK(BM_ArgumentFactory); void BM_StatusOrFactory(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { absl::StatusOr<BenchmarkType*> result = factory.StatusOrFactory(); if (result.ok()) { result.value()->DoWork(); } } } BENCHMARK(BM_StatusOrFactory); void BM_ArgumentFactoryFail(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { BenchmarkType* result = nullptr; absl::Status status = factory.ArgumentFactoryFail(&result); if (status.ok() && result != nullptr) { result->DoWork(); } } } BENCHMARK(BM_ArgumentFactoryFail); void BM_StatusOrFactoryFail(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { absl::StatusOr<BenchmarkType*> result = factory.StatusOrFactoryFail(); if (result.ok()) { result.value()->DoWork(); } } } BENCHMARK(BM_StatusOrFactoryFail); void BM_ArgumentFactoryFailShortMsg(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { BenchmarkType* result = nullptr; absl::Status status = factory.ArgumentFactoryFailShortMsg(&result); if (status.ok() && result != nullptr) { result->DoWork(); } } } BENCHMARK(BM_ArgumentFactoryFailShortMsg); void BM_StatusOrFactoryFailShortMsg(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { absl::StatusOr<BenchmarkType*> result = factory.StatusOrFactoryFailShortMsg(); if (result.ok()) { result.value()->DoWork(); } } } BENCHMARK(BM_StatusOrFactoryFailShortMsg); void BM_ArgumentFactoryFailLongMsg(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { BenchmarkType* result = nullptr; absl::Status status = factory.ArgumentFactoryFailLongMsg(&result); if (status.ok() && result != nullptr) { result->DoWork(); } } } BENCHMARK(BM_ArgumentFactoryFailLongMsg); void BM_StatusOrFactoryFailLongMsg(::testing::benchmark::State& state) { BenchmarkFactory<BenchmarkType> factory; for (auto s : state) { absl::StatusOr<BenchmarkType*> result = factory.StatusOrFactoryFailLongMsg(); if (result.ok()) { result.value()->DoWork(); } } } BENCHMARK(BM_StatusOrFactoryFailLongMsg); #if defined(PLATFORM_GOOGLE) absl::StatusOr<int> GetError() { return absl::InvalidArgumentError("An invalid argument error"); } absl::StatusOr<int> PropagateError() { TF_ASSIGN_OR_RETURN(int a, GetError()); return a; } absl::StatusOr<int> PropagateError2() { TF_ASSIGN_OR_RETURN(int a, PropagateError()); return a; } TEST(Status, StackTracePropagation) { absl::StatusOr<int> s = PropagateError2(); auto sources = s.status().GetSourceLocations(); ASSERT_EQ(sources.size(), 3); for (int i = 0; i < 3; ++i) { ASSERT_EQ(sources[i].file_name(), "third_party/tensorflow/tsl/platform/statusor_test.cc"); } } #endif } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/default/statusor.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/statusor_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
38985f23-70af-414f-9402-1f1728be4239
cpp
google/tsl
retrying_file_system
tsl/platform/retrying_file_system.h
tsl/platform/retrying_file_system_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_RETRYING_FILE_SYSTEM_H_ #define TENSORFLOW_TSL_PLATFORM_RETRYING_FILE_SYSTEM_H_ #include <functional> #include <string> #include <vector> #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/file_system.h" #include "tsl/platform/random.h" #include "tsl/platform/retrying_utils.h" #include "tsl/platform/status.h" namespace tsl { template <typename Underlying> class RetryingFileSystem : public FileSystem { public: RetryingFileSystem(std::unique_ptr<Underlying> base_file_system, const RetryConfig& retry_config) : base_file_system_(std::move(base_file_system)), retry_config_(retry_config) {} TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT; absl::Status NewRandomAccessFile( const string& filename, TransactionToken* token, std::unique_ptr<RandomAccessFile>* result) override; absl::Status NewWritableFile(const string& filename, TransactionToken* token, std::unique_ptr<WritableFile>* result) override; absl::Status NewAppendableFile( const string& filename, TransactionToken* token, std::unique_ptr<WritableFile>* result) override; absl::Status NewReadOnlyMemoryRegionFromFile( const string& filename, TransactionToken* token, std::unique_ptr<ReadOnlyMemoryRegion>* result) override; absl::Status FileExists(const string& fname, TransactionToken* token) override { return RetryingUtils::CallWithRetries( [this, &fname, token]() { return base_file_system_->FileExists(fname, token); }, retry_config_); } absl::Status GetChildren(const string& dir, TransactionToken* token, std::vector<string>* result) override { return RetryingUtils::CallWithRetries( [this, &dir, result, token]() { return base_file_system_->GetChildren(dir, token, result); }, retry_config_); } absl::Status GetMatchingPaths(const string& pattern, TransactionToken* token, std::vector<string>* result) override { return RetryingUtils::CallWithRetries( [this, &pattern, result, token]() { return base_file_system_->GetMatchingPaths(pattern, token, result); }, retry_config_); } absl::Status Stat(const string& fname, TransactionToken* token, FileStatistics* stat) override { return RetryingUtils::CallWithRetries( [this, &fname, stat, token]() { return base_file_system_->Stat(fname, token, stat); }, retry_config_); } absl::Status DeleteFile(const string& fname, TransactionToken* token) override { return RetryingUtils::DeleteWithRetries( [this, &fname, token]() { return base_file_system_->DeleteFile(fname, token); }, retry_config_); } absl::Status CreateDir(const string& dirname, TransactionToken* token) override { return RetryingUtils::CallWithRetries( [this, &dirname, token]() { return base_file_system_->CreateDir(dirname, token); }, retry_config_); } absl::Status DeleteDir(const string& dirname, TransactionToken* token) override { return RetryingUtils::DeleteWithRetries( [this, &dirname, token]() { return base_file_system_->DeleteDir(dirname, token); }, retry_config_); } absl::Status GetFileSize(const string& fname, TransactionToken* token, uint64* file_size) override { return RetryingUtils::CallWithRetries( [this, &fname, file_size, token]() { return base_file_system_->GetFileSize(fname, token, file_size); }, retry_config_); } absl::Status RenameFile(const string& src, const string& target, TransactionToken* token) override { return RetryingUtils::CallWithRetries( [this, &src, &target, token]() { return base_file_system_->RenameFile(src, target, token); }, retry_config_); } absl::Status IsDirectory(const string& dirname, TransactionToken* token) override { return RetryingUtils::CallWithRetries( [this, &dirname, token]() { return base_file_system_->IsDirectory(dirname, token); }, retry_config_); } absl::Status HasAtomicMove(const string& path, bool* has_atomic_move) override { return base_file_system_->HasAtomicMove(path, has_atomic_move); } absl::Status CanCreateTempFile(const std::string& fname, bool* can_create_temp_file) override { return base_file_system_->CanCreateTempFile(fname, can_create_temp_file); } absl::Status DeleteRecursively(const string& dirname, TransactionToken* token, int64_t* undeleted_files, int64_t* undeleted_dirs) override { return RetryingUtils::DeleteWithRetries( [this, &dirname, token, undeleted_files, undeleted_dirs]() { return base_file_system_->DeleteRecursively( dirname, token, undeleted_files, undeleted_dirs); }, retry_config_); } void FlushCaches(TransactionToken* token) override { base_file_system_->FlushCaches(token); } Underlying* underlying() const { return base_file_system_.get(); } private: std::unique_ptr<Underlying> base_file_system_; const RetryConfig retry_config_; RetryingFileSystem(const RetryingFileSystem&) = delete; void operator=(const RetryingFileSystem&) = delete; }; namespace retrying_internals { class RetryingRandomAccessFile : public RandomAccessFile { public: RetryingRandomAccessFile(std::unique_ptr<RandomAccessFile> base_file, const RetryConfig& retry_config) : base_file_(std::move(base_file)), retry_config_(retry_config) {} absl::Status Name(absl::string_view* result) const override { return base_file_->Name(result); } absl::Status Read(uint64 offset, size_t n, absl::string_view* result, char* scratch) const override { return RetryingUtils::CallWithRetries( [this, offset, n, result, scratch]() { return base_file_->Read(offset, n, result, scratch); }, retry_config_); } private: std::unique_ptr<RandomAccessFile> base_file_; const RetryConfig retry_config_; }; class RetryingWritableFile : public WritableFile { public: RetryingWritableFile(std::unique_ptr<WritableFile> base_file, const RetryConfig& retry_config) : base_file_(std::move(base_file)), retry_config_(retry_config) {} ~RetryingWritableFile() override { Close().IgnoreError(); } absl::Status Append(absl::string_view data) override { return RetryingUtils::CallWithRetries( [this, &data]() { return base_file_->Append(data); }, retry_config_); } absl::Status Close() override { return RetryingUtils::CallWithRetries( [this]() { return base_file_->Close(); }, retry_config_); } absl::Status Flush() override { return RetryingUtils::CallWithRetries( [this]() { return base_file_->Flush(); }, retry_config_); } absl::Status Name(absl::string_view* result) const override { return base_file_->Name(result); } absl::Status Sync() override { return RetryingUtils::CallWithRetries( [this]() { return base_file_->Sync(); }, retry_config_); } absl::Status Tell(int64_t* position) override { return RetryingUtils::CallWithRetries( [this, &position]() { return base_file_->Tell(position); }, retry_config_); } private: std::unique_ptr<WritableFile> base_file_; const RetryConfig retry_config_; }; } template <typename Underlying> absl::Status RetryingFileSystem<Underlying>::NewRandomAccessFile( const string& filename, TransactionToken* token, std::unique_ptr<RandomAccessFile>* result) { std::unique_ptr<RandomAccessFile> base_file; TF_RETURN_IF_ERROR(RetryingUtils::CallWithRetries( [this, &filename, &base_file, token]() { return base_file_system_->NewRandomAccessFile(filename, token, &base_file); }, retry_config_)); result->reset(new retrying_internals::RetryingRandomAccessFile( std::move(base_file), retry_config_)); return absl::OkStatus(); } template <typename Underlying> absl::Status RetryingFileSystem<Underlying>::NewWritableFile( const string& filename, TransactionToken* token, std::unique_ptr<WritableFile>* result) { std::unique_ptr<WritableFile> base_file; TF_RETURN_IF_ERROR(RetryingUtils::CallWithRetries( [this, &filename, &base_file, token]() { return base_file_system_->NewWritableFile(filename, token, &base_file); }, retry_config_)); result->reset(new retrying_internals::RetryingWritableFile( std::move(base_file), retry_config_)); return absl::OkStatus(); } template <typename Underlying> absl::Status RetryingFileSystem<Underlying>::NewAppendableFile( const string& filename, TransactionToken* token, std::unique_ptr<WritableFile>* result) { std::unique_ptr<WritableFile> base_file; TF_RETURN_IF_ERROR(RetryingUtils::CallWithRetries( [this, &filename, &base_file, token]() { return base_file_system_->NewAppendableFile(filename, token, &base_file); }, retry_config_)); result->reset(new retrying_internals::RetryingWritableFile( std::move(base_file), retry_config_)); return absl::OkStatus(); } template <typename Underlying> absl::Status RetryingFileSystem<Underlying>::NewReadOnlyMemoryRegionFromFile( const string& filename, TransactionToken* token, std::unique_ptr<ReadOnlyMemoryRegion>* result) { return RetryingUtils::CallWithRetries( [this, &filename, result, token]() { return base_file_system_->NewReadOnlyMemoryRegionFromFile( filename, token, result); }, retry_config_); } } #endif
#include "tsl/platform/retrying_file_system.h" #include <fstream> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/str_util.h" #include "tsl/platform/test.h" namespace tsl { namespace { typedef std::vector<std::tuple<string, absl::Status>> ExpectedCalls; ExpectedCalls CreateRetriableErrors(const string& method, int n) { ExpectedCalls expected_calls; expected_calls.reserve(n); for (int i = 0; i < n; i++) { expected_calls.emplace_back(std::make_tuple( method, errors::Unavailable(strings::StrCat("Retriable error #", i)))); } return expected_calls; } class MockCallSequence { public: explicit MockCallSequence(const ExpectedCalls& calls) : calls_(calls) {} ~MockCallSequence() { EXPECT_TRUE(calls_.empty()) << "Not all expected calls have been made, " << "the next expected call: " << std::get<0>(calls_.front()); } absl::Status ConsumeNextCall(const string& method) { EXPECT_FALSE(calls_.empty()) << "No more calls were expected."; auto call = calls_.front(); calls_.erase(calls_.begin()); EXPECT_EQ(std::get<0>(call), method) << "Unexpected method called."; return std::get<1>(call); } private: ExpectedCalls calls_; }; class MockRandomAccessFile : public RandomAccessFile { public: explicit MockRandomAccessFile(const ExpectedCalls& calls) : calls_(calls) {} absl::Status Name(absl::string_view* result) const override { return calls_.ConsumeNextCall("Name"); } absl::Status Read(uint64 offset, size_t n, absl::string_view* result, char* scratch) const override { return calls_.ConsumeNextCall("Read"); } private: mutable MockCallSequence calls_; }; class MockWritableFile : public WritableFile { public: explicit MockWritableFile(const ExpectedCalls& calls) : calls_(calls) {} absl::Status Append(absl::string_view data) override { return calls_.ConsumeNextCall("Append"); } absl::Status Close() override { return calls_.ConsumeNextCall("Close"); } absl::Status Flush() override { return calls_.ConsumeNextCall("Flush"); } absl::Status Name(absl::string_view* result) const override { return calls_.ConsumeNextCall("Name"); } absl::Status Sync() override { return calls_.ConsumeNextCall("Sync"); } absl::Status Tell(int64_t* position) override { return calls_.ConsumeNextCall("Tell"); } private: mutable MockCallSequence calls_; }; class MockFileSystem : public FileSystem { public: explicit MockFileSystem(const ExpectedCalls& calls, bool* flushed = nullptr) : calls_(calls), flushed_(flushed) {} TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT; absl::Status NewRandomAccessFile( const string& fname, TransactionToken* token, std::unique_ptr<RandomAccessFile>* result) override { *result = std::move(random_access_file_to_return); return calls_.ConsumeNextCall("NewRandomAccessFile"); } absl::Status NewWritableFile(const string& fname, TransactionToken* token, std::unique_ptr<WritableFile>* result) override { *result = std::move(writable_file_to_return); return calls_.ConsumeNextCall("NewWritableFile"); } absl::Status NewAppendableFile( const string& fname, TransactionToken* token, std::unique_ptr<WritableFile>* result) override { *result = std::move(writable_file_to_return); return calls_.ConsumeNextCall("NewAppendableFile"); } absl::Status NewReadOnlyMemoryRegionFromFile( const string& fname, TransactionToken* token, std::unique_ptr<ReadOnlyMemoryRegion>* result) override { return calls_.ConsumeNextCall("NewReadOnlyMemoryRegionFromFile"); } absl::Status FileExists(const string& fname, TransactionToken* token) override { return calls_.ConsumeNextCall("FileExists"); } absl::Status GetChildren(const string& dir, TransactionToken* token, std::vector<string>* result) override { return calls_.ConsumeNextCall("GetChildren"); } absl::Status GetMatchingPaths(const string& dir, TransactionToken* token, std::vector<string>* result) override { return calls_.ConsumeNextCall("GetMatchingPaths"); } absl::Status Stat(const string& fname, TransactionToken* token, FileStatistics* stat) override { return calls_.ConsumeNextCall("Stat"); } absl::Status DeleteFile(const string& fname, TransactionToken* token) override { return calls_.ConsumeNextCall("DeleteFile"); } absl::Status CreateDir(const string& dirname, TransactionToken* token) override { return calls_.ConsumeNextCall("CreateDir"); } absl::Status DeleteDir(const string& dirname, TransactionToken* token) override { return calls_.ConsumeNextCall("DeleteDir"); } absl::Status GetFileSize(const string& fname, TransactionToken* token, uint64* file_size) override { return calls_.ConsumeNextCall("GetFileSize"); } absl::Status RenameFile(const string& src, const string& target, TransactionToken* token) override { return calls_.ConsumeNextCall("RenameFile"); } absl::Status IsDirectory(const string& dirname, TransactionToken* token) override { return calls_.ConsumeNextCall("IsDirectory"); } absl::Status DeleteRecursively(const string& dirname, TransactionToken* token, int64_t* undeleted_files, int64_t* undeleted_dirs) override { return calls_.ConsumeNextCall("DeleteRecursively"); } void FlushCaches(TransactionToken* token) override { if (flushed_) { *flushed_ = true; } } std::unique_ptr<WritableFile> writable_file_to_return; std::unique_ptr<RandomAccessFile> random_access_file_to_return; private: MockCallSequence calls_; bool* flushed_ = nullptr; }; TEST(RetryingFileSystemTest, NewRandomAccessFile_ImmediateSuccess) { ExpectedCalls expected_file_calls( {std::make_tuple("Name", absl::OkStatus()), std::make_tuple("Read", absl::OkStatus())}); std::unique_ptr<RandomAccessFile> base_file( new MockRandomAccessFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewRandomAccessFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->random_access_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<RandomAccessFile> random_access_file; TF_EXPECT_OK( fs.NewRandomAccessFile("filename.txt", nullptr, &random_access_file)); absl::string_view result; TF_EXPECT_OK(random_access_file->Name(&result)); EXPECT_EQ(result, ""); char scratch[10]; TF_EXPECT_OK(random_access_file->Read(0, 10, &result, scratch)); } TEST(RetryingFileSystemTest, NewRandomAccessFile_SuccessWith3rdTry) { ExpectedCalls expected_file_calls( {std::make_tuple("Read", errors::Unavailable("Something is wrong")), std::make_tuple("Read", errors::Unavailable("Wrong again")), std::make_tuple("Read", absl::OkStatus())}); std::unique_ptr<RandomAccessFile> base_file( new MockRandomAccessFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewRandomAccessFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->random_access_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<RandomAccessFile> random_access_file; TF_EXPECT_OK( fs.NewRandomAccessFile("filename.txt", nullptr, &random_access_file)); absl::string_view result; char scratch[10]; TF_EXPECT_OK(random_access_file->Read(0, 10, &result, scratch)); } TEST(RetryingFileSystemTest, NewRandomAccessFile_AllRetriesFailed) { ExpectedCalls expected_file_calls = CreateRetriableErrors("Read", 11); std::unique_ptr<RandomAccessFile> base_file( new MockRandomAccessFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewRandomAccessFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->random_access_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<RandomAccessFile> random_access_file; TF_EXPECT_OK( fs.NewRandomAccessFile("filename.txt", nullptr, &random_access_file)); absl::string_view result; char scratch[10]; const auto& status = random_access_file->Read(0, 10, &result, scratch); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, NewRandomAccessFile_NoRetriesForSomeErrors) { ExpectedCalls expected_file_calls({ std::make_tuple("Read", errors::FailedPrecondition("Failed precondition")), }); std::unique_ptr<RandomAccessFile> base_file( new MockRandomAccessFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewRandomAccessFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->random_access_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<RandomAccessFile> random_access_file; TF_EXPECT_OK( fs.NewRandomAccessFile("filename.txt", nullptr, &random_access_file)); absl::string_view result; char scratch[10]; EXPECT_EQ("Failed precondition", random_access_file->Read(0, 10, &result, scratch).message()); } TEST(RetryingFileSystemTest, NewWritableFile_ImmediateSuccess) { ExpectedCalls expected_file_calls( {std::make_tuple("Name", absl::OkStatus()), std::make_tuple("Sync", absl::OkStatus()), std::make_tuple("Close", absl::OkStatus())}); std::unique_ptr<WritableFile> base_file( new MockWritableFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewWritableFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->writable_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<WritableFile> writable_file; TF_EXPECT_OK(fs.NewWritableFile("filename.txt", nullptr, &writable_file)); absl::string_view result; TF_EXPECT_OK(writable_file->Name(&result)); EXPECT_EQ(result, ""); TF_EXPECT_OK(writable_file->Sync()); } TEST(RetryingFileSystemTest, NewWritableFile_SuccessWith3rdTry) { ExpectedCalls expected_file_calls( {std::make_tuple("Sync", errors::Unavailable("Something is wrong")), std::make_tuple("Sync", errors::Unavailable("Something is wrong again")), std::make_tuple("Sync", absl::OkStatus()), std::make_tuple("Close", absl::OkStatus())}); std::unique_ptr<WritableFile> base_file( new MockWritableFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewWritableFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->writable_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<WritableFile> writable_file; TF_EXPECT_OK(fs.NewWritableFile("filename.txt", nullptr, &writable_file)); TF_EXPECT_OK(writable_file->Sync()); } TEST(RetryingFileSystemTest, NewWritableFile_SuccessWith3rdTry_ViaDestructor) { ExpectedCalls expected_file_calls( {std::make_tuple("Close", errors::Unavailable("Something is wrong")), std::make_tuple("Close", errors::Unavailable("Something is wrong again")), std::make_tuple("Close", absl::OkStatus())}); std::unique_ptr<WritableFile> base_file( new MockWritableFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewWritableFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->writable_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<WritableFile> writable_file; TF_EXPECT_OK(fs.NewWritableFile("filename.txt", nullptr, &writable_file)); writable_file.reset(); } TEST(RetryingFileSystemTest, NewAppendableFile_SuccessWith3rdTry) { ExpectedCalls expected_file_calls( {std::make_tuple("Sync", errors::Unavailable("Something is wrong")), std::make_tuple("Sync", errors::Unavailable("Something is wrong again")), std::make_tuple("Sync", absl::OkStatus()), std::make_tuple("Close", absl::OkStatus())}); std::unique_ptr<WritableFile> base_file( new MockWritableFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewAppendableFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->writable_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<WritableFile> writable_file; TF_EXPECT_OK(fs.NewAppendableFile("filename.txt", nullptr, &writable_file)); TF_EXPECT_OK(writable_file->Sync()); } TEST(RetryingFileSystemTest, NewWritableFile_AllRetriesFailed) { ExpectedCalls expected_file_calls = CreateRetriableErrors("Sync", 11); expected_file_calls.emplace_back(std::make_tuple("Close", absl::OkStatus())); std::unique_ptr<WritableFile> base_file( new MockWritableFile(expected_file_calls)); ExpectedCalls expected_fs_calls( {std::make_tuple("NewWritableFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); base_fs->writable_file_to_return = std::move(base_file); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<WritableFile> writable_file; TF_EXPECT_OK(fs.NewWritableFile("filename.txt", nullptr, &writable_file)); const auto& status = writable_file->Sync(); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, NewReadOnlyMemoryRegionFromFile_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("NewReadOnlyMemoryRegionFromFile", errors::Unavailable("Something is wrong")), std::make_tuple("NewReadOnlyMemoryRegionFromFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<ReadOnlyMemoryRegion> result; TF_EXPECT_OK( fs.NewReadOnlyMemoryRegionFromFile("filename.txt", nullptr, &result)); } TEST(RetryingFileSystemTest, NewReadOnlyMemoryRegionFromFile_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("NewReadOnlyMemoryRegionFromFile", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::unique_ptr<ReadOnlyMemoryRegion> result; const auto& status = fs.NewReadOnlyMemoryRegionFromFile("filename.txt", nullptr, &result); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, GetChildren_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("GetChildren", errors::Unavailable("Something is wrong")), std::make_tuple("GetChildren", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::vector<string> result; TF_EXPECT_OK(fs.GetChildren("gs: } TEST(RetryingFileSystemTest, GetChildren_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("GetChildren", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::vector<string> result; const auto& status = fs.GetChildren("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, GetMatchingPaths_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("GetMatchingPaths", errors::Unavailable("Something is wrong")), std::make_tuple("GetMatchingPaths", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::vector<string> result; TF_EXPECT_OK(fs.GetMatchingPaths("gs: } TEST(RetryingFileSystemTest, GetMatchingPaths_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("GetMatchingPaths", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); std::vector<string> result; const auto& status = fs.GetMatchingPaths("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, DeleteFile_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("DeleteFile", errors::Unavailable("Something is wrong")), std::make_tuple("DeleteFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); TF_EXPECT_OK(fs.DeleteFile("gs: } TEST(RetryingFileSystemTest, DeleteFile_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("DeleteFile", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); const auto& status = fs.DeleteFile("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, CreateDir_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("CreateDir", errors::Unavailable("Something is wrong")), std::make_tuple("CreateDir", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); TF_EXPECT_OK(fs.CreateDir("gs: } TEST(RetryingFileSystemTest, CreateDir_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("CreateDir", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); const auto& status = fs.CreateDir("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, DeleteDir_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("DeleteDir", errors::Unavailable("Something is wrong")), std::make_tuple("DeleteDir", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); TF_EXPECT_OK(fs.DeleteDir("gs: } TEST(RetryingFileSystemTest, DeleteDir_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("DeleteDir", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); const auto& status = fs.DeleteDir("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, GetFileSize_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("GetFileSize", errors::Unavailable("Something is wrong")), std::make_tuple("GetFileSize", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); uint64 size; TF_EXPECT_OK(fs.GetFileSize("gs: } TEST(RetryingFileSystemTest, GetFileSize_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("GetFileSize", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); uint64 size; const auto& status = fs.GetFileSize("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, RenameFile_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("RenameFile", errors::Unavailable("Something is wrong")), std::make_tuple("RenameFile", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); TF_EXPECT_OK(fs.RenameFile("old_name", "new_name", nullptr)); } TEST(RetryingFileSystemTest, RenameFile_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("RenameFile", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); const auto& status = fs.RenameFile("old_name", "new_name", nullptr); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, Stat_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("Stat", errors::Unavailable("Something is wrong")), std::make_tuple("Stat", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); FileStatistics stat; TF_EXPECT_OK(fs.Stat("file_name", nullptr, &stat)); } TEST(RetryingFileSystemTest, Stat_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("Stat", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); FileStatistics stat; const auto& status = fs.Stat("file_name", nullptr, &stat); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, FileExists_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("FileExists", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); const auto& status = fs.FileExists("file_name", nullptr); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, FileExists_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("FileExists", errors::Unavailable("Something is wrong")), std::make_tuple("FileExists", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); TF_EXPECT_OK(fs.FileExists("gs: } TEST(RetryingFileSystemTest, IsDirectory_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("IsDirectory", errors::Unavailable("Something is wrong")), std::make_tuple("IsDirectory", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); TF_EXPECT_OK(fs.IsDirectory("gs: } TEST(RetryingFileSystemTest, IsDirectory_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("IsDirectory", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); const auto& status = fs.IsDirectory("gs: EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, DeleteRecursively_SuccessWith2ndTry) { ExpectedCalls expected_fs_calls( {std::make_tuple("DeleteRecursively", errors::Unavailable("Something is wrong")), std::make_tuple("DeleteRecursively", absl::OkStatus())}); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); int64_t undeleted_files, undeleted_dirs; TF_EXPECT_OK(fs.DeleteRecursively("gs: &undeleted_dirs)); } TEST(RetryingFileSystemTest, DeleteRecursively_AllRetriesFailed) { ExpectedCalls expected_fs_calls = CreateRetriableErrors("DeleteRecursively", 11); std::unique_ptr<MockFileSystem> base_fs( new MockFileSystem(expected_fs_calls)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); int64_t undeleted_files, undeleted_dirs; const auto& status = fs.DeleteRecursively("gs: &undeleted_files, &undeleted_dirs); EXPECT_TRUE(absl::StrContains(status.message(), "Retriable error #10")) << status; } TEST(RetryingFileSystemTest, FlushCaches) { ExpectedCalls none; bool flushed = false; std::unique_ptr<MockFileSystem> base_fs(new MockFileSystem(none, &flushed)); RetryingFileSystem<MockFileSystem> fs( std::move(base_fs), RetryConfig(0 )); fs.FlushCaches(nullptr); EXPECT_TRUE(flushed); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/retrying_file_system.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/retrying_file_system_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
e44f5644-0e5c-4bc1-bd80-cff007141f3e
cpp
google/tsl
refcount
tsl/platform/refcount.h
tsl/platform/refcount_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_REFCOUNT_H_ #define TENSORFLOW_TSL_PLATFORM_REFCOUNT_H_ #include <atomic> #include <map> #include <memory> #include "tsl/platform/logging.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" namespace tsl { namespace core { class RefCounted { public: RefCounted(); void Ref() const; bool Unref() const; int_fast32_t RefCount() const; bool RefCountIsOne() const; protected: virtual ~RefCounted(); bool TryRef() const; virtual void NotifyDeleted() const; private: mutable std::atomic_int_fast32_t ref_; RefCounted(const RefCounted&) = delete; void operator=(const RefCounted&) = delete; }; struct RefCountDeleter { void operator()(const RefCounted* o) const { o->Unref(); } }; template <typename T> class RefCountPtr; template <typename T> ABSL_MUST_USE_RESULT RefCountPtr<T> GetNewRef(T* ptr) { static_assert(std::is_base_of<RefCounted, T>::value); if (ptr == nullptr) return RefCountPtr<T>(); ptr->Ref(); RefCountPtr<T> ret(ptr); return ret; } template <typename T> class RefCountPtr : public std::unique_ptr<T, RefCountDeleter> { public: using std::unique_ptr<T, RefCountDeleter>::unique_ptr; ABSL_MUST_USE_RESULT RefCountPtr GetNewRef() const { if (this->get() == nullptr) return RefCountPtr<T>(); this->get()->Ref(); return RefCountPtr<T>(this->get()); } }; class ScopedUnref { public: explicit ScopedUnref(const RefCounted* o) : obj_(o) {} ~ScopedUnref() { if (obj_) obj_->Unref(); } private: const RefCounted* obj_; ScopedUnref(const ScopedUnref&) = delete; void operator=(const ScopedUnref&) = delete; }; template <typename T> class WeakPtr; using WeakNotifyFn = std::function<void()>; class WeakRefCounted : public RefCounted { public: int WeakRefCount() const { return data_->RefCount() - 1; } protected: void NotifyDeleted() const override { data_->Notify(); } private: struct WeakRefData : public RefCounted { explicit WeakRefData(WeakRefCounted* ptr) : ptr(ptr), next_notifier_id(1) {} mutable mutex mu; WeakRefCounted* ptr TF_GUARDED_BY(mu); std::map<int, WeakNotifyFn> notifiers; int next_notifier_id; void Notify() { mutex_lock ml(mu); while (!notifiers.empty()) { auto iter = notifiers.begin(); WeakNotifyFn notify_fn = std::move(iter->second); notifiers.erase(iter); mu.unlock(); notify_fn(); mu.lock(); } ptr = nullptr; } WeakRefCounted* GetNewRef() { mutex_lock ml(mu); if (ptr != nullptr && ptr->TryRef()) { return ptr; } return nullptr; } int AddNotifier(WeakNotifyFn notify_fn) { mutex_lock ml(mu); if (ptr == nullptr) { return 0; } int notifier_id = next_notifier_id++; notifiers.emplace(notifier_id, std::move(notify_fn)); return notifier_id; } int DupNotifier(int notifier_id) { mutex_lock ml(mu); auto iter = notifiers.find(notifier_id); if (iter != notifiers.end()) { int notifier_id = next_notifier_id++; notifiers.emplace(notifier_id, iter->second); return notifier_id; } return 0; } void RemoveNotifier(int notifier_id) { mutex_lock ml(mu); notifiers.erase(notifier_id); } }; mutable RefCountPtr<WeakRefData> data_{new WeakRefData(this)}; template <typename T> friend class WeakPtr; friend struct WeakRefData; }; template <typename T> class WeakPtr { public: explicit WeakPtr(WeakRefCounted* ptr = nullptr, WeakNotifyFn notify_fn = nullptr) : data_(nullptr), notifier_id_(0) { if (ptr != nullptr) { ptr->data_->Ref(); data_.reset(ptr->data_.get()); if (notify_fn) { notifier_id_ = data_->AddNotifier(notify_fn); } } } ~WeakPtr() { if (data_ != nullptr && notifier_id_ != 0) { data_->RemoveNotifier(notifier_id_); } } WeakPtr(const WeakPtr& other) { operator=(other); } WeakPtr& operator=(const WeakPtr& other) { if (data_ != nullptr && notifier_id_ != 0) { data_->RemoveNotifier(notifier_id_); } other.data_->Ref(); data_.reset(other.data_.get()); notifier_id_ = data_->DupNotifier(other.notifier_id_); return *this; } WeakPtr(WeakPtr&& other) noexcept { data_ = std::move(other.data_); notifier_id_ = other.notifier_id_; other.notifier_id_ = 0; } WeakPtr& operator=(WeakPtr&& other) noexcept { if (this != &other) { if (data_ != nullptr && notifier_id_ != 0) { data_->RemoveNotifier(notifier_id_); } data_ = std::move(other.data_); notifier_id_ = other.notifier_id_; other.notifier_id_ = 0; } return *this; } RefCountPtr<T> GetNewRef() const { RefCountPtr<T> ref; if (data_ != nullptr) { WeakRefCounted* ptr = data_->GetNewRef(); ref.reset(static_cast<T*>(ptr)); } return std::move(ref); } private: RefCountPtr<WeakRefCounted::WeakRefData> data_; int notifier_id_; }; inline RefCounted::RefCounted() : ref_(1) {} inline RefCounted::~RefCounted() { DCHECK_EQ(ref_.load(), 0); } inline void RefCounted::Ref() const { int_fast32_t old_ref = ref_.fetch_add(1, std::memory_order_relaxed); DCHECK_GT(old_ref, 0); } inline bool RefCounted::TryRef() const { int_fast32_t old_ref = ref_.load(); while (old_ref != 0) { if (ref_.compare_exchange_weak(old_ref, old_ref + 1)) { return true; } } return false; } inline bool RefCounted::Unref() const { DCHECK_GT(ref_.load(), 0); if (ref_.fetch_sub(1, std::memory_order_acq_rel) == 1) { NotifyDeleted(); delete this; return true; } return false; } inline int_fast32_t RefCounted::RefCount() const { return ref_.load(std::memory_order_acquire); } inline void RefCounted::NotifyDeleted() const {} inline bool RefCounted::RefCountIsOne() const { return (ref_.load(std::memory_order_acquire) == 1); } } } #endif
#include "tsl/platform/refcount.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl { namespace core { namespace { class RefTest : public ::testing::Test { public: RefTest() { constructed_ = 0; destroyed_ = 0; } static int constructed_; static int destroyed_; }; int RefTest::constructed_; int RefTest::destroyed_; class MyRef : public RefCounted { public: MyRef() { RefTest::constructed_++; } ~MyRef() override { RefTest::destroyed_++; } }; TEST_F(RefTest, New) { MyRef* ref = new MyRef; ASSERT_EQ(1, constructed_); ASSERT_EQ(0, destroyed_); ref->Unref(); ASSERT_EQ(1, constructed_); ASSERT_EQ(1, destroyed_); } TEST_F(RefTest, RefUnref) { MyRef* ref = new MyRef; ASSERT_EQ(1, constructed_); ASSERT_EQ(0, destroyed_); ref->Ref(); ASSERT_EQ(0, destroyed_); ref->Unref(); ASSERT_EQ(0, destroyed_); ref->Unref(); ASSERT_EQ(1, destroyed_); } TEST_F(RefTest, RefCountOne) { MyRef* ref = new MyRef; ASSERT_TRUE(ref->RefCountIsOne()); ref->Unref(); } TEST_F(RefTest, RefCountNotOne) { MyRef* ref = new MyRef; ref->Ref(); ASSERT_FALSE(ref->RefCountIsOne()); ref->Unref(); ref->Unref(); } TEST_F(RefTest, ConstRefUnref) { const MyRef* cref = new MyRef; ASSERT_EQ(1, constructed_); ASSERT_EQ(0, destroyed_); cref->Ref(); ASSERT_EQ(0, destroyed_); cref->Unref(); ASSERT_EQ(0, destroyed_); cref->Unref(); ASSERT_EQ(1, destroyed_); } TEST_F(RefTest, ReturnOfUnref) { MyRef* ref = new MyRef; ref->Ref(); EXPECT_FALSE(ref->Unref()); EXPECT_TRUE(ref->Unref()); } TEST_F(RefTest, ScopedUnref) { { ScopedUnref unref(new MyRef); } EXPECT_EQ(destroyed_, 1); } TEST_F(RefTest, ScopedUnref_Nullptr) { { ScopedUnref unref(nullptr); } EXPECT_EQ(destroyed_, 0); } TEST_F(RefTest, RefCountPtr) { const RefCountPtr<MyRef> cref = RefCountPtr<MyRef>(new MyRef); ASSERT_TRUE(cref.get() != nullptr); ASSERT_EQ(cref->RefCount(), 1); { const RefCountPtr<MyRef> cref2 = cref.GetNewRef(); ASSERT_EQ(cref->RefCount(), 2); } ASSERT_EQ(cref->RefCount(), 1); } class ObjType : public WeakRefCounted { public: ObjType() : ObjType(unused_dtor_called_) {} explicit ObjType(int& dtor_called) : dtor_called_(dtor_called) {} ~ObjType() override { dtor_called_++; } int& dtor_called_; static int unused_dtor_called_; }; int ObjType::unused_dtor_called_ = 0; TEST(WeakPtr, SingleThread) { auto obj = new ObjType(); WeakPtr<ObjType> weakptr(obj); ASSERT_TRUE(obj->RefCountIsOne()); EXPECT_EQ(obj->WeakRefCount(), 1); EXPECT_NE(weakptr.GetNewRef(), nullptr); obj->Unref(); EXPECT_EQ(weakptr.GetNewRef(), nullptr); } TEST(WeakPtr, MultiThreadedWeakRef) { std::atomic<int> hit_destructed{0}; auto env = Env::Default(); for (int i = 0; i < 100; i++) { auto obj = new ObjType(); WeakPtr<ObjType> weakptr(obj); bool obj_destructed = false; EXPECT_EQ(obj->WeakRefCount(), 1); auto fn = [&]() { auto ref = weakptr.GetNewRef(); if (ref != nullptr) { EXPECT_EQ(ref.get(), obj); EXPECT_EQ(ref->WeakRefCount(), 1); EXPECT_GE(ref->RefCount(), 1); } else { hit_destructed++; EXPECT_TRUE(obj_destructed); } }; auto t1 = env->StartThread(ThreadOptions{}, "thread-1", fn); auto t2 = env->StartThread(ThreadOptions{}, "thread-2", fn); env->SleepForMicroseconds(10); obj_destructed = true; obj->Unref(); delete t1; delete t2; EXPECT_EQ(weakptr.GetNewRef(), nullptr); } if (hit_destructed == 0) { LOG(WARNING) << "The destructed weakref test branch is not exercised."; } if (hit_destructed == 200) { LOG(WARNING) << "The valid weakref test branch is not exercised."; } } TEST(WeakPtr, NotifyCalled) { auto obj = new ObjType(); int num_calls1 = 0; int num_calls2 = 0; auto notify_fn1 = [&num_calls1]() { num_calls1++; }; auto notify_fn2 = [&num_calls2]() { num_calls2++; }; WeakPtr<ObjType> weakptr1(obj, notify_fn1); WeakPtr<ObjType> weakptr2(obj, notify_fn2); ASSERT_TRUE(obj->RefCountIsOne()); EXPECT_EQ(obj->WeakRefCount(), 2); EXPECT_NE(weakptr1.GetNewRef(), nullptr); EXPECT_NE(weakptr2.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 0); EXPECT_EQ(num_calls2, 0); obj->Unref(); EXPECT_EQ(weakptr1.GetNewRef(), nullptr); EXPECT_EQ(weakptr2.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 1); EXPECT_EQ(num_calls2, 1); } TEST(WeakPtr, NotifyCalledBeforeDestructor) { int dtor_called = 0; auto obj = new ObjType(dtor_called); int num_calls1 = 0; auto notify_fn1 = [&num_calls1, &dtor_called]() { num_calls1++; EXPECT_EQ(dtor_called, 0); }; WeakPtr<ObjType> weakptr1(obj, notify_fn1); ASSERT_TRUE(obj->RefCountIsOne()); EXPECT_EQ(obj->WeakRefCount(), 1); EXPECT_NE(weakptr1.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 0); obj->Unref(); EXPECT_EQ(weakptr1.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 1); EXPECT_EQ(dtor_called, 1); } TEST(WeakPtr, CopyTargetCalled) { auto obj = new ObjType(); int num_calls1 = 0; int num_calls2 = 0; auto notify_fn1 = [&num_calls1]() { num_calls1++; }; auto notify_fn2 = [&num_calls2]() { num_calls2++; }; WeakPtr<ObjType> weakptr1(obj, notify_fn1); WeakPtr<ObjType> weakptr2(obj, notify_fn2); WeakPtr<ObjType> weakptr3(weakptr1); weakptr2 = weakptr1; ASSERT_TRUE(obj->RefCountIsOne()); EXPECT_EQ(obj->WeakRefCount(), 3); EXPECT_NE(weakptr2.GetNewRef(), nullptr); EXPECT_NE(weakptr3.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 0); EXPECT_EQ(num_calls2, 0); obj->Unref(); EXPECT_EQ(weakptr2.GetNewRef(), nullptr); EXPECT_EQ(weakptr3.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 3); EXPECT_EQ(num_calls2, 0); } TEST(WeakPtr, MoveTargetNotCalled) { auto obj = new ObjType(); int num_calls1 = 0; int num_calls2 = 0; int num_calls3 = 0; auto notify_fn1 = [&num_calls1]() { num_calls1++; }; auto notify_fn2 = [&num_calls2]() { num_calls2++; }; auto notify_fn3 = [&num_calls3]() { num_calls3++; }; WeakPtr<ObjType> weakptr1(obj, notify_fn1); WeakPtr<ObjType> weakptr2(obj, notify_fn2); WeakPtr<ObjType> weakptr3(WeakPtr<ObjType>(obj, notify_fn3)); weakptr2 = std::move(weakptr1); ASSERT_TRUE(obj->RefCountIsOne()); EXPECT_EQ(obj->WeakRefCount(), 2); EXPECT_NE(weakptr2.GetNewRef(), nullptr); EXPECT_NE(weakptr3.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 0); EXPECT_EQ(num_calls2, 0); EXPECT_EQ(num_calls3, 0); obj->Unref(); EXPECT_EQ(weakptr2.GetNewRef(), nullptr); EXPECT_EQ(weakptr3.GetNewRef(), nullptr); EXPECT_EQ(num_calls1, 1); EXPECT_EQ(num_calls2, 0); EXPECT_EQ(num_calls3, 1); } TEST(WeakPtr, DestroyedNotifyNotCalled) { auto obj = new ObjType(); int num_calls = 0; auto notify_fn = [&num_calls]() { num_calls++; }; { WeakPtr<ObjType> weakptr(obj, notify_fn); } ASSERT_TRUE(obj->RefCountIsOne()); EXPECT_EQ(obj->WeakRefCount(), 0); EXPECT_EQ(num_calls, 0); obj->Unref(); EXPECT_EQ(num_calls, 0); } } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/refcount.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/refcount_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
777cc1b5-5357-4567-95b3-77796b769b4a
cpp
google/tsl
threadpool_async_executor
tsl/platform/threadpool_async_executor.h
tsl/platform/threadpool_async_executor_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_THREADPOOL_ASYNC_EXECUTOR_H_ #define TENSORFLOW_TSL_PLATFORM_THREADPOOL_ASYNC_EXECUTOR_H_ #include <utility> #include "xla/tsl/concurrency/async_value.h" #include "tsl/platform/threadpool.h" namespace tsl::thread { class ThreadPoolAsyncExecutor : public AsyncValue::Executor { public: explicit ThreadPoolAsyncExecutor(ThreadPool* thread_pool) : thread_pool_(thread_pool) {} void Execute(Task task) final { auto* task_ptr = new Task(std::move(task)); thread_pool_->Schedule([task_ptr] { (*task_ptr)(); delete task_ptr; }); } private: ThreadPool* thread_pool_; }; } #endif
#include "tsl/platform/threadpool_async_executor.h" #include "absl/synchronization/notification.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl::thread { namespace { TEST(ThreadPoolAsyncExecutorTest, ExecuteTasks) { ThreadPool thread_pool(Env::Default(), "test", 4); ThreadPoolAsyncExecutor executor(&thread_pool); absl::Notification notification; executor.Execute([&] { notification.Notify(); }); notification.WaitForNotification(); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/threadpool_async_executor.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/threadpool_async_executor_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
39ede851-60b9-4b19-80df-cfd236d29c33
cpp
google/tsl
fingerprint
tsl/platform/fingerprint.h
tsl/platform/fingerprint_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_FINGERPRINT_H_ #define TENSORFLOW_TSL_PLATFORM_FINGERPRINT_H_ #include "tsl/platform/platform.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/types.h" #if TSL_IS_IN_OSS #define USE_OSS_FARMHASH #endif #ifdef USE_OSS_FARMHASH #include <farmhash.h> #else #include "util/hash/farmhash_fingerprint.h" #endif namespace tsl { struct Fprint128 { uint64_t low64; uint64_t high64; }; inline bool operator==(const Fprint128& lhs, const Fprint128& rhs) { return lhs.low64 == rhs.low64 && lhs.high64 == rhs.high64; } struct Fprint128Hasher { size_t operator()(const Fprint128& v) const { return static_cast<size_t>(v.low64); } }; namespace internal { inline uint64_t ShiftMix(const uint64_t val) { return val ^ (val >> 47); } } inline uint64_t FingerprintCat64(const uint64_t fp1, const uint64_t fp2) { static const uint64_t kMul = 0xc6a4a7935bd1e995ULL; uint64_t result = fp1 ^ kMul; result ^= internal::ShiftMix(fp2 * kMul) * kMul; result *= kMul; result = internal::ShiftMix(result) * kMul; result = internal::ShiftMix(result); return result; } inline uint64_t Fingerprint64(const absl::string_view s) { #ifdef USE_OSS_FARMHASH return ::util::Fingerprint64(s.data(), s.size()); #else return farmhash::Fingerprint64(s.data(), s.size()); #endif } inline uint32_t Fingerprint32(const absl::string_view s) { #ifdef USE_OSS_FARMHASH return ::util::Fingerprint32(s.data(), s.size()); #else return farmhash::Fingerprint32(s.data(), s.size()); #endif } inline Fprint128 Fingerprint128(const absl::string_view s) { #ifdef USE_OSS_FARMHASH const auto fingerprint = ::util::Fingerprint128(s.data(), s.size()); return {::util::Uint128Low64(fingerprint), ::util::Uint128High64(fingerprint)}; #else const auto fingerprint = farmhash::Fingerprint128(s.data(), s.size()); return {absl::Uint128Low64(fingerprint), absl::Uint128High64(fingerprint)}; #endif } inline Fprint128 FingerprintCat128(const Fprint128& a, const Fprint128& b) { return {FingerprintCat64(a.low64, b.low64), FingerprintCat64(a.high64, b.high64)}; } inline Fprint128 FingerprintCat128(const Fprint128& a, const uint64_t b) { auto x = FingerprintCat64(a.low64, b); return {x, FingerprintCat64(a.high64, x)}; } } #endif
#include "tsl/platform/fingerprint.h" #include <unordered_set> #include "tsl/platform/test.h" #include "tsl/platform/types.h" namespace tsl { namespace { TEST(Fingerprint64, IsForeverFrozen) { EXPECT_EQ(15404698994557526151ULL, Fingerprint64("Hello")); EXPECT_EQ(18308117990299812472ULL, Fingerprint64("World")); } TEST(Fingerprint128, IsForeverFrozen) { { const Fprint128 fingerprint = Fingerprint128("Hello"); EXPECT_EQ(1163506517679092766ULL, fingerprint.low64); EXPECT_EQ(10829806600034513965ULL, fingerprint.high64); } { const Fprint128 fingerprint = Fingerprint128("World"); EXPECT_EQ(14404540403896557767ULL, fingerprint.low64); EXPECT_EQ(4859093245152058524ULL, fingerprint.high64); } } TEST(Fingerprint128, Fprint128Hasher) { const std::unordered_set<Fprint128, Fprint128Hasher> map = {{1, 2}, {3, 4}}; } TEST(FingerprintCat64, IsForeverFrozen) { EXPECT_EQ(16877292868973613377ULL, FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("World"))); EXPECT_EQ(7158413233176775252ULL, FingerprintCat64(Fingerprint64("World"), Fingerprint64("Hello"))); } TEST(FingerprintCat64, Idempotence) { const uint64_t orig = FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("World")); EXPECT_EQ(orig, FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("World"))); EXPECT_NE(FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("Hi")), FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("World"))); EXPECT_EQ(orig, FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("World"))); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/fingerprint.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/fingerprint_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
3e141fb0-20e1-44bb-9811-0160bc6ad953
cpp
google/tsl
criticality
tsl/platform/default/criticality.h
tsl/platform/criticality_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_CRITICALITY_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_CRITICALITY_H_ namespace tsl { namespace criticality { inline Criticality GetCriticality() { return Criticality::kCritical; } } } #endif
#include "tsl/platform/criticality.h" #include "tsl/platform/test.h" namespace tsl { namespace criticality { TEST(CriticalityTest, Basic) { EXPECT_EQ(GetCriticality(), Criticality::kCritical); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/default/criticality.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/criticality_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
d7563ad5-4d68-4de2-a7be-a79d148bcbfa
cpp
google/tsl
integral_types
tsl/platform/default/integral_types.h
tsl/platform/integral_types_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_ #include <cstdint> namespace tsl { typedef signed char int8; typedef short int16; typedef int int32; typedef ::std::int64_t int64; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef std::uint64_t uint64; } #endif
#include "tsl/platform/test.h" #include "tsl/platform/types.h" namespace tsl { namespace { TEST(IntegralTypes, Basic) { EXPECT_EQ(1, sizeof(int8)); EXPECT_EQ(2, sizeof(int16)); EXPECT_EQ(4, sizeof(int32)); EXPECT_EQ(8, sizeof(int64_t)); EXPECT_EQ(1, sizeof(uint8)); EXPECT_EQ(2, sizeof(uint16)); EXPECT_EQ(4, sizeof(uint32)); EXPECT_EQ(8, sizeof(uint64)); } TEST(IntegralTypes, MinAndMaxConstants) { EXPECT_EQ(static_cast<uint8>(kint8min), static_cast<uint8>(kint8max) + 1); EXPECT_EQ(static_cast<uint16>(kint16min), static_cast<uint16>(kint16max) + 1); EXPECT_EQ(static_cast<uint32>(kint32min), static_cast<uint32>(kint32max) + 1); EXPECT_EQ(static_cast<uint64>(kint64min), static_cast<uint64>(kint64max) + 1); EXPECT_EQ(0, static_cast<uint8>(kuint8max + 1)); EXPECT_EQ(0, static_cast<uint16>(kuint16max + 1)); EXPECT_EQ(0, static_cast<uint32>(kuint32max + 1)); EXPECT_EQ(0, static_cast<uint64>(kuint64max + 1)); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/default/integral_types.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/integral_types_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
91aaefa3-4292-4601-b861-d0aa60b79ec6
cpp
google/tsl
expiring_lru_cache
tsl/platform/cloud/expiring_lru_cache.h
tsl/platform/cloud/expiring_lru_cache_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_EXPIRING_LRU_CACHE_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_EXPIRING_LRU_CACHE_H_ #include <list> #include <map> #include <memory> #include <string> #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" namespace tsl { template <typename T> class ExpiringLRUCache { public: ExpiringLRUCache(uint64 max_age, size_t max_entries, Env* env = Env::Default()) : max_age_(max_age), max_entries_(max_entries), env_(env) {} void Insert(const string& key, const T& value) { if (max_age_ == 0) { return; } mutex_lock lock(mu_); InsertLocked(key, value); } bool Delete(const string& key) { mutex_lock lock(mu_); return DeleteLocked(key); } bool Lookup(const string& key, T* value) { if (max_age_ == 0) { return false; } mutex_lock lock(mu_); return LookupLocked(key, value); } typedef std::function<absl::Status(const string&, T*)> ComputeFunc; absl::Status LookupOrCompute(const string& key, T* value, const ComputeFunc& compute_func) { if (max_age_ == 0) { return compute_func(key, value); } mutex_lock lock(mu_); if (LookupLocked(key, value)) { return absl::OkStatus(); } absl::Status s = compute_func(key, value); if (s.ok()) { InsertLocked(key, *value); } return s; } void Clear() { mutex_lock lock(mu_); cache_.clear(); lru_list_.clear(); } uint64 max_age() const { return max_age_; } size_t max_entries() const { return max_entries_; } private: struct Entry { uint64 timestamp; T value; std::list<string>::iterator lru_iterator; }; bool LookupLocked(const string& key, T* value) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { auto it = cache_.find(key); if (it == cache_.end()) { return false; } lru_list_.erase(it->second.lru_iterator); if (env_->NowSeconds() - it->second.timestamp > max_age_) { cache_.erase(it); return false; } *value = it->second.value; lru_list_.push_front(it->first); it->second.lru_iterator = lru_list_.begin(); return true; } void InsertLocked(const string& key, const T& value) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { lru_list_.push_front(key); Entry entry{env_->NowSeconds(), value, lru_list_.begin()}; auto insert = cache_.insert(std::make_pair(key, entry)); if (!insert.second) { lru_list_.erase(insert.first->second.lru_iterator); insert.first->second = entry; } else if (max_entries_ > 0 && cache_.size() > max_entries_) { cache_.erase(lru_list_.back()); lru_list_.pop_back(); } } bool DeleteLocked(const string& key) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { auto it = cache_.find(key); if (it == cache_.end()) { return false; } lru_list_.erase(it->second.lru_iterator); cache_.erase(it); return true; } const uint64 max_age_; const size_t max_entries_; Env* const env_; mutex mu_; std::map<string, Entry> cache_ TF_GUARDED_BY(mu_); std::list<string> lru_list_ TF_GUARDED_BY(mu_); }; } #endif
#include "tsl/platform/cloud/expiring_lru_cache.h" #include <memory> #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/cloud/now_seconds_env.h" #include "tsl/platform/test.h" namespace tsl { namespace { TEST(ExpiringLRUCacheTest, MaxAge) { const string key = "a"; std::unique_ptr<NowSecondsEnv> env(new NowSecondsEnv); ExpiringLRUCache<int> cache(1, 0, env.get()); env->SetNowSeconds(1); cache.Insert(key, 41); env->SetNowSeconds(2); cache.Insert(key, 42); env->SetNowSeconds(3); int value = 0; EXPECT_TRUE(cache.Lookup(key, &value)); EXPECT_EQ(value, 42); env->SetNowSeconds(4); EXPECT_FALSE(cache.Lookup(key, &value)); cache.Insert(key, 43); EXPECT_TRUE(cache.Lookup(key, &value)); EXPECT_EQ(value, 43); env->SetNowSeconds(5); value = 0; EXPECT_TRUE(cache.Lookup(key, &value)); EXPECT_EQ(value, 43); env->SetNowSeconds(6); EXPECT_FALSE(cache.Lookup(key, &value)); } TEST(ExpiringLRUCacheTest, MaxEntries) { ExpiringLRUCache<int> cache1(0, 4); cache1.Insert("a", 1); int value = 0; EXPECT_FALSE(cache1.Lookup("a", &value)); ExpiringLRUCache<int> cache2(1, 4); cache2.Insert("a", 1); cache2.Insert("b", 2); cache2.Insert("c", 3); cache2.Insert("d", 4); EXPECT_TRUE(cache2.Lookup("a", &value)); EXPECT_EQ(value, 1); EXPECT_TRUE(cache2.Lookup("b", &value)); EXPECT_EQ(value, 2); EXPECT_TRUE(cache2.Lookup("c", &value)); EXPECT_EQ(value, 3); EXPECT_TRUE(cache2.Lookup("d", &value)); EXPECT_EQ(value, 4); cache2.Insert("e", 5); EXPECT_FALSE(cache2.Lookup("a", &value)); EXPECT_TRUE(cache2.Lookup("b", &value)); EXPECT_EQ(value, 2); EXPECT_TRUE(cache2.Lookup("c", &value)); EXPECT_EQ(value, 3); EXPECT_TRUE(cache2.Lookup("d", &value)); EXPECT_EQ(value, 4); EXPECT_TRUE(cache2.Lookup("e", &value)); EXPECT_EQ(value, 5); } TEST(ExpiringLRUCacheTest, LookupOrCompute) { uint64 num_compute_calls = 0; ExpiringLRUCache<int>::ComputeFunc compute_func = [&num_compute_calls](const string& key, int* value) { *value = num_compute_calls; num_compute_calls++; return absl::OkStatus(); }; ExpiringLRUCache<int> cache1(0, 4); int value = -1; TF_EXPECT_OK(cache1.LookupOrCompute("a", &value, compute_func)); EXPECT_EQ(value, 0); EXPECT_EQ(num_compute_calls, 1); TF_EXPECT_OK(cache1.LookupOrCompute("a", &value, compute_func)); EXPECT_EQ(value, 1); EXPECT_EQ(num_compute_calls, 2); ExpiringLRUCache<int> cache2(2, 4); num_compute_calls = 0; value = -1; TF_EXPECT_OK(cache2.LookupOrCompute("a", &value, compute_func)); EXPECT_EQ(value, 0); EXPECT_EQ(num_compute_calls, 1); TF_EXPECT_OK(cache2.LookupOrCompute("a", &value, compute_func)); EXPECT_EQ(value, 0); EXPECT_EQ(num_compute_calls, 1); TF_EXPECT_OK(cache2.LookupOrCompute("b", &value, compute_func)); EXPECT_EQ(value, 1); EXPECT_EQ(num_compute_calls, 2); TF_EXPECT_OK(cache2.LookupOrCompute("c", &value, compute_func)); EXPECT_EQ(value, 2); EXPECT_EQ(num_compute_calls, 3); TF_EXPECT_OK(cache2.LookupOrCompute("d", &value, compute_func)); EXPECT_EQ(value, 3); EXPECT_EQ(num_compute_calls, 4); TF_EXPECT_OK(cache2.LookupOrCompute("e", &value, compute_func)); EXPECT_EQ(value, 4); EXPECT_EQ(num_compute_calls, 5); TF_EXPECT_OK(cache2.LookupOrCompute("b", &value, compute_func)); EXPECT_EQ(value, 1); EXPECT_EQ(num_compute_calls, 5); TF_EXPECT_OK(cache2.LookupOrCompute("c", &value, compute_func)); EXPECT_EQ(value, 2); EXPECT_EQ(num_compute_calls, 5); TF_EXPECT_OK(cache2.LookupOrCompute("d", &value, compute_func)); EXPECT_EQ(value, 3); EXPECT_EQ(num_compute_calls, 5); TF_EXPECT_OK(cache2.LookupOrCompute("a", &value, compute_func)); EXPECT_EQ(value, 5); EXPECT_EQ(num_compute_calls, 6); } TEST(ExpiringLRUCacheTest, Clear) { ExpiringLRUCache<int> cache(1, 4); cache.Insert("a", 1); cache.Insert("b", 2); cache.Insert("c", 3); cache.Insert("d", 4); int value = 0; EXPECT_TRUE(cache.Lookup("a", &value)); EXPECT_EQ(value, 1); EXPECT_TRUE(cache.Lookup("b", &value)); EXPECT_EQ(value, 2); EXPECT_TRUE(cache.Lookup("c", &value)); EXPECT_EQ(value, 3); EXPECT_TRUE(cache.Lookup("d", &value)); EXPECT_EQ(value, 4); cache.Clear(); EXPECT_FALSE(cache.Lookup("a", &value)); EXPECT_FALSE(cache.Lookup("b", &value)); EXPECT_FALSE(cache.Lookup("c", &value)); EXPECT_FALSE(cache.Lookup("d", &value)); } TEST(ExpiringLRUCacheTest, Delete) { ExpiringLRUCache<int> cache(1, 4); cache.Insert("a", 1); int value = 0; EXPECT_TRUE(cache.Lookup("a", &value)); EXPECT_EQ(value, 1); EXPECT_TRUE(cache.Delete("a")); EXPECT_FALSE(cache.Lookup("a", &value)); EXPECT_FALSE(cache.Delete("a")); EXPECT_FALSE(cache.Lookup("a", &value)); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/expiring_lru_cache.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/platform/cloud/expiring_lru_cache_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
35322236-752a-4ec4-8d6f-3ed654be6fab
cpp
google/tsl
scoped_annotation
tsl/profiler/lib/scoped_annotation.h
tsl/profiler/lib/scoped_annotation_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_LIB_SCOPED_ANNOTATION_H_ #define TENSORFLOW_TSL_PROFILER_LIB_SCOPED_ANNOTATION_H_ #include <stddef.h> #include <atomic> #include <string> #include <string_view> #include <utility> #include "tsl/platform/macros.h" #include "tsl/platform/platform.h" #include "tsl/profiler/lib/nvtx_utils.h" #if !defined(IS_MOBILE_PLATFORM) #include "xla/tsl/profiler/backends/cpu/annotation_stack.h" #endif namespace tsl::profiler { template <typename T> void PushAnnotation(const T& generator) { if (auto domain = DefaultProfilerDomain(); TF_PREDICT_FALSE(domain != nullptr)) { RangePush(domain, generator()); return; } #if !defined(IS_MOBILE_PLATFORM) if (TF_PREDICT_FALSE(AnnotationStack::IsEnabled())) { AnnotationStack::PushAnnotation(static_cast<std::string_view>(generator())); } #endif } inline void PushAnnotation(const char* name) { PushAnnotation([&] { return name; }); } inline void PushAnnotation(const std::string& name) { PushAnnotation([&] { return name; }); } inline void PopAnnotation() { std::atomic_thread_fence(std::memory_order_acquire); if (auto domain = DefaultProfilerDomain(); TF_PREDICT_FALSE(domain != nullptr)) { RangePop(domain); return; } #if !defined(IS_MOBILE_PLATFORM) if (TF_PREDICT_FALSE(AnnotationStack::IsEnabled())) { AnnotationStack::PopAnnotation(); } #endif } class ScopedAnnotation { public: template <typename T> explicit ScopedAnnotation(T&& annotation) { PushAnnotation(std::forward<T>(annotation)); } ~ScopedAnnotation() { PopAnnotation(); } static bool IsEnabled() { #if !defined(IS_MOBILE_PLATFORM) return AnnotationStack::IsEnabled(); #else return false; #endif } private: ScopedAnnotation(const ScopedAnnotation&) = delete; ScopedAnnotation& operator=(const ScopedAnnotation&) = delete; }; } #endif
#include "tsl/profiler/lib/scoped_annotation.h" #include <string> #include "absl/strings/str_cat.h" #include "xla/tsl/profiler/backends/cpu/annotation_stack.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { namespace profiler { namespace { TEST(ScopedAnnotation, Simple) { { ScopedAnnotation trace("blah"); EXPECT_EQ(AnnotationStack::Get(), ""); } { AnnotationStack::Enable(true); ScopedAnnotation trace("blah"); EXPECT_EQ(AnnotationStack::Get(), "blah"); AnnotationStack::Enable(false); } { AnnotationStack::Enable(true); ScopedAnnotation outer("foo"); ScopedAnnotation inner("bar"); EXPECT_EQ(AnnotationStack::Get(), "foo::bar"); AnnotationStack::Enable(false); } { AnnotationStack::Enable(true); PushAnnotation("foo"); PushAnnotation("bar"); EXPECT_EQ(AnnotationStack::Get(), "foo::bar"); PopAnnotation(); PopAnnotation(); AnnotationStack::Enable(false); } EXPECT_EQ(AnnotationStack::Get(), ""); } std::string GenerateRandomString(int length) { return std::string(length, 'a'); } void BM_ScopedAnnotationDisabled(::testing::benchmark::State& state) { const int annotation_size = state.range(0); std::string annotation = GenerateRandomString(annotation_size); for (auto s : state) { ScopedAnnotation trace(annotation); } } BENCHMARK(BM_ScopedAnnotationDisabled)->Arg(8)->Arg(32)->Arg(128); void BM_ScopedAnnotationEnabled(::testing::benchmark::State& state) { const int annotation_size = state.range(0); std::string annotation = GenerateRandomString(annotation_size); AnnotationStack::Enable(true); for (auto s : state) { ScopedAnnotation trace(annotation); } AnnotationStack::Enable(false); } BENCHMARK(BM_ScopedAnnotationEnabled)->Arg(8)->Arg(32)->Arg(128); void BM_ScopedAnnotationEnabled_Nested(::testing::benchmark::State& state) { const int annotation_size = state.range(0); std::string annotation = GenerateRandomString(annotation_size); AnnotationStack::Enable(true); for (auto s : state) { ScopedAnnotation trace(annotation); { ScopedAnnotation trace(annotation); } } AnnotationStack::Enable(false); } BENCHMARK(BM_ScopedAnnotationEnabled_Nested)->Arg(8)->Arg(32)->Arg(128); void BM_ScopedAnnotationEnabled_Adhoc(::testing::benchmark::State& state) { AnnotationStack::Enable(true); int i = 0; for (auto s : state) { ScopedAnnotation trace(absl::StrCat(i, "-", i * i)); ++i; } AnnotationStack::Enable(false); } BENCHMARK(BM_ScopedAnnotationEnabled_Adhoc); void BM_ScopedAnnotationDisabled_Lambda(::testing::benchmark::State& state) { int i = 0; for (auto s : state) { ScopedAnnotation trace([&]() { return absl::StrCat(i, "-", i * i); }); ++i; } } BENCHMARK(BM_ScopedAnnotationDisabled_Lambda); void BM_ScopedAnnotationEnabled_Adhoc_Lambda( ::testing::benchmark::State& state) { AnnotationStack::Enable(true); int i = 0; for (auto s : state) { ScopedAnnotation trace([&]() { return absl::StrCat(i, "-", i * i); }); ++i; } AnnotationStack::Enable(false); } BENCHMARK(BM_ScopedAnnotationEnabled_Adhoc_Lambda); } } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/scoped_annotation.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/scoped_annotation_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
e565f5e2-dd49-475c-bed3-1886c9573187
cpp
google/tsl
traceme_encode
tsl/profiler/lib/traceme_encode.h
tsl/profiler/lib/traceme_encode_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_LIB_TRACEME_ENCODE_H_ #define TENSORFLOW_TSL_PROFILER_LIB_TRACEME_ENCODE_H_ #include <string.h> #include <initializer_list> #include <string> #include "absl/base/attributes.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { struct TraceMeArg { TraceMeArg(absl::string_view k, const absl::AlphaNum& v ABSL_ATTRIBUTE_LIFETIME_BOUND) : key(k), value(v.Piece()) {} TraceMeArg(const TraceMeArg&) = delete; void operator=(const TraceMeArg&) = delete; absl::string_view key; absl::string_view value; }; namespace traceme_internal { TF_ATTRIBUTE_ALWAYS_INLINE inline char* Append(char* out, absl::string_view str) { DCHECK(!absl::StrContains(str, '#')) << "'#' is not a valid character in TraceMeEncode"; const size_t str_size = str.size(); if (TF_PREDICT_TRUE(str_size > 0)) { memcpy(out, str.data(), str_size); out += str_size; } return out; } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string AppendArgs( std::string name, std::initializer_list<TraceMeArg> args) { if (TF_PREDICT_TRUE(args.size() > 0)) { const auto old_size = name.size(); auto new_size = old_size + args.size() * 2 + 1; for (const auto& arg : args) { new_size += arg.key.size() + arg.value.size(); } name.resize(new_size); char* const begin = &name[0]; char* out = begin + old_size; *out++ = '#'; for (const auto& arg : args) { out = Append(out, arg.key); *out++ = '='; out = Append(out, arg.value); *out++ = ','; } *(out - 1) = '#'; DCHECK_EQ(out, begin + new_size); } return name; } TF_ATTRIBUTE_ALWAYS_INLINE inline void AppendMetadata( std::string* name, absl::string_view new_metadata) { if (!TF_PREDICT_FALSE(new_metadata.empty())) { if (!name->empty() && name->back() == '#') { name->back() = ','; if (TF_PREDICT_TRUE(new_metadata.front() == '#')) { new_metadata.remove_prefix(1); } } name->append(new_metadata.data(), new_metadata.size()); } } } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeEncode( std::string name, std::initializer_list<TraceMeArg> args) { return traceme_internal::AppendArgs(std::move(name), args); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeEncode( absl::string_view name, std::initializer_list<TraceMeArg> args) { return traceme_internal::AppendArgs(std::string(name), args); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeEncode( const char* name, std::initializer_list<TraceMeArg> args) { return traceme_internal::AppendArgs(std::string(name), args); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeEncode( std::initializer_list<TraceMeArg> args) { return traceme_internal::AppendArgs(std::string(), args); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeOp( absl::string_view op_name, absl::string_view op_type) { return absl::StrCat(op_name, ":", op_type); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeOp(const char* op_name, const char* op_type) { return absl::StrCat(op_name, ":", op_type); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeOp( std::string&& op_name, absl::string_view op_type) { absl::StrAppend(&op_name, ":", op_type); return op_name; } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeOpOverride( absl::string_view op_name, absl::string_view op_type) { return absl::StrCat("#tf_op=", op_name, ":", op_type, "#"); } TF_ATTRIBUTE_ALWAYS_INLINE inline std::string TraceMeOpOverride( const char* op_name, const char* op_type) { return absl::StrCat("#tf_op=", op_name, ":", op_type, "#"); } } } #endif
#include "tsl/profiler/lib/traceme_encode.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "tsl/platform/platform.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { namespace profiler { namespace { TEST(TraceMeEncodeTest, NoArgTest) { EXPECT_EQ(TraceMeEncode("Hello!", {}), "Hello!"); } TEST(TraceMeEncodeTest, OneArgTest) { EXPECT_EQ(TraceMeEncode("Hello", {{"context", "World"}}), "Hello#context=World#"); } TEST(TraceMeEncodeTest, TwoArgsTest) { EXPECT_EQ(TraceMeEncode("Hello", {{"context", "World"}, {"request_id", 42}}), "Hello#context=World,request_id=42#"); } TEST(TraceMeEncodeTest, ThreeArgsTest) { EXPECT_EQ(TraceMeEncode("Hello", {{"context", "World"}, {"request_id", 42}, {"addr", absl::Hex(0xdeadbeef)}}), "Hello#context=World,request_id=42,addr=deadbeef#"); } #if !defined(PLATFORM_WINDOWS) TEST(TraceMeEncodeTest, TemporaryStringTest) { EXPECT_EQ(TraceMeEncode("Hello", {{std::string("context"), absl::StrCat("World:", 2020)}}), "Hello#context=World:2020#"); } #endif #if defined(PLATFORM_GOOGLE) struct Point { template <typename Sink> friend void AbslStringify(Sink& sink, const Point& p) { absl::Format(&sink, "(%d, %d)", p.x, p.y); } int x; int y; }; TEST(TraceMeEncodeTest, AbslStringifyTest) { EXPECT_EQ(TraceMeEncode("Plot", {{"point", Point{10, 20}}}), "Plot#point=(10, 20)#"); } #endif TEST(TraceMeEncodeTest, NoNameTest) { EXPECT_EQ(TraceMeEncode({{"context", "World"}, {"request_id", 42}}), "#context=World,request_id=42#"); } } void BM_TraceMeEncode(::testing::benchmark::State& state) { for (auto s : state) { TraceMeEncode( "MyTestEvent", {{"Lorem ipsum dolor sit amet", 1}, {"consectetur adipiscing elit", 2}, {"sed do eiusmod tempor incididunt", 3.52}, {"ut labore et dolore magna aliqua", "Ut enim ad minim veniam"}, {"quis nostrud exercitation ullamco", "laboris nisi ut aliquip ex"}, {"ea commodo consequat.", 11111.1111}, {"Duis aute", 1234567890}, {"irure dolor in", " reprehenderit in voluptate"}, {"velit esse cillum dolore", "eu fugiat nulla pariatur."}, {"Excepteur sint", "occaecat cupidatat non proident, sunt in"}, {"culpa qui officia", "deserunt mollit anim id est laborum."}}); } } BENCHMARK(BM_TraceMeEncode); } }
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/traceme_encode.h
https://github.com/google/tsl/blob/6d708fdcdd4f40537b7fa273371215a6fa3d4423/tsl/profiler/lib/traceme_encode_test.cc
6d708fdcdd4f40537b7fa273371215a6fa3d4423
a820520b-9e83-4f87-bd88-7914067953c6
cpp
google/quiche
oblivious_http_client
quiche/oblivious_http/oblivious_http_client.cc
quiche/oblivious_http/oblivious_http_client_test.cc
#include "quiche/oblivious_http/oblivious_http_client.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_crypto_logging.h" namespace quiche { namespace { absl::Status ValidateClientParameters( absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new()); if (client_ctx == nullptr) { return SslErrorAsStatus( "Failed to initialize HPKE ObliviousHttpClient Context."); } std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0'); size_t enc_len; absl::string_view info = "verify if given HPKE public key is valid"; if (!EVP_HPKE_CTX_setup_sender( client_ctx.get(), reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), ohttp_key_config.GetHpkeKem(), ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(hpke_public_key.data()), hpke_public_key.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size())) { return SslErrorAsStatus( "Failed to setup HPKE context with given public key param " "hpke_public_key."); } return absl::OkStatus(); } } ObliviousHttpClient::ObliviousHttpClient( std::string client_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) : hpke_public_key_(std::move(client_public_key)), ohttp_key_config_(ohttp_key_config) {} absl::StatusOr<ObliviousHttpClient> ObliviousHttpClient::Create( absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) { if (hpke_public_key.empty()) { return absl::InvalidArgumentError("Invalid/Empty HPKE public key."); } auto is_valid_input = ValidateClientParameters(hpke_public_key, ohttp_key_config); if (!is_valid_input.ok()) { return absl::InvalidArgumentError( absl::StrCat("Invalid input received in method parameters. ", is_valid_input.message())); } return ObliviousHttpClient(std::string(hpke_public_key), ohttp_key_config); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpClient::CreateObliviousHttpRequest( std::string plaintext_data) const { return ObliviousHttpRequest::CreateClientObliviousRequest( std::move(plaintext_data), hpke_public_key_, ohttp_key_config_); } absl::StatusOr<ObliviousHttpResponse> ObliviousHttpClient::DecryptObliviousHttpResponse( std::string encrypted_data, ObliviousHttpRequest::Context& oblivious_http_request_context) const { return ObliviousHttpResponse::CreateClientObliviousResponse( std::move(encrypted_data), oblivious_http_request_context); } }
#include "quiche/oblivious_http/oblivious_http_client.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_thread.h" namespace quiche { std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return ohttp_key_config.value(); } bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey( absl::string_view hpke_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new()); EXPECT_NE(bssl_hpke_key, nullptr); EXPECT_TRUE(EVP_HPKE_KEY_init( bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t*>(hpke_key.data()), hpke_key.size())); return bssl_hpke_key; } TEST(ObliviousHttpClient, TestEncapsulate) { auto client = ObliviousHttpClient::Create( GetHpkePublicKey(), GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(client.ok()); auto encrypted_req = client->CreateObliviousHttpRequest("test string 1"); ASSERT_TRUE(encrypted_req.ok()); auto serialized_encrypted_req = encrypted_req->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_encrypted_req.empty()); } TEST(ObliviousHttpClient, TestEncryptingMultipleRequestsWithSingleInstance) { auto client = ObliviousHttpClient::Create( GetHpkePublicKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(client.ok()); auto ohttp_req_1 = client->CreateObliviousHttpRequest("test string 1"); ASSERT_TRUE(ohttp_req_1.ok()); auto serialized_ohttp_req_1 = ohttp_req_1->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_ohttp_req_1.empty()); auto ohttp_req_2 = client->CreateObliviousHttpRequest("test string 2"); ASSERT_TRUE(ohttp_req_2.ok()); auto serialized_ohttp_req_2 = ohttp_req_2->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_ohttp_req_2.empty()); EXPECT_NE(serialized_ohttp_req_1, serialized_ohttp_req_2); } TEST(ObliviousHttpClient, TestInvalidHPKEKey) { EXPECT_EQ(ObliviousHttpClient::Create( "Invalid HPKE key", GetOhttpKeyConfig(50, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpClient::Create( "", GetOhttpKeyConfig(50, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpClient, TestTwoSamePlaintextsWillGenerateDifferentEncryptedPayloads) { auto client = ObliviousHttpClient::Create( GetHpkePublicKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(client.ok()); auto encrypted_request_1 = client->CreateObliviousHttpRequest("same plaintext"); ASSERT_TRUE(encrypted_request_1.ok()); auto serialized_encrypted_request_1 = encrypted_request_1->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_encrypted_request_1.empty()); auto encrypted_request_2 = client->CreateObliviousHttpRequest("same plaintext"); ASSERT_TRUE(encrypted_request_2.ok()); auto serialized_encrypted_request_2 = encrypted_request_2->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_encrypted_request_2.empty()); EXPECT_NE(serialized_encrypted_request_1, serialized_encrypted_request_2); } TEST(ObliviousHttpClient, TestObliviousResponseHandling) { auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate_req_on_client = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate_req_on_client.ok()); auto decapsulate_req_on_gateway = ObliviousHttpRequest::CreateServerObliviousRequest( encapsulate_req_on_client->EncapsulateAndSerialize(), *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(decapsulate_req_on_gateway.ok()); auto gateway_request_context = std::move(decapsulate_req_on_gateway.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", gateway_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); auto client = ObliviousHttpClient::Create(GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(client.ok()); auto client_request_context = std::move(encapsulate_req_on_client.value()).ReleaseContext(); auto decapsulate_resp_on_client = client->DecryptObliviousHttpResponse( encapsulate_resp_on_gateway->EncapsulateAndSerialize(), client_request_context); ASSERT_TRUE(decapsulate_resp_on_client.ok()); EXPECT_EQ(decapsulate_resp_on_client->GetPlaintextData(), "test response"); } TEST(ObliviousHttpClient, DecryptResponseReceivedByTheClientUsingServersObliviousContext) { auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate_req_on_client = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate_req_on_client.ok()); auto decapsulate_req_on_gateway = ObliviousHttpRequest::CreateServerObliviousRequest( encapsulate_req_on_client->EncapsulateAndSerialize(), *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(decapsulate_req_on_gateway.ok()); auto gateway_request_context = std::move(decapsulate_req_on_gateway.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", gateway_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); auto client = ObliviousHttpClient::Create(GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(client.ok()); auto decapsulate_resp_on_client = client->DecryptObliviousHttpResponse( encapsulate_resp_on_gateway->EncapsulateAndSerialize(), gateway_request_context); ASSERT_TRUE(decapsulate_resp_on_client.ok()); EXPECT_EQ(decapsulate_resp_on_client->GetPlaintextData(), "test response"); } TEST(ObliviousHttpClient, TestWithMultipleThreads) { class TestQuicheThread : public QuicheThread { public: TestQuicheThread(const ObliviousHttpClient& client, std::string request_payload, ObliviousHttpHeaderKeyConfig ohttp_key_config) : QuicheThread("client_thread"), client_(client), request_payload_(request_payload), ohttp_key_config_(ohttp_key_config) {} protected: void Run() override { auto encrypted_request = client_.CreateObliviousHttpRequest(request_payload_); ASSERT_TRUE(encrypted_request.ok()); ASSERT_FALSE(encrypted_request->EncapsulateAndSerialize().empty()); auto decapsulate_req_on_gateway = ObliviousHttpRequest::CreateServerObliviousRequest( encrypted_request->EncapsulateAndSerialize(), *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config_)), ohttp_key_config_); ASSERT_TRUE(decapsulate_req_on_gateway.ok()); auto gateway_request_context = std::move(decapsulate_req_on_gateway.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", gateway_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); ASSERT_FALSE( encapsulate_resp_on_gateway->EncapsulateAndSerialize().empty()); auto client_request_context = std::move(encrypted_request.value()).ReleaseContext(); auto decrypted_response = client_.DecryptObliviousHttpResponse( encapsulate_resp_on_gateway->EncapsulateAndSerialize(), client_request_context); ASSERT_TRUE(decrypted_response.ok()); ASSERT_FALSE(decrypted_response->GetPlaintextData().empty()); } private: const ObliviousHttpClient& client_; std::string request_payload_; ObliviousHttpHeaderKeyConfig ohttp_key_config_; }; auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto client = ObliviousHttpClient::Create(GetHpkePublicKey(), ohttp_key_config); TestQuicheThread t1(*client, "test request 1", ohttp_key_config); TestQuicheThread t2(*client, "test request 2", ohttp_key_config); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/oblivious_http_client.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/oblivious_http_client_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b177da21-0cd6-4142-be0f-c1ea4d838d88
cpp
google/quiche
oblivious_http_gateway
quiche/oblivious_http/oblivious_http_gateway.cc
quiche/oblivious_http/oblivious_http_gateway_test.cc
#include "quiche/oblivious_http/oblivious_http_gateway.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_crypto_logging.h" #include "quiche/common/quiche_random.h" namespace quiche { ObliviousHttpGateway::ObliviousHttpGateway( bssl::UniquePtr<EVP_HPKE_KEY> recipient_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, QuicheRandom* quiche_random) : server_hpke_key_(std::move(recipient_key)), ohttp_key_config_(ohttp_key_config), quiche_random_(quiche_random) {} absl::StatusOr<ObliviousHttpGateway> ObliviousHttpGateway::Create( absl::string_view hpke_private_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, QuicheRandom* quiche_random) { if (hpke_private_key.empty()) { return absl::InvalidArgumentError("Invalid/Empty HPKE private key."); } bssl::UniquePtr<EVP_HPKE_KEY> recipient_key(EVP_HPKE_KEY_new()); if (recipient_key == nullptr) { return SslErrorAsStatus( "Failed to initialize ObliviousHttpGateway/Server's Key."); } if (!EVP_HPKE_KEY_init( recipient_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t*>(hpke_private_key.data()), hpke_private_key.size())) { return SslErrorAsStatus("Failed to import HPKE private key."); } if (quiche_random == nullptr) quiche_random = QuicheRandom::GetInstance(); return ObliviousHttpGateway(std::move(recipient_key), ohttp_key_config, quiche_random); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpGateway::DecryptObliviousHttpRequest( absl::string_view encrypted_data, absl::string_view request_label) const { return ObliviousHttpRequest::CreateServerObliviousRequest( encrypted_data, *(server_hpke_key_), ohttp_key_config_, request_label); } absl::StatusOr<ObliviousHttpResponse> ObliviousHttpGateway::CreateObliviousHttpResponse( std::string plaintext_data, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view response_label) const { return ObliviousHttpResponse::CreateServerObliviousResponse( std::move(plaintext_data), oblivious_http_request_context, response_label, quiche_random_); } }
#include "quiche/oblivious_http/oblivious_http_gateway.h" #include <stdint.h> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_thread.h" #include "quiche/common/quiche_random.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" namespace quiche { namespace { std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return std::move(ohttp_key_config.value()); } TEST(ObliviousHttpGateway, TestProvisioningKeyAndDecapsulate) { constexpr absl::string_view kX25519SecretKey = "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"; std::string x25519_secret_key_bytes; ASSERT_TRUE( absl::HexStringToBytes(kX25519SecretKey, &x25519_secret_key_bytes)); auto instance = ObliviousHttpGateway::Create( x25519_secret_key_bytes, GetOhttpKeyConfig( 1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM)); constexpr absl::string_view kEncapsulatedRequest = "010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c2" "08b4726374e469135906992e1268c594d2a10c695d858c40a026e7965e7d86b83dd440b2" "c0185204b4d63525"; std::string encapsulated_request_bytes; ASSERT_TRUE(absl::HexStringToBytes(kEncapsulatedRequest, &encapsulated_request_bytes)); auto decrypted_req = instance->DecryptObliviousHttpRequest(encapsulated_request_bytes); ASSERT_TRUE(decrypted_req.ok()); ASSERT_FALSE(decrypted_req->GetPlaintextData().empty()); } TEST(ObliviousHttpGateway, TestDecryptingMultipleRequestsWithSingleInstance) { auto instance = ObliviousHttpGateway::Create( GetHpkePrivateKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); absl::string_view encrypted_req_1 = "010020000100025f20b60306b61ad9ecad389acd752ca75c4e2969469809fe3d84aae137" "f73e4ccfe9ba71f12831fdce6c8202fbd38a84c5d8a73ac4c8ea6c10592594845f"; std::string encrypted_req_1_bytes; ASSERT_TRUE(absl::HexStringToBytes(encrypted_req_1, &encrypted_req_1_bytes)); auto decapsulated_req_1 = instance->DecryptObliviousHttpRequest(encrypted_req_1_bytes); ASSERT_TRUE(decapsulated_req_1.ok()); ASSERT_FALSE(decapsulated_req_1->GetPlaintextData().empty()); absl::string_view encrypted_req_2 = "01002000010002285ebc2fcad72cc91b378050cac29a62feea9cd97829335ee9fc87e672" "4fa13ff2efdff620423d54225d3099088e7b32a5165f805a5d922918865a0a447a"; std::string encrypted_req_2_bytes; ASSERT_TRUE(absl::HexStringToBytes(encrypted_req_2, &encrypted_req_2_bytes)); auto decapsulated_req_2 = instance->DecryptObliviousHttpRequest(encrypted_req_2_bytes); ASSERT_TRUE(decapsulated_req_2.ok()); ASSERT_FALSE(decapsulated_req_2->GetPlaintextData().empty()); } TEST(ObliviousHttpGateway, TestInvalidHPKEKey) { EXPECT_EQ(ObliviousHttpGateway::Create( "Invalid HPKE key", GetOhttpKeyConfig(70, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInternal); EXPECT_EQ(ObliviousHttpGateway::Create( "", GetOhttpKeyConfig(70, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpGateway, TestObliviousResponseHandling) { auto ohttp_key_config = GetOhttpKeyConfig(3, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto instance = ObliviousHttpGateway::Create(GetHpkePrivateKey(), ohttp_key_config); ASSERT_TRUE(instance.ok()); auto encapsualte_request_on_client = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsualte_request_on_client.ok()); auto decapsulated_req_on_server = instance->DecryptObliviousHttpRequest( encapsualte_request_on_client->EncapsulateAndSerialize()); ASSERT_TRUE(decapsulated_req_on_server.ok()); auto server_request_context = std::move(decapsulated_req_on_server.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = instance->CreateObliviousHttpResponse( "some response", server_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); ASSERT_FALSE(encapsulate_resp_on_gateway->EncapsulateAndSerialize().empty()); } TEST(ObliviousHttpGateway, TestHandlingMultipleResponsesForMultipleRequestsWithSingleInstance) { auto instance = ObliviousHttpGateway::Create( GetHpkePrivateKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM), QuicheRandom::GetInstance()); std::string encrypted_request_1_bytes; ASSERT_TRUE( absl::HexStringToBytes("010020000100025f20b60306b61ad9ecad389acd752ca75c4" "e2969469809fe3d84aae137" "f73e4ccfe9ba71f12831fdce6c8202fbd38a84c5d8a73ac4c" "8ea6c10592594845f", &encrypted_request_1_bytes)); auto decrypted_request_1 = instance->DecryptObliviousHttpRequest(encrypted_request_1_bytes); ASSERT_TRUE(decrypted_request_1.ok()); std::string encrypted_request_2_bytes; ASSERT_TRUE( absl::HexStringToBytes("01002000010002285ebc2fcad72cc91b378050cac29a62fee" "a9cd97829335ee9fc87e672" "4fa13ff2efdff620423d54225d3099088e7b32a5165f805a5" "d922918865a0a447a", &encrypted_request_2_bytes)); auto decrypted_request_2 = instance->DecryptObliviousHttpRequest(encrypted_request_2_bytes); ASSERT_TRUE(decrypted_request_2.ok()); auto oblivious_request_context_1 = std::move(decrypted_request_1.value()).ReleaseContext(); auto encrypted_response_1 = instance->CreateObliviousHttpResponse( "test response 1", oblivious_request_context_1); ASSERT_TRUE(encrypted_response_1.ok()); ASSERT_FALSE(encrypted_response_1->EncapsulateAndSerialize().empty()); auto oblivious_request_context_2 = std::move(decrypted_request_2.value()).ReleaseContext(); auto encrypted_response_2 = instance->CreateObliviousHttpResponse( "test response 2", oblivious_request_context_2); ASSERT_TRUE(encrypted_response_2.ok()); ASSERT_FALSE(encrypted_response_2->EncapsulateAndSerialize().empty()); } TEST(ObliviousHttpGateway, TestWithMultipleThreads) { class TestQuicheThread : public QuicheThread { public: TestQuicheThread(const ObliviousHttpGateway& gateway_receiver, std::string request_payload, std::string response_payload) : QuicheThread("gateway_thread"), gateway_receiver_(gateway_receiver), request_payload_(request_payload), response_payload_(response_payload) {} protected: void Run() override { auto decrypted_request = gateway_receiver_.DecryptObliviousHttpRequest(request_payload_); ASSERT_TRUE(decrypted_request.ok()); ASSERT_FALSE(decrypted_request->GetPlaintextData().empty()); auto gateway_request_context = std::move(decrypted_request.value()).ReleaseContext(); auto encrypted_response = gateway_receiver_.CreateObliviousHttpResponse( response_payload_, gateway_request_context); ASSERT_TRUE(encrypted_response.ok()); ASSERT_FALSE(encrypted_response->EncapsulateAndSerialize().empty()); } private: const ObliviousHttpGateway& gateway_receiver_; std::string request_payload_, response_payload_; }; auto gateway_receiver = ObliviousHttpGateway::Create( GetHpkePrivateKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM), QuicheRandom::GetInstance()); std::string request_payload_1; ASSERT_TRUE( absl::HexStringToBytes("010020000100025f20b60306b61ad9ecad389acd752ca75c4" "e2969469809fe3d84aae137" "f73e4ccfe9ba71f12831fdce6c8202fbd38a84c5d8a73ac4c" "8ea6c10592594845f", &request_payload_1)); TestQuicheThread t1(*gateway_receiver, request_payload_1, "test response 1"); std::string request_payload_2; ASSERT_TRUE( absl::HexStringToBytes("01002000010002285ebc2fcad72cc91b378050cac29a62fee" "a9cd97829335ee9fc87e672" "4fa13ff2efdff620423d54225d3099088e7b32a5165f805a5" "d922918865a0a447a", &request_payload_2)); TestQuicheThread t2(*gateway_receiver, request_payload_2, "test response 2"); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/oblivious_http_gateway.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/oblivious_http_gateway_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1a6e151a-6a5c-41d9-bb6f-d22408852851
cpp
google/quiche
oblivious_http_request
quiche/oblivious_http/buffers/oblivious_http_request.cc
quiche/oblivious_http/buffers/oblivious_http_request_test.cc
#include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_crypto_logging.h" namespace quiche { ObliviousHttpRequest::Context::Context( bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key) : hpke_context_(std::move(hpke_context)), encapsulated_key_(std::move(encapsulated_key)) {} ObliviousHttpRequest::ObliviousHttpRequest( bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, std::string req_ciphertext, std::string req_plaintext) : oblivious_http_request_context_(absl::make_optional( Context(std::move(hpke_context), std::move(encapsulated_key)))), key_config_(ohttp_key_config), request_ciphertext_(std::move(req_ciphertext)), request_plaintext_(std::move(req_plaintext)) {} absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::CreateServerObliviousRequest( absl::string_view encrypted_data, const EVP_HPKE_KEY& gateway_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view request_label) { if (EVP_HPKE_KEY_kem(&gateway_key) == nullptr) { return absl::InvalidArgumentError( "Invalid input param. Failed to import gateway_key."); } bssl::UniquePtr<EVP_HPKE_CTX> gateway_ctx(EVP_HPKE_CTX_new()); if (gateway_ctx == nullptr) { return SslErrorAsStatus("Failed to initialize Gateway/Server's Context."); } QuicheDataReader reader(encrypted_data); auto is_hdr_ok = ohttp_key_config.ParseOhttpPayloadHeader(reader); if (!is_hdr_ok.ok()) { return is_hdr_ok; } size_t enc_key_len = EVP_HPKE_KEM_enc_len(EVP_HPKE_KEY_kem(&gateway_key)); absl::string_view enc_key_received; if (!reader.ReadStringPiece(&enc_key_received, enc_key_len)) { return absl::FailedPreconditionError(absl::StrCat( "Failed to extract encapsulation key of expected len=", enc_key_len, "from payload.")); } std::string info = ohttp_key_config.SerializeRecipientContextInfo(request_label); if (!EVP_HPKE_CTX_setup_recipient( gateway_ctx.get(), &gateway_key, ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(enc_key_received.data()), enc_key_received.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size())) { return SslErrorAsStatus("Failed to setup recipient context"); } absl::string_view ciphertext_received = reader.ReadRemainingPayload(); std::string decrypted(ciphertext_received.size(), '\0'); size_t decrypted_len; if (!EVP_HPKE_CTX_open( gateway_ctx.get(), reinterpret_cast<uint8_t*>(decrypted.data()), &decrypted_len, decrypted.size(), reinterpret_cast<const uint8_t*>(ciphertext_received.data()), ciphertext_received.size(), nullptr, 0)) { return SslErrorAsStatus("Failed to decrypt.", absl::StatusCode::kInvalidArgument); } decrypted.resize(decrypted_len); return ObliviousHttpRequest( std::move(gateway_ctx), std::string(enc_key_received), ohttp_key_config, std::string(ciphertext_received), std::move(decrypted)); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::CreateClientObliviousRequest( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view request_label) { return EncapsulateWithSeed(std::move(plaintext_payload), hpke_public_key, ohttp_key_config, "", request_label); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::CreateClientWithSeedForTesting( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view seed, absl::string_view request_label) { return ObliviousHttpRequest::EncapsulateWithSeed( std::move(plaintext_payload), hpke_public_key, ohttp_key_config, seed, request_label); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::EncapsulateWithSeed( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view seed, absl::string_view request_label) { if (plaintext_payload.empty() || hpke_public_key.empty()) { return absl::InvalidArgumentError("Invalid input."); } bssl::UniquePtr<EVP_HPKE_KEY> client_key(EVP_HPKE_KEY_new()); if (client_key == nullptr) { return SslErrorAsStatus("Failed to initialize HPKE Client Key."); } bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new()); if (client_ctx == nullptr) { return SslErrorAsStatus("Failed to initialize HPKE Client Context."); } std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0'); size_t enc_len; std::string info = ohttp_key_config.SerializeRecipientContextInfo(request_label); if (seed.empty()) { if (!EVP_HPKE_CTX_setup_sender( client_ctx.get(), reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), ohttp_key_config.GetHpkeKem(), ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(hpke_public_key.data()), hpke_public_key.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size())) { return SslErrorAsStatus( "Failed to setup HPKE context with given public key param " "hpke_public_key."); } } else { if (!EVP_HPKE_CTX_setup_sender_with_seed_for_testing( client_ctx.get(), reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), ohttp_key_config.GetHpkeKem(), ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(hpke_public_key.data()), hpke_public_key.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size(), reinterpret_cast<const uint8_t*>(seed.data()), seed.size())) { return SslErrorAsStatus( "Failed to setup HPKE context with given public key param " "hpke_public_key and seed."); } } encapsulated_key.resize(enc_len); std::string ciphertext( plaintext_payload.size() + EVP_HPKE_CTX_max_overhead(client_ctx.get()), '\0'); size_t ciphertext_len; if (!EVP_HPKE_CTX_seal( client_ctx.get(), reinterpret_cast<uint8_t*>(ciphertext.data()), &ciphertext_len, ciphertext.size(), reinterpret_cast<const uint8_t*>(plaintext_payload.data()), plaintext_payload.size(), nullptr, 0)) { return SslErrorAsStatus( "Failed to encrypt plaintext_payload with given public key param " "hpke_public_key."); } ciphertext.resize(ciphertext_len); if (encapsulated_key.empty() || ciphertext.empty()) { return absl::InternalError(absl::StrCat( "Failed to generate required data: ", (encapsulated_key.empty() ? "encapsulated key is empty" : ""), (ciphertext.empty() ? "encrypted data is empty" : ""), ".")); } return ObliviousHttpRequest( std::move(client_ctx), std::move(encapsulated_key), ohttp_key_config, std::move(ciphertext), std::move(plaintext_payload)); } std::string ObliviousHttpRequest::EncapsulateAndSerialize() const { if (!oblivious_http_request_context_.has_value()) { QUICHE_BUG(ohttp_encapsulate_after_context_extract) << "EncapsulateAndSerialize cannot be called after ReleaseContext()"; return ""; } return absl::StrCat(key_config_.SerializeOhttpPayloadHeader(), oblivious_http_request_context_->encapsulated_key_, request_ciphertext_); } absl::string_view ObliviousHttpRequest::GetPlaintextData() const { return request_plaintext_; } }
#include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include <stddef.h> #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/hkdf.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { namespace { const uint32_t kHeaderLength = ObliviousHttpHeaderKeyConfig::kHeaderLength; std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } std::string GetAlternativeHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef63"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } std::string GetSeed() { absl::string_view seed = "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736"; std::string seed_bytes; EXPECT_TRUE(absl::HexStringToBytes(seed, &seed_bytes)); return seed_bytes; } std::string GetSeededEncapsulatedKey() { absl::string_view encapsulated_key = "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431"; std::string encapsulated_key_bytes; EXPECT_TRUE( absl::HexStringToBytes(encapsulated_key, &encapsulated_key_bytes)); return encapsulated_key_bytes; } bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey( absl::string_view hpke_key, const ObliviousHttpHeaderKeyConfig &ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new()); EXPECT_NE(bssl_hpke_key, nullptr); EXPECT_TRUE(EVP_HPKE_KEY_init( bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t *>(hpke_key.data()), hpke_key.size())); return bssl_hpke_key; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return std::move(ohttp_key_config.value()); } } TEST(ObliviousHttpRequest, TestDecapsulateWithSpecAppendixAExample) { auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM); constexpr absl::string_view kX25519SecretKey = "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"; constexpr absl::string_view kEncapsulatedRequest = "010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c2" "08b4726374e469135906992e1268c594d2a10c695d858c40a026e7965e7d86b83dd440b2" "c0185204b4d63525"; std::string encapsulated_request_bytes; ASSERT_TRUE(absl::HexStringToBytes(kEncapsulatedRequest, &encapsulated_request_bytes)); std::string x25519_secret_key_bytes; ASSERT_TRUE( absl::HexStringToBytes(kX25519SecretKey, &x25519_secret_key_bytes)); auto instance = ObliviousHttpRequest::CreateServerObliviousRequest( encapsulated_request_bytes, *(ConstructHpkeKey(x25519_secret_key_bytes, ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(instance.ok()); auto decrypted = instance->GetPlaintextData(); constexpr absl::string_view kExpectedEphemeralPublicKey = "4b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c208b472"; std::string expected_ephemeral_public_key_bytes; ASSERT_TRUE(absl::HexStringToBytes(kExpectedEphemeralPublicKey, &expected_ephemeral_public_key_bytes)); auto oblivious_request_context = std::move(instance.value()).ReleaseContext(); EXPECT_EQ(oblivious_request_context.encapsulated_key_, expected_ephemeral_public_key_bytes); constexpr absl::string_view kExpectedBinaryHTTPMessage = "00034745540568747470730b6578616d706c652e636f6d012f"; std::string expected_binary_http_message_bytes; ASSERT_TRUE(absl::HexStringToBytes(kExpectedBinaryHTTPMessage, &expected_binary_http_message_bytes)); EXPECT_EQ(decrypted, expected_binary_http_message_bytes); } TEST(ObliviousHttpRequest, TestEncapsulatedRequestStructure) { uint8_t test_key_id = 7; uint16_t test_kem_id = EVP_HPKE_DHKEM_X25519_HKDF_SHA256; uint16_t test_kdf_id = EVP_HPKE_HKDF_SHA256; uint16_t test_aead_id = EVP_HPKE_AES_256_GCM; std::string plaintext = "test"; auto instance = ObliviousHttpRequest::CreateClientObliviousRequest( plaintext, GetHpkePublicKey(), GetOhttpKeyConfig(test_key_id, test_kem_id, test_kdf_id, test_aead_id)); ASSERT_TRUE(instance.ok()); auto payload_bytes = instance->EncapsulateAndSerialize(); EXPECT_GE(payload_bytes.size(), kHeaderLength); QuicheDataReader reader(payload_bytes); uint8_t key_id; EXPECT_TRUE(reader.ReadUInt8(&key_id)); EXPECT_EQ(key_id, test_key_id); uint16_t kem_id; EXPECT_TRUE(reader.ReadUInt16(&kem_id)); EXPECT_EQ(kem_id, test_kem_id); uint16_t kdf_id; EXPECT_TRUE(reader.ReadUInt16(&kdf_id)); EXPECT_EQ(kdf_id, test_kdf_id); uint16_t aead_id; EXPECT_TRUE(reader.ReadUInt16(&aead_id)); EXPECT_EQ(aead_id, test_aead_id); auto client_request_context = std::move(instance.value()).ReleaseContext(); auto client_encapsulated_key = client_request_context.encapsulated_key_; EXPECT_EQ(client_encapsulated_key.size(), X25519_PUBLIC_VALUE_LEN); auto enc_key_plus_ciphertext = payload_bytes.substr(kHeaderLength); auto packed_encapsulated_key = enc_key_plus_ciphertext.substr(0, X25519_PUBLIC_VALUE_LEN); EXPECT_EQ(packed_encapsulated_key, client_encapsulated_key); auto ciphertext = enc_key_plus_ciphertext.substr(X25519_PUBLIC_VALUE_LEN); EXPECT_GE(ciphertext.size(), plaintext.size()); } TEST(ObliviousHttpRequest, TestDeterministicSeededOhttpRequest) { auto ohttp_key_config = GetOhttpKeyConfig(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulated = ObliviousHttpRequest::CreateClientWithSeedForTesting( "test", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(encapsulated.ok()); auto encapsulated_request = encapsulated->EncapsulateAndSerialize(); auto ohttp_request_context = std::move(encapsulated.value()).ReleaseContext(); EXPECT_EQ(ohttp_request_context.encapsulated_key_, GetSeededEncapsulatedKey()); absl::string_view expected_encrypted_request = "9f37cfed07d0111ecd2c34f794671759bcbd922a"; std::string expected_encrypted_request_bytes; ASSERT_TRUE(absl::HexStringToBytes(expected_encrypted_request, &expected_encrypted_request_bytes)); EXPECT_NE(ohttp_request_context.hpke_context_, nullptr); size_t encapsulated_key_len = EVP_HPKE_KEM_enc_len( EVP_HPKE_CTX_kem(ohttp_request_context.hpke_context_.get())); int encrypted_payload_offset = kHeaderLength + encapsulated_key_len; EXPECT_EQ(encapsulated_request.substr(encrypted_payload_offset), expected_encrypted_request_bytes); } TEST(ObliviousHttpRequest, TestSeededEncapsulatedKeySamePlaintextsSameCiphertexts) { auto ohttp_key_config = GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto req_with_same_plaintext_1 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "same plaintext", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_same_plaintext_1.ok()); auto ciphertext_1 = req_with_same_plaintext_1->EncapsulateAndSerialize(); auto req_with_same_plaintext_2 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "same plaintext", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_same_plaintext_2.ok()); auto ciphertext_2 = req_with_same_plaintext_2->EncapsulateAndSerialize(); EXPECT_EQ(ciphertext_1, ciphertext_2); } TEST(ObliviousHttpRequest, TestSeededEncapsulatedKeyDifferentPlaintextsDifferentCiphertexts) { auto ohttp_key_config = GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto req_with_different_plaintext_1 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "different 1", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_different_plaintext_1.ok()); auto ciphertext_1 = req_with_different_plaintext_1->EncapsulateAndSerialize(); auto req_with_different_plaintext_2 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "different 2", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_different_plaintext_2.ok()); auto ciphertext_2 = req_with_different_plaintext_2->EncapsulateAndSerialize(); EXPECT_NE(ciphertext_1, ciphertext_2); } TEST(ObliviousHttpRequest, TestInvalidInputsOnClientSide) { auto ohttp_key_config = GetOhttpKeyConfig(30, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); EXPECT_EQ(ObliviousHttpRequest::CreateClientObliviousRequest( "", GetHpkePublicKey(), ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpRequest::CreateClientObliviousRequest( "some plaintext", "", ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpRequest, TestInvalidInputsOnServerSide) { auto ohttp_key_config = GetOhttpKeyConfig(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); EXPECT_EQ(ObliviousHttpRequest::CreateServerObliviousRequest( "", *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpRequest::CreateServerObliviousRequest( absl::StrCat(ohttp_key_config.SerializeOhttpPayloadHeader(), GetSeededEncapsulatedKey(), "9f37cfed07d0111ecd2c34f794671759bcbd922a"), {}, ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpRequest, EndToEndTestForRequest) { auto ohttp_key_config = GetOhttpKeyConfig(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate.ok()); auto oblivious_request = encapsulate->EncapsulateAndSerialize(); auto decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest( oblivious_request, *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(decapsulate.ok()); auto decrypted = decapsulate->GetPlaintextData(); EXPECT_EQ(decrypted, "test"); } TEST(ObliviousHttpRequest, EndToEndTestForRequestWithWrongKey) { auto ohttp_key_config = GetOhttpKeyConfig(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetAlternativeHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate.ok()); auto oblivious_request = encapsulate->EncapsulateAndSerialize(); auto decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest( oblivious_request, *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); EXPECT_EQ(decapsulate.status().code(), absl::StatusCode::kInvalidArgument); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/buffers/oblivious_http_request.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/buffers/oblivious_http_request_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
80934fd1-45fb-49c7-a4da-48fc1851b923
cpp
google/quiche
oblivious_http_response
quiche/oblivious_http/buffers/oblivious_http_response.cc
quiche/oblivious_http/buffers/oblivious_http_response_test.cc
#include "quiche/oblivious_http/buffers/oblivious_http_response.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/aead.h" #include "openssl/hkdf.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/quiche_crypto_logging.h" #include "quiche/common/quiche_random.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { namespace { void random(QuicheRandom* quiche_random, char* dest, size_t len) { if (quiche_random == nullptr) { quiche_random = QuicheRandom::GetInstance(); } quiche_random->RandBytes(dest, len); } } ObliviousHttpResponse::ObliviousHttpResponse(std::string encrypted_data, std::string resp_plaintext) : encrypted_data_(std::move(encrypted_data)), response_plaintext_(std::move(resp_plaintext)) {} absl::StatusOr<ObliviousHttpResponse> ObliviousHttpResponse::CreateClientObliviousResponse( std::string encrypted_data, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label) { if (oblivious_http_request_context.hpke_context_ == nullptr) { return absl::FailedPreconditionError( "HPKE context wasn't initialized before proceeding with this Response " "Decapsulation on Client-side."); } size_t expected_key_len = EVP_HPKE_KEM_enc_len( EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get())); if (oblivious_http_request_context.encapsulated_key_.size() != expected_key_len) { return absl::InvalidArgumentError(absl::StrCat( "Invalid len for encapsulated_key arg. Expected:", expected_key_len, " Actual:", oblivious_http_request_context.encapsulated_key_.size())); } if (encrypted_data.empty()) { return absl::InvalidArgumentError("Empty encrypted_data input param."); } absl::StatusOr<CommonAeadParamsResult> aead_params_st = GetCommonAeadParams(oblivious_http_request_context); if (!aead_params_st.ok()) { return aead_params_st.status(); } size_t secret_len = aead_params_st.value().secret_len; if (encrypted_data.size() < secret_len) { return absl::InvalidArgumentError( absl::StrCat("Invalid input response. Failed to parse required minimum " "expected_len=", secret_len, " bytes.")); } absl::string_view response_nonce = absl::string_view(encrypted_data).substr(0, secret_len); absl::string_view encrypted_response = absl::string_view(encrypted_data).substr(secret_len); auto common_ops_st = CommonOperationsToEncapDecap( response_nonce, oblivious_http_request_context, resp_label, aead_params_st.value().aead_key_len, aead_params_st.value().aead_nonce_len, aead_params_st.value().secret_len); if (!common_ops_st.ok()) { return common_ops_st.status(); } std::string decrypted(encrypted_response.size(), '\0'); size_t decrypted_len; if (!EVP_AEAD_CTX_open( common_ops_st.value().aead_ctx.get(), reinterpret_cast<uint8_t*>(decrypted.data()), &decrypted_len, decrypted.size(), reinterpret_cast<const uint8_t*>( common_ops_st.value().aead_nonce.data()), aead_params_st.value().aead_nonce_len, reinterpret_cast<const uint8_t*>(encrypted_response.data()), encrypted_response.size(), nullptr, 0)) { return SslErrorAsStatus( "Failed to decrypt the response with derived AEAD key and nonce."); } decrypted.resize(decrypted_len); ObliviousHttpResponse oblivious_response(std::move(encrypted_data), std::move(decrypted)); return oblivious_response; } absl::StatusOr<ObliviousHttpResponse> ObliviousHttpResponse::CreateServerObliviousResponse( std::string plaintext_payload, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view response_label, QuicheRandom* quiche_random) { if (oblivious_http_request_context.hpke_context_ == nullptr) { return absl::FailedPreconditionError( "HPKE context wasn't initialized before proceeding with this Response " "Encapsulation on Server-side."); } size_t expected_key_len = EVP_HPKE_KEM_enc_len( EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get())); if (oblivious_http_request_context.encapsulated_key_.size() != expected_key_len) { return absl::InvalidArgumentError(absl::StrCat( "Invalid len for encapsulated_key arg. Expected:", expected_key_len, " Actual:", oblivious_http_request_context.encapsulated_key_.size())); } if (plaintext_payload.empty()) { return absl::InvalidArgumentError("Empty plaintext_payload input param."); } absl::StatusOr<CommonAeadParamsResult> aead_params_st = GetCommonAeadParams(oblivious_http_request_context); if (!aead_params_st.ok()) { return aead_params_st.status(); } const size_t nonce_size = aead_params_st->secret_len; const size_t max_encrypted_data_size = nonce_size + plaintext_payload.size() + EVP_AEAD_max_overhead(EVP_HPKE_AEAD_aead(EVP_HPKE_CTX_aead( oblivious_http_request_context.hpke_context_.get()))); std::string encrypted_data(max_encrypted_data_size, '\0'); random(quiche_random, encrypted_data.data(), nonce_size); absl::string_view response_nonce = absl::string_view(encrypted_data).substr(0, nonce_size); auto common_ops_st = CommonOperationsToEncapDecap( response_nonce, oblivious_http_request_context, response_label, aead_params_st.value().aead_key_len, aead_params_st.value().aead_nonce_len, aead_params_st.value().secret_len); if (!common_ops_st.ok()) { return common_ops_st.status(); } size_t ciphertext_len; if (!EVP_AEAD_CTX_seal( common_ops_st.value().aead_ctx.get(), reinterpret_cast<uint8_t*>(encrypted_data.data() + nonce_size), &ciphertext_len, encrypted_data.size() - nonce_size, reinterpret_cast<const uint8_t*>( common_ops_st.value().aead_nonce.data()), aead_params_st.value().aead_nonce_len, reinterpret_cast<const uint8_t*>(plaintext_payload.data()), plaintext_payload.size(), nullptr, 0)) { return SslErrorAsStatus( "Failed to encrypt the payload with derived AEAD key."); } encrypted_data.resize(nonce_size + ciphertext_len); if (nonce_size == 0 || ciphertext_len == 0) { return absl::InternalError(absl::StrCat( "ObliviousHttpResponse Object wasn't initialized with required fields.", (nonce_size == 0 ? "Generated nonce is empty." : ""), (ciphertext_len == 0 ? "Generated Encrypted payload is empty." : ""))); } ObliviousHttpResponse oblivious_response(std::move(encrypted_data), std::move(plaintext_payload)); return oblivious_response; } const std::string& ObliviousHttpResponse::EncapsulateAndSerialize() const { return encrypted_data_; } const std::string& ObliviousHttpResponse::GetPlaintextData() const { return response_plaintext_; } absl::StatusOr<ObliviousHttpResponse::CommonAeadParamsResult> ObliviousHttpResponse::GetCommonAeadParams( ObliviousHttpRequest::Context& oblivious_http_request_context) { const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead( EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get())); if (evp_hpke_aead == nullptr) { return absl::FailedPreconditionError( "Key Configuration not supported by HPKE AEADs. Check your key " "config."); } const size_t aead_key_len = EVP_AEAD_key_length(evp_hpke_aead); const size_t aead_nonce_len = EVP_AEAD_nonce_length(evp_hpke_aead); const size_t secret_len = std::max(aead_key_len, aead_nonce_len); CommonAeadParamsResult result{evp_hpke_aead, aead_key_len, aead_nonce_len, secret_len}; return result; } absl::StatusOr<ObliviousHttpResponse::CommonOperationsResult> ObliviousHttpResponse::CommonOperationsToEncapDecap( absl::string_view response_nonce, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label, const size_t aead_key_len, const size_t aead_nonce_len, const size_t secret_len) { if (response_nonce.empty()) { return absl::InvalidArgumentError("Invalid input params."); } std::string secret(secret_len, '\0'); if (!EVP_HPKE_CTX_export(oblivious_http_request_context.hpke_context_.get(), reinterpret_cast<uint8_t*>(secret.data()), secret.size(), reinterpret_cast<const uint8_t*>(resp_label.data()), resp_label.size())) { return SslErrorAsStatus("Failed to export secret."); } std::string salt = absl::StrCat( oblivious_http_request_context.encapsulated_key_, response_nonce); std::string pseudorandom_key(EVP_MAX_MD_SIZE, '\0'); size_t prk_len; auto evp_md = EVP_HPKE_KDF_hkdf_md( EVP_HPKE_CTX_kdf(oblivious_http_request_context.hpke_context_.get())); if (evp_md == nullptr) { QUICHE_BUG(Invalid Key Configuration : Unsupported BoringSSL HPKE KDFs) << "Update KeyConfig to support only BoringSSL HKDFs."; return absl::FailedPreconditionError( "Key Configuration not supported by BoringSSL HPKE KDFs. Check your " "Key " "Config."); } if (!HKDF_extract( reinterpret_cast<uint8_t*>(pseudorandom_key.data()), &prk_len, evp_md, reinterpret_cast<const uint8_t*>(secret.data()), secret_len, reinterpret_cast<const uint8_t*>(salt.data()), salt.size())) { return SslErrorAsStatus( "Failed to derive pesudorandom key from salt and secret."); } pseudorandom_key.resize(prk_len); std::string aead_key(aead_key_len, '\0'); absl::string_view hkdf_info = ObliviousHttpHeaderKeyConfig::kKeyHkdfInfo; if (!HKDF_expand(reinterpret_cast<uint8_t*>(aead_key.data()), aead_key_len, evp_md, reinterpret_cast<const uint8_t*>(pseudorandom_key.data()), prk_len, reinterpret_cast<const uint8_t*>(hkdf_info.data()), hkdf_info.size())) { return SslErrorAsStatus( "Failed to expand AEAD key using pseudorandom key(prk)."); } std::string aead_nonce(aead_nonce_len, '\0'); hkdf_info = ObliviousHttpHeaderKeyConfig::kNonceHkdfInfo; if (!HKDF_expand(reinterpret_cast<uint8_t*>(aead_nonce.data()), aead_nonce_len, evp_md, reinterpret_cast<const uint8_t*>(pseudorandom_key.data()), prk_len, reinterpret_cast<const uint8_t*>(hkdf_info.data()), hkdf_info.size())) { return SslErrorAsStatus( "Failed to expand AEAD nonce using pseudorandom key(prk)."); } const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead( EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get())); if (evp_hpke_aead == nullptr) { return absl::FailedPreconditionError( "Key Configuration not supported by HPKE AEADs. Check your key " "config."); } bssl::UniquePtr<EVP_AEAD_CTX> aead_ctx(EVP_AEAD_CTX_new( evp_hpke_aead, reinterpret_cast<const uint8_t*>(aead_key.data()), aead_key.size(), 0)); if (aead_ctx == nullptr) { return SslErrorAsStatus("Failed to initialize AEAD context."); } if (!EVP_AEAD_CTX_init(aead_ctx.get(), evp_hpke_aead, reinterpret_cast<const uint8_t*>(aead_key.data()), aead_key.size(), 0, nullptr)) { return SslErrorAsStatus( "Failed to initialize AEAD context with derived key."); } CommonOperationsResult result{std::move(aead_ctx), std::move(aead_nonce)}; return result; } }
#include "quiche/oblivious_http/buffers/oblivious_http_response.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { namespace { std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } std::string GetSeed() { absl::string_view seed = "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736"; std::string seed_bytes; EXPECT_TRUE(absl::HexStringToBytes(seed, &seed_bytes)); return seed_bytes; } std::string GetSeededEncapsulatedKey() { absl::string_view encapsulated_key = "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431"; std::string encapsulated_key_bytes; EXPECT_TRUE( absl::HexStringToBytes(encapsulated_key, &encapsulated_key_bytes)); return encapsulated_key_bytes; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return ohttp_key_config.value(); } bssl::UniquePtr<EVP_HPKE_CTX> GetSeededClientContext(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new()); std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0'); size_t enc_len; std::string info = GetOhttpKeyConfig(key_id, kem_id, kdf_id, aead_id) .SerializeRecipientContextInfo(); EXPECT_TRUE(EVP_HPKE_CTX_setup_sender_with_seed_for_testing( client_ctx.get(), reinterpret_cast<uint8_t *>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), EVP_hpke_x25519_hkdf_sha256(), EVP_hpke_hkdf_sha256(), EVP_hpke_aes_256_gcm(), reinterpret_cast<const uint8_t *>(GetHpkePublicKey().data()), GetHpkePublicKey().size(), reinterpret_cast<const uint8_t *>(info.data()), info.size(), reinterpret_cast<const uint8_t *>(GetSeed().data()), GetSeed().size())); encapsulated_key.resize(enc_len); EXPECT_EQ(encapsulated_key, GetSeededEncapsulatedKey()); return client_ctx; } bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey( absl::string_view hpke_key, const ObliviousHttpHeaderKeyConfig &ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new()); EXPECT_NE(bssl_hpke_key, nullptr); EXPECT_TRUE(EVP_HPKE_KEY_init( bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t *>(hpke_key.data()), hpke_key.size())); return bssl_hpke_key; } ObliviousHttpRequest SetUpObliviousHttpContext(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id, std::string plaintext) { auto ohttp_key_config = GetOhttpKeyConfig(key_id, kem_id, kdf_id, aead_id); auto client_request_encapsulate = ObliviousHttpRequest::CreateClientWithSeedForTesting( std::move(plaintext), GetHpkePublicKey(), ohttp_key_config, GetSeed()); EXPECT_TRUE(client_request_encapsulate.ok()); auto oblivious_request = client_request_encapsulate->EncapsulateAndSerialize(); auto server_request_decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest( oblivious_request, *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); EXPECT_TRUE(server_request_decapsulate.ok()); return std::move(server_request_decapsulate.value()); } class TestQuicheRandom : public QuicheRandom { public: TestQuicheRandom(char seed) : seed_(seed) {} ~TestQuicheRandom() override {} void RandBytes(void *data, size_t len) override { memset(data, seed_, len); } uint64_t RandUint64() override { uint64_t random_int; memset(&random_int, seed_, sizeof(random_int)); return random_int; } void InsecureRandBytes(void *data, size_t len) override { return RandBytes(data, len); } uint64_t InsecureRandUint64() override { return RandUint64(); } private: char seed_; }; size_t GetResponseNonceLength(const EVP_HPKE_CTX &hpke_context) { EXPECT_NE(&hpke_context, nullptr); const EVP_AEAD *evp_hpke_aead = EVP_HPKE_AEAD_aead(EVP_HPKE_CTX_aead(&hpke_context)); EXPECT_NE(evp_hpke_aead, nullptr); const size_t aead_key_len = EVP_AEAD_key_length(evp_hpke_aead); const size_t aead_nonce_len = EVP_AEAD_nonce_length(evp_hpke_aead); const size_t secret_len = std::max(aead_key_len, aead_nonce_len); return secret_len; } TEST(ObliviousHttpResponse, TestDecapsulateReceivedResponse) { absl::string_view encrypted_response = "39d5b03c02c97e216df444e4681007105974d4df1585aae05e7b53f3ccdb55d51f711d48" "eeefbc1a555d6d928e35df33fd23c23846fa7b083e30692f7b"; std::string encrypted_response_bytes; ASSERT_TRUE( absl::HexStringToBytes(encrypted_response, &encrypted_response_bytes)); auto oblivious_context = SetUpObliviousHttpContext(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM, "test") .ReleaseContext(); auto decapsulated = ObliviousHttpResponse::CreateClientObliviousResponse( std::move(encrypted_response_bytes), oblivious_context); EXPECT_TRUE(decapsulated.ok()); auto decrypted = decapsulated->GetPlaintextData(); EXPECT_EQ(decrypted, "test response"); } } TEST(ObliviousHttpResponse, EndToEndTestForResponse) { auto oblivious_ctx = ObliviousHttpRequest::Context( GetSeededClientContext(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM), GetSeededEncapsulatedKey()); auto server_response_encapsulate = ObliviousHttpResponse::CreateServerObliviousResponse("test response", oblivious_ctx); EXPECT_TRUE(server_response_encapsulate.ok()); auto oblivious_response = server_response_encapsulate->EncapsulateAndSerialize(); auto client_response_encapsulate = ObliviousHttpResponse::CreateClientObliviousResponse(oblivious_response, oblivious_ctx); auto decrypted = client_response_encapsulate->GetPlaintextData(); EXPECT_EQ(decrypted, "test response"); } TEST(ObliviousHttpResponse, TestEncapsulateWithQuicheRandom) { auto random = TestQuicheRandom('z'); auto server_seeded_request = SetUpObliviousHttpContext( 6, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM, "test"); auto server_request_context = std::move(server_seeded_request).ReleaseContext(); auto server_response_encapsulate = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", server_request_context, ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel, &random); EXPECT_TRUE(server_response_encapsulate.ok()); std::string response_nonce = server_response_encapsulate->EncapsulateAndSerialize().substr( 0, GetResponseNonceLength(*(server_request_context.hpke_context_))); EXPECT_EQ(response_nonce, std::string( GetResponseNonceLength(*(server_request_context.hpke_context_)), 'z')); absl::string_view expected_encrypted_response = "2a3271ac4e6a501f51d0264d3dd7d0bc8a06973b58e89c26d6dac06144"; std::string expected_encrypted_response_bytes; ASSERT_TRUE(absl::HexStringToBytes(expected_encrypted_response, &expected_encrypted_response_bytes)); EXPECT_EQ( server_response_encapsulate->EncapsulateAndSerialize().substr( GetResponseNonceLength(*(server_request_context.hpke_context_))), expected_encrypted_response_bytes); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/buffers/oblivious_http_response.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/buffers/oblivious_http_response_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d79cc799-2095-4818-baf9-bbf5f8ee9e8a
cpp
google/quiche
oblivious_http_header_key_config
quiche/oblivious_http/common/oblivious_http_header_key_config.cc
quiche/oblivious_http/common/oblivious_http_header_key_config_test.cc
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" #include <algorithm> #include <cstdint> #include <functional> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_endian.h" namespace quiche { namespace { constexpr size_t kSizeOfHpkeKemId = 2; constexpr size_t kSizeOfSymmetricAlgorithmHpkeKdfId = 2; constexpr size_t kSizeOfSymmetricAlgorithmHpkeAeadId = 2; absl::StatusOr<const EVP_HPKE_KEM*> CheckKemId(uint16_t kem_id) { switch (kem_id) { case EVP_HPKE_DHKEM_X25519_HKDF_SHA256: return EVP_hpke_x25519_hkdf_sha256(); default: return absl::UnimplementedError("No support for this KEM ID."); } } absl::StatusOr<const EVP_HPKE_KDF*> CheckKdfId(uint16_t kdf_id) { switch (kdf_id) { case EVP_HPKE_HKDF_SHA256: return EVP_hpke_hkdf_sha256(); default: return absl::UnimplementedError("No support for this KDF ID."); } } absl::StatusOr<const EVP_HPKE_AEAD*> CheckAeadId(uint16_t aead_id) { switch (aead_id) { case EVP_HPKE_AES_128_GCM: return EVP_hpke_aes_128_gcm(); case EVP_HPKE_AES_256_GCM: return EVP_hpke_aes_256_gcm(); case EVP_HPKE_CHACHA20_POLY1305: return EVP_hpke_chacha20_poly1305(); default: return absl::UnimplementedError("No support for this AEAD ID."); } } } ObliviousHttpHeaderKeyConfig::ObliviousHttpHeaderKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) : key_id_(key_id), kem_id_(kem_id), kdf_id_(kdf_id), aead_id_(aead_id) {} absl::StatusOr<ObliviousHttpHeaderKeyConfig> ObliviousHttpHeaderKeyConfig::Create(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { ObliviousHttpHeaderKeyConfig instance(key_id, kem_id, kdf_id, aead_id); auto is_config_ok = instance.ValidateKeyConfig(); if (!is_config_ok.ok()) { return is_config_ok; } return instance; } absl::Status ObliviousHttpHeaderKeyConfig::ValidateKeyConfig() const { auto supported_kem = CheckKemId(kem_id_); if (!supported_kem.ok()) { return absl::InvalidArgumentError( absl::StrCat("Unsupported KEM ID:", kem_id_)); } auto supported_kdf = CheckKdfId(kdf_id_); if (!supported_kdf.ok()) { return absl::InvalidArgumentError( absl::StrCat("Unsupported KDF ID:", kdf_id_)); } auto supported_aead = CheckAeadId(aead_id_); if (!supported_aead.ok()) { return absl::InvalidArgumentError( absl::StrCat("Unsupported AEAD ID:", aead_id_)); } return absl::OkStatus(); } const EVP_HPKE_KEM* ObliviousHttpHeaderKeyConfig::GetHpkeKem() const { auto kem = CheckKemId(kem_id_); QUICHE_CHECK_OK(kem.status()); return kem.value(); } const EVP_HPKE_KDF* ObliviousHttpHeaderKeyConfig::GetHpkeKdf() const { auto kdf = CheckKdfId(kdf_id_); QUICHE_CHECK_OK(kdf.status()); return kdf.value(); } const EVP_HPKE_AEAD* ObliviousHttpHeaderKeyConfig::GetHpkeAead() const { auto aead = CheckAeadId(aead_id_); QUICHE_CHECK_OK(aead.status()); return aead.value(); } std::string ObliviousHttpHeaderKeyConfig::SerializeRecipientContextInfo( absl::string_view request_label) const { uint8_t zero_byte = 0x00; int buf_len = request_label.size() + kHeaderLength + sizeof(zero_byte); std::string info(buf_len, '\0'); QuicheDataWriter writer(info.size(), info.data()); QUICHE_CHECK(writer.WriteStringPiece(request_label)); QUICHE_CHECK(writer.WriteUInt8(zero_byte)); QUICHE_CHECK(writer.WriteUInt8(key_id_)); QUICHE_CHECK(writer.WriteUInt16(kem_id_)); QUICHE_CHECK(writer.WriteUInt16(kdf_id_)); QUICHE_CHECK(writer.WriteUInt16(aead_id_)); return info; } absl::Status ObliviousHttpHeaderKeyConfig::ParseOhttpPayloadHeader( absl::string_view payload_bytes) const { if (payload_bytes.empty()) { return absl::InvalidArgumentError("Empty request payload."); } QuicheDataReader reader(payload_bytes); return ParseOhttpPayloadHeader(reader); } absl::Status ObliviousHttpHeaderKeyConfig::ParseOhttpPayloadHeader( QuicheDataReader& reader) const { uint8_t key_id; if (!reader.ReadUInt8(&key_id)) { return absl::InvalidArgumentError("Failed to read key_id from header."); } if (key_id != key_id_) { return absl::InvalidArgumentError( absl::StrCat("KeyID in request:", static_cast<uint16_t>(key_id), " doesn't match with server's public key " "configuration KeyID:", static_cast<uint16_t>(key_id_))); } uint16_t kem_id; if (!reader.ReadUInt16(&kem_id)) { return absl::InvalidArgumentError("Failed to read kem_id from header."); } if (kem_id != kem_id_) { return absl::InvalidArgumentError( absl::StrCat("Received Invalid kemID:", kem_id, " Expected:", kem_id_)); } uint16_t kdf_id; if (!reader.ReadUInt16(&kdf_id)) { return absl::InvalidArgumentError("Failed to read kdf_id from header."); } if (kdf_id != kdf_id_) { return absl::InvalidArgumentError( absl::StrCat("Received Invalid kdfID:", kdf_id, " Expected:", kdf_id_)); } uint16_t aead_id; if (!reader.ReadUInt16(&aead_id)) { return absl::InvalidArgumentError("Failed to read aead_id from header."); } if (aead_id != aead_id_) { return absl::InvalidArgumentError(absl::StrCat( "Received Invalid aeadID:", aead_id, " Expected:", aead_id_)); } return absl::OkStatus(); } absl::StatusOr<uint8_t> ObliviousHttpHeaderKeyConfig::ParseKeyIdFromObliviousHttpRequestPayload( absl::string_view payload_bytes) { if (payload_bytes.empty()) { return absl::InvalidArgumentError("Empty request payload."); } QuicheDataReader reader(payload_bytes); uint8_t key_id; if (!reader.ReadUInt8(&key_id)) { return absl::InvalidArgumentError("Failed to read key_id from payload."); } return key_id; } std::string ObliviousHttpHeaderKeyConfig::SerializeOhttpPayloadHeader() const { int buf_len = sizeof(key_id_) + sizeof(kem_id_) + sizeof(kdf_id_) + sizeof(aead_id_); std::string hdr(buf_len, '\0'); QuicheDataWriter writer(hdr.size(), hdr.data()); QUICHE_CHECK(writer.WriteUInt8(key_id_)); QUICHE_CHECK(writer.WriteUInt16(kem_id_)); QUICHE_CHECK(writer.WriteUInt16(kdf_id_)); QUICHE_CHECK(writer.WriteUInt16(aead_id_)); return hdr; } namespace { absl::StatusOr<uint16_t> KeyLength(uint16_t kem_id) { auto supported_kem = CheckKemId(kem_id); if (!supported_kem.ok()) { return absl::InvalidArgumentError(absl::StrCat( "Unsupported KEM ID:", kem_id, ". public key length is unknown.")); } return EVP_HPKE_KEM_public_key_len(supported_kem.value()); } absl::StatusOr<std::string> SerializeOhttpKeyWithPublicKey( uint8_t key_id, absl::string_view public_key, const std::vector<ObliviousHttpHeaderKeyConfig>& ohttp_configs) { auto ohttp_config = ohttp_configs[0]; static_assert(sizeof(ohttp_config.GetHpkeKemId()) == kSizeOfHpkeKemId && sizeof(ohttp_config.GetHpkeKdfId()) == kSizeOfSymmetricAlgorithmHpkeKdfId && sizeof(ohttp_config.GetHpkeAeadId()) == kSizeOfSymmetricAlgorithmHpkeAeadId, "Size of HPKE IDs should match RFC specification."); uint16_t symmetric_algs_length = ohttp_configs.size() * (kSizeOfSymmetricAlgorithmHpkeKdfId + kSizeOfSymmetricAlgorithmHpkeAeadId); int buf_len = sizeof(key_id) + kSizeOfHpkeKemId + public_key.size() + sizeof(symmetric_algs_length) + symmetric_algs_length; std::string ohttp_key_configuration(buf_len, '\0'); QuicheDataWriter writer(ohttp_key_configuration.size(), ohttp_key_configuration.data()); if (!writer.WriteUInt8(key_id)) { return absl::InternalError("Failed to serialize OHTTP key.[key_id]"); } if (!writer.WriteUInt16(ohttp_config.GetHpkeKemId())) { return absl::InternalError( "Failed to serialize OHTTP key.[kem_id]"); } if (!writer.WriteStringPiece(public_key)) { return absl::InternalError( "Failed to serialize OHTTP key.[public_key]"); } if (!writer.WriteUInt16(symmetric_algs_length)) { return absl::InternalError( "Failed to serialize OHTTP key.[symmetric_algs_length]"); } for (const auto& item : ohttp_configs) { if (item.GetHpkeKemId() != ohttp_config.GetHpkeKemId()) { QUICHE_BUG(ohttp_key_configs_builder_parser) << "ObliviousHttpKeyConfigs object cannot hold ConfigMap of " "different KEM IDs:[ " << item.GetHpkeKemId() << "," << ohttp_config.GetHpkeKemId() << " ]for a given key_id:" << static_cast<uint16_t>(key_id); } if (!writer.WriteUInt16(item.GetHpkeKdfId())) { return absl::InternalError( "Failed to serialize OHTTP key.[kdf_id]"); } if (!writer.WriteUInt16(item.GetHpkeAeadId())) { return absl::InternalError( "Failed to serialize OHTTP key.[aead_id]"); } } QUICHE_DCHECK_EQ(writer.remaining(), 0u); return ohttp_key_configuration; } std::string GetDebugStringForFailedKeyConfig( const ObliviousHttpKeyConfigs::OhttpKeyConfig& failed_key_config) { std::string debug_string = "[ "; absl::StrAppend(&debug_string, "key_id:", static_cast<uint16_t>(failed_key_config.key_id), " , kem_id:", failed_key_config.kem_id, ". Printing HEX formatted public_key:", absl::BytesToHexString(failed_key_config.public_key)); absl::StrAppend(&debug_string, ", symmetric_algorithms: { "); for (const auto& symmetric_config : failed_key_config.symmetric_algorithms) { absl::StrAppend(&debug_string, "{kdf_id: ", symmetric_config.kdf_id, ", aead_id:", symmetric_config.aead_id, " }"); } absl::StrAppend(&debug_string, " } ]"); return debug_string; } absl::Status StoreKeyConfigIfValid( ObliviousHttpKeyConfigs::OhttpKeyConfig key_config, absl::btree_map<uint8_t, std::vector<ObliviousHttpHeaderKeyConfig>, std::greater<uint8_t>>& configs, absl::flat_hash_map<uint8_t, std::string>& keys) { if (!CheckKemId(key_config.kem_id).ok() || key_config.public_key.size() != KeyLength(key_config.kem_id).value()) { QUICHE_LOG(ERROR) << "Failed to process: " << GetDebugStringForFailedKeyConfig(key_config); return absl::InvalidArgumentError( absl::StrCat("Invalid key_config! [KEM ID:", key_config.kem_id, "]")); } for (const auto& symmetric_config : key_config.symmetric_algorithms) { if (!CheckKdfId(symmetric_config.kdf_id).ok() || !CheckAeadId(symmetric_config.aead_id).ok()) { QUICHE_LOG(ERROR) << "Failed to process: " << GetDebugStringForFailedKeyConfig(key_config); return absl::InvalidArgumentError( absl::StrCat("Invalid key_config! [KDF ID:", symmetric_config.kdf_id, ", AEAD ID:", symmetric_config.aead_id, "]")); } auto ohttp_config = ObliviousHttpHeaderKeyConfig::Create( key_config.key_id, key_config.kem_id, symmetric_config.kdf_id, symmetric_config.aead_id); if (ohttp_config.ok()) { configs[key_config.key_id].emplace_back(std::move(ohttp_config.value())); } } keys.emplace(key_config.key_id, std::move(key_config.public_key)); return absl::OkStatus(); } } absl::StatusOr<ObliviousHttpKeyConfigs> ObliviousHttpKeyConfigs::ParseConcatenatedKeys(absl::string_view key_config) { ConfigMap configs; PublicKeyMap keys; auto reader = QuicheDataReader(key_config); while (!reader.IsDoneReading()) { absl::Status status = ReadSingleKeyConfig(reader, configs, keys); if (!status.ok()) return status; } return ObliviousHttpKeyConfigs(std::move(configs), std::move(keys)); } absl::StatusOr<ObliviousHttpKeyConfigs> ObliviousHttpKeyConfigs::Create( absl::flat_hash_set<ObliviousHttpKeyConfigs::OhttpKeyConfig> ohttp_key_configs) { if (ohttp_key_configs.empty()) { return absl::InvalidArgumentError("Empty input."); } ConfigMap configs_map; PublicKeyMap keys_map; for (auto& ohttp_key_config : ohttp_key_configs) { auto result = StoreKeyConfigIfValid(std::move(ohttp_key_config), configs_map, keys_map); if (!result.ok()) { return result; } } auto oblivious_configs = ObliviousHttpKeyConfigs(std::move(configs_map), std::move(keys_map)); return oblivious_configs; } absl::StatusOr<ObliviousHttpKeyConfigs> ObliviousHttpKeyConfigs::Create( const ObliviousHttpHeaderKeyConfig& single_key_config, absl::string_view public_key) { if (public_key.empty()) { return absl::InvalidArgumentError("Empty input."); } if (auto key_length = KeyLength(single_key_config.GetHpkeKemId()); public_key.size() != key_length.value()) { return absl::InvalidArgumentError(absl::StrCat( "Invalid key. Key size mismatch. Expected:", key_length.value(), " Actual:", public_key.size())); } ConfigMap configs; PublicKeyMap keys; uint8_t key_id = single_key_config.GetKeyId(); keys.emplace(key_id, public_key); configs[key_id].emplace_back(std::move(single_key_config)); return ObliviousHttpKeyConfigs(std::move(configs), std::move(keys)); } absl::StatusOr<std::string> ObliviousHttpKeyConfigs::GenerateConcatenatedKeys() const { std::string concatenated_keys; for (const auto& [key_id, ohttp_configs] : configs_) { auto key = public_keys_.find(key_id); if (key == public_keys_.end()) { return absl::InternalError( "Failed to serialize. No public key found for key_id"); } auto serialized = SerializeOhttpKeyWithPublicKey(key_id, key->second, ohttp_configs); if (!serialized.ok()) { return absl::InternalError("Failed to serialize OHTTP key configs."); } absl::StrAppend(&concatenated_keys, serialized.value()); } return concatenated_keys; } ObliviousHttpHeaderKeyConfig ObliviousHttpKeyConfigs::PreferredConfig() const { return configs_.begin()->second.front(); } absl::StatusOr<absl::string_view> ObliviousHttpKeyConfigs::GetPublicKeyForId( uint8_t key_id) const { auto key = public_keys_.find(key_id); if (key == public_keys_.end()) { return absl::NotFoundError("No public key found for key_id"); } return key->second; } absl::Status ObliviousHttpKeyConfigs::ReadSingleKeyConfig( QuicheDataReader& reader, ConfigMap& configs, PublicKeyMap& keys) { uint8_t key_id; uint16_t kem_id; if (!reader.ReadUInt8(&key_id) || !reader.ReadUInt16(&kem_id)) { return absl::InvalidArgumentError("Invalid key_config!"); } auto maybe_key_length = KeyLength(kem_id); if (!maybe_key_length.ok()) { return maybe_key_length.status(); } const int key_length = maybe_key_length.value(); std::string key_str(key_length, '\0'); if (!reader.ReadBytes(key_str.data(), key_length)) { return absl::InvalidArgumentError("Invalid key_config!"); } if (!keys.insert({key_id, std::move(key_str)}).second) { return absl::InvalidArgumentError("Duplicate key_id's in key_config!"); } absl::string_view alg_bytes; if (!reader.ReadStringPiece16(&alg_bytes)) { return absl::InvalidArgumentError("Invalid key_config!"); } QuicheDataReader sub_reader(alg_bytes); while (!sub_reader.IsDoneReading()) { uint16_t kdf_id; uint16_t aead_id; if (!sub_reader.ReadUInt16(&kdf_id) || !sub_reader.ReadUInt16(&aead_id)) { return absl::InvalidArgumentError("Invalid key_config!"); } absl::StatusOr<ObliviousHttpHeaderKeyConfig> maybe_cfg = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); if (!maybe_cfg.ok()) { return maybe_cfg.status(); } configs[key_id].emplace_back(std::move(maybe_cfg.value())); } return absl::OkStatus(); } }
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" #include <cstdint> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { namespace { using ::testing::AllOf; using ::testing::Property; using ::testing::StrEq; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; std::string BuildHeader(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { int buf_len = sizeof(key_id) + sizeof(kem_id) + sizeof(kdf_id) + sizeof(aead_id); std::string hdr(buf_len, '\0'); QuicheDataWriter writer(hdr.size(), hdr.data()); EXPECT_TRUE(writer.WriteUInt8(key_id)); EXPECT_TRUE(writer.WriteUInt16(kem_id)); EXPECT_TRUE(writer.WriteUInt16(kdf_id)); EXPECT_TRUE(writer.WriteUInt16(aead_id)); return hdr; } std::string GetSerializedKeyConfig( ObliviousHttpKeyConfigs::OhttpKeyConfig& key_config) { uint16_t symmetric_algs_length = key_config.symmetric_algorithms.size() * (sizeof(key_config.symmetric_algorithms.cbegin()->kdf_id) + sizeof(key_config.symmetric_algorithms.cbegin()->aead_id)); int buf_len = sizeof(key_config.key_id) + sizeof(key_config.kem_id) + key_config.public_key.size() + sizeof(symmetric_algs_length) + symmetric_algs_length; std::string ohttp_key(buf_len, '\0'); QuicheDataWriter writer(ohttp_key.size(), ohttp_key.data()); EXPECT_TRUE(writer.WriteUInt8(key_config.key_id)); EXPECT_TRUE(writer.WriteUInt16(key_config.kem_id)); EXPECT_TRUE(writer.WriteStringPiece(key_config.public_key)); EXPECT_TRUE(writer.WriteUInt16(symmetric_algs_length)); for (const auto& symmetric_alg : key_config.symmetric_algorithms) { EXPECT_TRUE(writer.WriteUInt16(symmetric_alg.kdf_id)); EXPECT_TRUE(writer.WriteUInt16(symmetric_alg.aead_id)); } return ohttp_key; } TEST(ObliviousHttpHeaderKeyConfig, TestSerializeRecipientContextInfo) { uint8_t key_id = 3; uint16_t kem_id = EVP_HPKE_DHKEM_X25519_HKDF_SHA256; uint16_t kdf_id = EVP_HPKE_HKDF_SHA256; uint16_t aead_id = EVP_HPKE_AES_256_GCM; absl::string_view ohttp_req_label = "message/bhttp request"; std::string expected(ohttp_req_label); uint8_t zero_byte = 0x00; int buf_len = ohttp_req_label.size() + sizeof(zero_byte) + sizeof(key_id) + sizeof(kem_id) + sizeof(kdf_id) + sizeof(aead_id); expected.reserve(buf_len); expected.push_back(zero_byte); std::string ohttp_cfg(BuildHeader(key_id, kem_id, kdf_id, aead_id)); expected.insert(expected.end(), ohttp_cfg.begin(), ohttp_cfg.end()); auto instance = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); ASSERT_TRUE(instance.ok()); EXPECT_EQ(instance.value().SerializeRecipientContextInfo(), expected); } TEST(ObliviousHttpHeaderKeyConfig, TestValidKeyConfig) { auto valid_key_config = ObliviousHttpHeaderKeyConfig::Create( 2, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(valid_key_config.ok()); } TEST(ObliviousHttpHeaderKeyConfig, TestInvalidKeyConfig) { auto invalid_kem = ObliviousHttpHeaderKeyConfig::Create( 3, 0, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); EXPECT_EQ(invalid_kem.status().code(), absl::StatusCode::kInvalidArgument); auto invalid_kdf = ObliviousHttpHeaderKeyConfig::Create( 3, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, 0, EVP_HPKE_AES_256_GCM); EXPECT_EQ(invalid_kdf.status().code(), absl::StatusCode::kInvalidArgument); auto invalid_aead = ObliviousHttpHeaderKeyConfig::Create( 3, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, 0); EXPECT_EQ(invalid_kdf.status().code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfig, TestParsingValidHeader) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(instance.ok()); std::string good_hdr(BuildHeader(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(instance.value().ParseOhttpPayloadHeader(good_hdr).ok()); } TEST(ObliviousHttpHeaderKeyConfig, TestParsingInvalidHeader) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(instance.ok()); std::string keyid_mismatch_hdr( BuildHeader(0, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); EXPECT_EQ(instance.value().ParseOhttpPayloadHeader(keyid_mismatch_hdr).code(), absl::StatusCode::kInvalidArgument); std::string invalid_hpke_hdr(BuildHeader(8, 0, 0, 0)); EXPECT_EQ(instance.value().ParseOhttpPayloadHeader(invalid_hpke_hdr).code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfig, TestParsingKeyIdFromObliviousHttpRequest) { std::string key_id(sizeof(uint8_t), '\0'); QuicheDataWriter writer(key_id.size(), key_id.data()); EXPECT_TRUE(writer.WriteUInt8(99)); auto parsed_key_id = ObliviousHttpHeaderKeyConfig::ParseKeyIdFromObliviousHttpRequestPayload( key_id); ASSERT_TRUE(parsed_key_id.ok()); EXPECT_EQ(parsed_key_id.value(), 99); } TEST(ObliviousHttpHeaderKeyConfig, TestCopyable) { auto obj1 = ObliviousHttpHeaderKeyConfig::Create( 4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(obj1.ok()); auto copy_obj1_to_obj2 = obj1.value(); EXPECT_EQ(copy_obj1_to_obj2.kHeaderLength, obj1->kHeaderLength); EXPECT_EQ(copy_obj1_to_obj2.SerializeRecipientContextInfo(), obj1->SerializeRecipientContextInfo()); } TEST(ObliviousHttpHeaderKeyConfig, TestSerializeOhttpPayloadHeader) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 7, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM); ASSERT_TRUE(instance.ok()); EXPECT_EQ(instance->SerializeOhttpPayloadHeader(), BuildHeader(7, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM)); } MATCHER_P(HasKeyId, id, "") { *result_listener << "has key_id=" << arg.GetKeyId(); return arg.GetKeyId() == id; } MATCHER_P(HasKemId, id, "") { *result_listener << "has kem_id=" << arg.GetHpkeKemId(); return arg.GetHpkeKemId() == id; } MATCHER_P(HasKdfId, id, "") { *result_listener << "has kdf_id=" << arg.GetHpkeKdfId(); return arg.GetHpkeKdfId() == id; } MATCHER_P(HasAeadId, id, "") { *result_listener << "has aead_id=" << arg.GetHpkeAeadId(); return arg.GetHpkeAeadId() == id; } TEST(ObliviousHttpKeyConfigs, SingleKeyConfig) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010002", &key)); auto configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).value(); EXPECT_THAT(configs, Property(&ObliviousHttpKeyConfigs::NumKeys, 1)); EXPECT_THAT( configs.PreferredConfig(), AllOf(HasKeyId(0x4b), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_AES_256_GCM))); std::string expected_public_key; ASSERT_TRUE(absl::HexStringToBytes( "f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b", &expected_public_key)); EXPECT_THAT( configs.GetPublicKeyForId(configs.PreferredConfig().GetKeyId()).value(), StrEq(expected_public_key)); } TEST(ObliviousHttpKeyConfigs, TwoSimilarKeyConfigs) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010002" "4f0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010001", &key)); EXPECT_THAT(ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).value(), Property(&ObliviousHttpKeyConfigs::NumKeys, 2)); EXPECT_THAT( ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key)->PreferredConfig(), AllOf(HasKeyId(0x4f), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_AES_128_GCM))); } TEST(ObliviousHttpKeyConfigs, RFCExample) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "01002031e1f05a740102115220e9af918f738674aec95f54db6e04eb705aae8e79815500" "080001000100010003", &key)); auto configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).value(); EXPECT_THAT(configs, Property(&ObliviousHttpKeyConfigs::NumKeys, 1)); EXPECT_THAT( configs.PreferredConfig(), AllOf(HasKeyId(0x01), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_AES_128_GCM))); std::string expected_public_key; ASSERT_TRUE(absl::HexStringToBytes( "31e1f05a740102115220e9af918f738674aec95f54db6e04eb705aae8e798155", &expected_public_key)); EXPECT_THAT( configs.GetPublicKeyForId(configs.PreferredConfig().GetKeyId()).value(), StrEq(expected_public_key)); } TEST(ObliviousHttpKeyConfigs, DuplicateKeyId) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010002" "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fb27a049bc746a6e97a1e0244b00" "0400010001", &key)); EXPECT_FALSE(ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).ok()); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateWithSingleKeyConfig) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 123, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305); EXPECT_TRUE(instance.ok()); std::string test_public_key( EVP_HPKE_KEM_public_key_len(instance->GetHpkeKem()), 'a'); auto configs = ObliviousHttpKeyConfigs::Create(instance.value(), test_public_key); EXPECT_TRUE(configs.ok()); auto serialized_key = configs->GenerateConcatenatedKeys(); EXPECT_TRUE(serialized_key.ok()); auto ohttp_configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(serialized_key.value()); EXPECT_TRUE(ohttp_configs.ok()); ASSERT_EQ(ohttp_configs->PreferredConfig().GetKeyId(), 123); auto parsed_public_key = ohttp_configs->GetPublicKeyForId(123); EXPECT_TRUE(parsed_public_key.ok()); EXPECT_EQ(parsed_public_key.value(), test_public_key); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateWithWithMultipleKeys) { std::string expected_preferred_public_key(32, 'b'); ObliviousHttpKeyConfigs::OhttpKeyConfig config1 = { 100, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, std::string(32, 'a'), {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}}}; ObliviousHttpKeyConfigs::OhttpKeyConfig config2 = { 200, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, expected_preferred_public_key, {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305}}}; auto configs = ObliviousHttpKeyConfigs::Create({config1, config2}); EXPECT_TRUE(configs.ok()); auto serialized_key = configs->GenerateConcatenatedKeys(); EXPECT_TRUE(serialized_key.ok()); ASSERT_EQ(serialized_key.value(), absl::StrCat(GetSerializedKeyConfig(config2), GetSerializedKeyConfig(config1))); auto ohttp_configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(serialized_key.value()); EXPECT_TRUE(ohttp_configs.ok()); ASSERT_EQ(ohttp_configs->NumKeys(), 2); EXPECT_THAT(configs->PreferredConfig(), AllOf(HasKeyId(200), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_CHACHA20_POLY1305))); auto parsed_preferred_public_key = ohttp_configs->GetPublicKeyForId( ohttp_configs->PreferredConfig().GetKeyId()); EXPECT_TRUE(parsed_preferred_public_key.ok()); EXPECT_EQ(parsed_preferred_public_key.value(), expected_preferred_public_key); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateWithInvalidConfigs) { ASSERT_EQ(ObliviousHttpKeyConfigs::Create({}).status().code(), absl::StatusCode::kInvalidArgument); ASSERT_EQ(ObliviousHttpKeyConfigs::Create( {{100, 2, std::string(32, 'a'), {{2, 3}, {4, 5}}}, {200, 6, std::string(32, 'b'), {{7, 8}, {9, 10}}}}) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ( ObliviousHttpKeyConfigs::Create( {{123, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, "invalid key length" , {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}}}}) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateSingleKeyConfigWithInvalidConfig) { const auto sample_ohttp_hdr_config = ObliviousHttpHeaderKeyConfig::Create( 123, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM); ASSERT_TRUE(sample_ohttp_hdr_config.ok()); ASSERT_EQ(ObliviousHttpKeyConfigs::Create(sample_ohttp_hdr_config.value(), "" ) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpKeyConfigs::Create( sample_ohttp_hdr_config.value(), "invalid key length" ) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfigs, TestHashImplWithObliviousStruct) { absl::flat_hash_set<ObliviousHttpKeyConfigs::SymmetricAlgorithmsConfig> symmetric_algs_set; for (int i = 0; i < 50; ++i) { symmetric_algs_set.insert({EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}); symmetric_algs_set.insert({EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}); symmetric_algs_set.insert( {EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305}); } ASSERT_EQ(symmetric_algs_set.size(), 3); EXPECT_THAT(symmetric_algs_set, UnorderedElementsAreArray< ObliviousHttpKeyConfigs::SymmetricAlgorithmsConfig>({ {EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}, {EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}, {EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305}, })); absl::flat_hash_set<ObliviousHttpKeyConfigs::OhttpKeyConfig> ohttp_key_configs_set; ObliviousHttpKeyConfigs::OhttpKeyConfig expected_key_config{ 100, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, std::string(32, 'c'), {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}, {EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}}}; for (int i = 0; i < 50; ++i) { ohttp_key_configs_set.insert(expected_key_config); } ASSERT_EQ(ohttp_key_configs_set.size(), 1); EXPECT_THAT(ohttp_key_configs_set, UnorderedElementsAre(expected_key_config)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/common/oblivious_http_header_key_config.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/oblivious_http/common/oblivious_http_header_key_config_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
cbdbbcd9-531f-44a7-8c9c-6d54780b1a2c
cpp
google/quiche
web_transport_headers
quiche/web_transport/web_transport_headers.cc
quiche/web_transport/web_transport_headers_test.cc
#include "quiche/web_transport/web_transport_headers.h" #include <array> #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/common/quiche_status_utils.h" #include "quiche/common/structured_headers.h" namespace webtransport { namespace { using ::quiche::structured_headers::Dictionary; using ::quiche::structured_headers::DictionaryMember; using ::quiche::structured_headers::Item; using ::quiche::structured_headers::ItemTypeToString; using ::quiche::structured_headers::List; using ::quiche::structured_headers::ParameterizedItem; using ::quiche::structured_headers::ParameterizedMember; absl::Status CheckItemType(const ParameterizedItem& item, Item::ItemType expected_type) { if (item.item.Type() != expected_type) { return absl::InvalidArgumentError(absl::StrCat( "Expected all members to be of type ", ItemTypeToString(expected_type), ", found ", ItemTypeToString(item.item.Type()), " instead")); } return absl::OkStatus(); } absl::Status CheckMemberType(const ParameterizedMember& member, Item::ItemType expected_type) { if (member.member_is_inner_list || member.member.size() != 1) { return absl::InvalidArgumentError(absl::StrCat( "Expected all members to be of type", ItemTypeToString(expected_type), ", found a nested list instead")); } return CheckItemType(member.member[0], expected_type); } ABSL_CONST_INIT std::array kInitHeaderFields{ std::make_pair("u", &WebTransportInitHeader::initial_unidi_limit), std::make_pair("bl", &WebTransportInitHeader::initial_incoming_bidi_limit), std::make_pair("br", &WebTransportInitHeader::initial_outgoing_bidi_limit), }; } absl::StatusOr<std::vector<std::string>> ParseSubprotocolRequestHeader( absl::string_view value) { std::optional<List> parsed = quiche::structured_headers::ParseList(value); if (!parsed.has_value()) { return absl::InvalidArgumentError( "Failed to parse the header as an sf-list"); } std::vector<std::string> result; result.reserve(parsed->size()); for (ParameterizedMember& member : *parsed) { QUICHE_RETURN_IF_ERROR(CheckMemberType(member, Item::kTokenType)); result.push_back(std::move(member.member[0].item).TakeString()); } return result; } absl::StatusOr<std::string> SerializeSubprotocolRequestHeader( absl::Span<const std::string> subprotocols) { for (const std::string& token : subprotocols) { if (!quiche::structured_headers::IsValidToken(token)) { return absl::InvalidArgumentError(absl::StrCat("Invalid token: ", token)); } } return absl::StrJoin(subprotocols, ", "); } absl::StatusOr<std::string> ParseSubprotocolResponseHeader( absl::string_view value) { std::optional<ParameterizedItem> parsed = quiche::structured_headers::ParseItem(value); if (!parsed.has_value()) { return absl::InvalidArgumentError("Failed to parse sf-item"); } QUICHE_RETURN_IF_ERROR(CheckItemType(*parsed, Item::kTokenType)); return std::move(parsed->item).TakeString(); } absl::StatusOr<std::string> SerializeSubprotocolResponseHeader( absl::string_view subprotocol) { if (!quiche::structured_headers::IsValidToken(subprotocol)) { return absl::InvalidArgumentError("Invalid token value supplied"); } return std::string(subprotocol); } absl::StatusOr<WebTransportInitHeader> ParseInitHeader( absl::string_view header) { std::optional<Dictionary> parsed = quiche::structured_headers::ParseDictionary(header); if (!parsed.has_value()) { return absl::InvalidArgumentError( "Failed to parse WebTransport-Init header as an sf-dictionary"); } WebTransportInitHeader output; for (const auto& [field_name_a, field_value] : *parsed) { for (const auto& [field_name_b, field_accessor] : kInitHeaderFields) { if (field_name_a != field_name_b) { continue; } QUICHE_RETURN_IF_ERROR(CheckMemberType(field_value, Item::kIntegerType)); int64_t value = field_value.member[0].item.GetInteger(); if (value < 0) { return absl::InvalidArgumentError( absl::StrCat("Received negative value for ", field_name_a)); } output.*field_accessor = value; } } return output; } absl::StatusOr<std::string> SerializeInitHeader( const WebTransportInitHeader& header) { std::vector<DictionaryMember> members; members.reserve(kInitHeaderFields.size()); for (const auto& [field_name, field_accessor] : kInitHeaderFields) { Item item(static_cast<int64_t>(header.*field_accessor)); members.push_back(std::make_pair( field_name, ParameterizedMember({ParameterizedItem(item, {})}, false, {}))); } std::optional<std::string> result = quiche::structured_headers::SerializeDictionary( Dictionary(std::move(members))); if (!result.has_value()) { return absl::InternalError("Failed to serialize the dictionary"); } return *std::move(result); } }
#include "quiche/web_transport/web_transport_headers.h" #include "absl/status/status.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace webtransport { namespace { using ::quiche::test::IsOkAndHolds; using ::quiche::test::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; TEST(WebTransportHeaders, ParseSubprotocolRequestHeader) { EXPECT_THAT(ParseSubprotocolRequestHeader("test"), IsOkAndHolds(ElementsAre("test"))); EXPECT_THAT(ParseSubprotocolRequestHeader("moqt-draft01, moqt-draft02"), IsOkAndHolds(ElementsAre("moqt-draft01", "moqt-draft02"))); EXPECT_THAT(ParseSubprotocolRequestHeader("moqt-draft01; a=b, moqt-draft02"), IsOkAndHolds(ElementsAre("moqt-draft01", "moqt-draft02"))); EXPECT_THAT(ParseSubprotocolRequestHeader("moqt-draft01, moqt-draft02; a=b"), IsOkAndHolds(ElementsAre("moqt-draft01", "moqt-draft02"))); EXPECT_THAT(ParseSubprotocolRequestHeader("\"test\""), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found string instead"))); EXPECT_THAT(ParseSubprotocolRequestHeader("42"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found integer instead"))); EXPECT_THAT(ParseSubprotocolRequestHeader("a, (b)"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found a nested list instead"))); EXPECT_THAT(ParseSubprotocolRequestHeader("a, (b c)"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found a nested list instead"))); EXPECT_THAT(ParseSubprotocolRequestHeader("foo, ?1, bar"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found boolean instead"))); EXPECT_THAT(ParseSubprotocolRequestHeader("(a"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("parse the header as an sf-list"))); } TEST(WebTransportHeaders, SerializeSubprotocolRequestHeader) { EXPECT_THAT(SerializeSubprotocolRequestHeader({"test"}), IsOkAndHolds("test")); EXPECT_THAT(SerializeSubprotocolRequestHeader({"foo", "bar"}), IsOkAndHolds("foo, bar")); EXPECT_THAT(SerializeSubprotocolRequestHeader({"moqt-draft01", "a/b/c"}), IsOkAndHolds("moqt-draft01, a/b/c")); EXPECT_THAT( SerializeSubprotocolRequestHeader({"abcd", "0123", "efgh"}), StatusIs(absl::StatusCode::kInvalidArgument, "Invalid token: 0123")); } TEST(WebTransportHeader, ParseSubprotocolResponseHeader) { EXPECT_THAT(ParseSubprotocolResponseHeader("foo"), IsOkAndHolds("foo")); EXPECT_THAT(ParseSubprotocolResponseHeader("foo; a=b"), IsOkAndHolds("foo")); EXPECT_THAT( ParseSubprotocolResponseHeader("1234"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found integer"))); EXPECT_THAT( ParseSubprotocolResponseHeader("(a"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("parse sf-item"))); } TEST(WebTransportHeader, SerializeSubprotocolResponseHeader) { EXPECT_THAT(SerializeSubprotocolResponseHeader("foo"), IsOkAndHolds("foo")); EXPECT_THAT(SerializeSubprotocolResponseHeader("moqt-draft01"), IsOkAndHolds("moqt-draft01")); EXPECT_THAT(SerializeSubprotocolResponseHeader("123abc"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(WebTransportHeader, ParseInitHeader) { WebTransportInitHeader expected_header; expected_header.initial_unidi_limit = 100; expected_header.initial_incoming_bidi_limit = 200; expected_header.initial_outgoing_bidi_limit = 400; EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=100"), IsOkAndHolds(expected_header)); EXPECT_THAT(ParseInitHeader("br=300, bl=200, u=100, br=400"), IsOkAndHolds(expected_header)); EXPECT_THAT(ParseInitHeader("br=400, bl=200; foo=bar, u=100"), IsOkAndHolds(expected_header)); EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=100.0"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found decimal instead"))); EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=?1"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found boolean instead"))); EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=(a b)"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found a nested list instead"))); EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=:abcd:"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found byte sequence instead"))); EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=-1"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("negative value"))); EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=18446744073709551615"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Failed to parse"))); } TEST(WebTransportHeaders, SerializeInitHeader) { EXPECT_THAT(SerializeInitHeader(WebTransportInitHeader{}), IsOkAndHolds("u=0, bl=0, br=0")); WebTransportInitHeader test_header; test_header.initial_unidi_limit = 100; test_header.initial_incoming_bidi_limit = 200; test_header.initial_outgoing_bidi_limit = 400; EXPECT_THAT(SerializeInitHeader(test_header), IsOkAndHolds("u=100, bl=200, br=400")); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/web_transport/web_transport_headers.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/web_transport/web_transport_headers_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5a602f40-4697-4fe5-b527-76ff68a9646e
cpp
google/quiche
web_transport_priority_scheduler
quiche/web_transport/web_transport_priority_scheduler.cc
quiche/web_transport/web_transport_priority_scheduler_test.cc
#include "quiche/web_transport/web_transport_priority_scheduler.h" #include <optional> #include <utility> #include "absl/cleanup/cleanup.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "quiche/common/quiche_status_utils.h" #include "quiche/web_transport/web_transport.h" namespace webtransport { absl::Status PriorityScheduler::Register(StreamId stream_id, const StreamPriority& priority) { auto [it, success] = stream_to_group_map_.insert({stream_id, nullptr}); if (!success) { return absl::AlreadyExistsError("Provided stream ID already registered"); } auto cleanup_nullptr_map_entry = absl::MakeCleanup([&] { stream_to_group_map_.erase(stream_id); }); auto [scheduler_it, scheduler_created] = per_group_schedulers_.try_emplace(priority.send_group_id); if (scheduler_created) { QUICHE_RETURN_IF_ERROR(active_groups_.Register(priority.send_group_id, {})); } PerGroupScheduler& scheduler = scheduler_it->second; QUICHE_RETURN_IF_ERROR(scheduler.Register(stream_id, priority.send_order)); it->second = &*scheduler_it; std::move(cleanup_nullptr_map_entry).Cancel(); return absl::OkStatus(); } absl::Status PriorityScheduler::Unregister(StreamId stream_id) { auto it = stream_to_group_map_.find(stream_id); if (it == stream_to_group_map_.end()) { return absl::NotFoundError("Stream ID not registered"); } SendGroupId group_id = it->second->first; PerGroupScheduler* group_scheduler = &it->second->second; stream_to_group_map_.erase(it); QUICHE_RETURN_IF_ERROR(group_scheduler->Unregister(stream_id)); if (!group_scheduler->HasRegistered()) { per_group_schedulers_.erase(group_id); QUICHE_RETURN_IF_ERROR(active_groups_.Unregister(group_id)); } return absl::OkStatus(); } absl::Status PriorityScheduler::UpdateSendOrder(StreamId stream_id, SendOrder new_send_order) { PerGroupScheduler* scheduler = SchedulerForStream(stream_id); if (scheduler == nullptr) { return absl::NotFoundError("Stream ID not registered"); } return scheduler->UpdatePriority(stream_id, new_send_order); } absl::Status PriorityScheduler::UpdateSendGroup(StreamId stream_id, SendGroupId new_send_group) { PerGroupScheduler* scheduler = SchedulerForStream(stream_id); if (scheduler == nullptr) { return absl::NotFoundError("Stream ID not registered"); } bool is_scheduled = scheduler->IsScheduled(stream_id); std::optional<SendOrder> send_order = scheduler->GetPriorityFor(stream_id); if (!send_order.has_value()) { return absl::InternalError( "Stream registered at the top level scheduler, but not at the " "per-group one"); } QUICHE_RETURN_IF_ERROR(Unregister(stream_id)); QUICHE_RETURN_IF_ERROR( Register(stream_id, StreamPriority{new_send_group, *send_order})); if (is_scheduled) { QUICHE_RETURN_IF_ERROR(Schedule(stream_id)); } return absl::OkStatus(); } std::optional<StreamPriority> PriorityScheduler::GetPriorityFor( StreamId stream_id) const { auto it = stream_to_group_map_.find(stream_id); if (it == stream_to_group_map_.end()) { return std::nullopt; } const auto& [group_id, group_scheduler] = *it->second; std::optional<SendOrder> send_order = group_scheduler.GetPriorityFor(stream_id); if (!send_order.has_value()) { return std::nullopt; } return StreamPriority{group_id, *send_order}; } absl::StatusOr<bool> PriorityScheduler::ShouldYield(StreamId stream_id) const { auto it = stream_to_group_map_.find(stream_id); if (it == stream_to_group_map_.end()) { return absl::NotFoundError("Stream ID not registered"); } const auto& [group_id, group_scheduler] = *it->second; absl::StatusOr<bool> per_group_result = active_groups_.ShouldYield(group_id); QUICHE_RETURN_IF_ERROR(per_group_result.status()); if (*per_group_result) { return true; } return group_scheduler.ShouldYield(stream_id); } absl::StatusOr<StreamId> PriorityScheduler::PopFront() { absl::StatusOr<SendGroupId> group_id = active_groups_.PopFront(); QUICHE_RETURN_IF_ERROR(group_id.status()); auto it = per_group_schedulers_.find(*group_id); if (it == per_group_schedulers_.end()) { return absl::InternalError( "Scheduled a group with no per-group scheduler attached"); } PerGroupScheduler& scheduler = it->second; absl::StatusOr<StreamId> result = scheduler.PopFront(); if (!result.ok()) { return absl::InternalError("Inactive group found in top-level schedule"); } if (scheduler.HasScheduled()) { QUICHE_RETURN_IF_ERROR(active_groups_.Schedule(*group_id)); } return result; } absl::Status PriorityScheduler::Schedule(StreamId stream_id) { auto it = stream_to_group_map_.find(stream_id); if (it == stream_to_group_map_.end()) { return absl::NotFoundError("Stream ID not registered"); } auto& [group_id, group_scheduler] = *it->second; QUICHE_RETURN_IF_ERROR(active_groups_.Schedule(group_id)); return group_scheduler.Schedule(stream_id); } bool PriorityScheduler::IsScheduled(StreamId stream_id) const { const PerGroupScheduler* scheduler = SchedulerForStream(stream_id); if (scheduler == nullptr) { return false; } return scheduler->IsScheduled(stream_id); } }
#include "quiche/web_transport/web_transport_priority_scheduler.h" #include <optional> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/web_transport/web_transport.h" namespace webtransport { namespace { using ::quiche::test::IsOkAndHolds; using ::quiche::test::StatusIs; using ::testing::ElementsAre; void ScheduleIds(PriorityScheduler& scheduler, absl::Span<const StreamId> ids) { for (StreamId id : ids) { QUICHE_EXPECT_OK(scheduler.Schedule(id)); } } std::vector<StreamId> PopAll(PriorityScheduler& scheduler) { std::vector<StreamId> result; result.reserve(scheduler.NumScheduled()); for (;;) { absl::StatusOr<StreamId> id = scheduler.PopFront(); if (!id.ok()) { EXPECT_THAT(id, StatusIs(absl::StatusCode::kNotFound)); break; } result.push_back(*id); } return result; } TEST(WebTransportSchedulerTest, Register) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 0})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0})); QUICHE_EXPECT_OK(scheduler.Register(4, StreamPriority{0, 0})); EXPECT_THAT(scheduler.Register(4, StreamPriority{0, 0}), StatusIs(absl::StatusCode::kAlreadyExists)); EXPECT_THAT(scheduler.Register(4, StreamPriority{1, 0}), StatusIs(absl::StatusCode::kAlreadyExists)); } TEST(WebTransportSchedulerTest, Unregister) { PriorityScheduler scheduler; EXPECT_FALSE(scheduler.HasRegistered()); QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); EXPECT_TRUE(scheduler.HasRegistered()); QUICHE_EXPECT_OK(scheduler.Unregister(1)); EXPECT_TRUE(scheduler.HasRegistered()); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); ScheduleIds(scheduler, {0, 1}); QUICHE_EXPECT_OK(scheduler.Unregister(0)); QUICHE_EXPECT_OK(scheduler.Unregister(1)); EXPECT_FALSE(scheduler.HasRegistered()); QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); EXPECT_TRUE(scheduler.HasRegistered()); EXPECT_FALSE(scheduler.HasScheduled()); } TEST(WebTransportSchedulerTest, UpdatePriority) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 10})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 20})); EXPECT_EQ(scheduler.GetPriorityFor(0), (StreamPriority{0, 10})); EXPECT_EQ(scheduler.GetPriorityFor(1), (StreamPriority{0, 20})); QUICHE_EXPECT_OK(scheduler.UpdateSendGroup(0, 1)); QUICHE_EXPECT_OK(scheduler.UpdateSendOrder(1, 40)); EXPECT_EQ(scheduler.GetPriorityFor(0), (StreamPriority{1, 10})); EXPECT_EQ(scheduler.GetPriorityFor(1), (StreamPriority{0, 40})); EXPECT_THAT(scheduler.UpdateSendGroup(1000, 1), StatusIs(absl::StatusCode::kNotFound)); EXPECT_THAT(scheduler.UpdateSendOrder(1000, 1), StatusIs(absl::StatusCode::kNotFound)); EXPECT_EQ(scheduler.GetPriorityFor(1000), std::nullopt); } TEST(WebTransportSchedulerTest, Schedule) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); EXPECT_FALSE(scheduler.IsScheduled(0)); EXPECT_FALSE(scheduler.IsScheduled(1)); EXPECT_FALSE(scheduler.IsScheduled(1000)); QUICHE_EXPECT_OK(scheduler.Schedule(0)); EXPECT_TRUE(scheduler.IsScheduled(0)); EXPECT_FALSE(scheduler.IsScheduled(1)); QUICHE_EXPECT_OK(scheduler.Schedule(1)); EXPECT_TRUE(scheduler.IsScheduled(0)); EXPECT_TRUE(scheduler.IsScheduled(1)); EXPECT_THAT(scheduler.Schedule(0), StatusIs(absl::StatusCode::kOk)); EXPECT_THAT(scheduler.Schedule(2), StatusIs(absl::StatusCode::kNotFound)); } TEST(WebTransportSchedulerTest, SamePriority) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{0, 0})); ScheduleIds(scheduler, {0, 1, 2, 3}); EXPECT_EQ(scheduler.NumScheduled(), 4); EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 1, 2, 3)); ScheduleIds(scheduler, {3, 1, 2}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2)); } TEST(WebTransportSchedulerTest, SingleBucketOrdered) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 1})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{0, 2})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{0, 3})); ScheduleIds(scheduler, {0, 1, 2, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 2, 1, 0)); ScheduleIds(scheduler, {3, 1, 2, 0}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 2, 1, 0)); } TEST(WebTransportSchedulerTest, EveryStreamInItsOwnBucket) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{1, 1})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{2, 2})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{3, 3})); ScheduleIds(scheduler, {0, 1, 2, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 1, 2, 3)); ScheduleIds(scheduler, {3, 1, 2}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2)); } TEST(WebTransportSchedulerTest, TwoBucketsNoSendOrder) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 0})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0})); ScheduleIds(scheduler, {0, 1, 2, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 2, 1, 3)); ScheduleIds(scheduler, {0, 2, 1, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 2, 1, 3)); ScheduleIds(scheduler, {3, 2, 1, 0}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2, 0)); ScheduleIds(scheduler, {0, 2}); EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(0)); ScheduleIds(scheduler, {1, 3, 0}); EXPECT_THAT(PopAll(scheduler), ElementsAre(2, 1, 3, 0)); } TEST(WebTransportSchedulerTest, TwoBucketsWithSendOrder) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 10})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 20})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 30})); ScheduleIds(scheduler, {0, 1, 2, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 3, 0, 2)); ScheduleIds(scheduler, {3, 2, 1, 0}); EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2, 0)); } TEST(WebTransportSchedulerTest, ShouldYield) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{0, 10})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0})); EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(4), StatusIs(absl::StatusCode::kNotFound)); QUICHE_EXPECT_OK(scheduler.Schedule(0)); EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(true)); PopAll(scheduler); QUICHE_EXPECT_OK(scheduler.Schedule(2)); EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(false)); EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(true)); PopAll(scheduler); QUICHE_EXPECT_OK(scheduler.Schedule(3)); EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(true)); EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(false)); PopAll(scheduler); } TEST(WebTransportSchedulerTest, UpdatePriorityWhileScheduled) { PriorityScheduler scheduler; QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0})); QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 0})); QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0})); ScheduleIds(scheduler, {0, 1, 2, 3}); EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 2, 1, 3)); ScheduleIds(scheduler, {0, 1, 2, 3}); QUICHE_EXPECT_OK(scheduler.UpdateSendOrder(1, 10)); EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 2, 0, 3)); ScheduleIds(scheduler, {0, 1, 2, 3}); QUICHE_EXPECT_OK(scheduler.UpdateSendGroup(1, 1)); EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 1, 2, 3)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/web_transport/web_transport_priority_scheduler.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/web_transport/web_transport_priority_scheduler_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bd8bc1a3-cd69-4c3e-b828-b3739fd2b8e0
cpp
google/quiche
encapsulated_web_transport
quiche/web_transport/encapsulated/encapsulated_web_transport.cc
quiche/web_transport/encapsulated/encapsulated_web_transport_test.cc
#include "quiche/web_transport/encapsulated/encapsulated_web_transport.h" #include <stdbool.h> #include <algorithm> #include <array> #include <cstddef> #include <cstdint> #include <cstring> #include <iterator> #include <memory> #include <optional> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/node_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "quiche/common/capsule.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_circular_deque.h" #include "quiche/common/quiche_status_utils.h" #include "quiche/common/quiche_stream.h" #include "quiche/web_transport/web_transport.h" namespace webtransport { namespace { using ::quiche::Capsule; using ::quiche::CapsuleType; using ::quiche::CloseWebTransportSessionCapsule; constexpr uint64_t kEncapsulatedMaxDatagramSize = 9000; constexpr StreamPriority kDefaultPriority = StreamPriority{0, 0}; } EncapsulatedSession::EncapsulatedSession( Perspective perspective, FatalErrorCallback fatal_error_callback) : perspective_(perspective), fatal_error_callback_(std::move(fatal_error_callback)), capsule_parser_(this), next_outgoing_bidi_stream_(perspective == Perspective::kClient ? 0 : 1), next_outgoing_unidi_stream_(perspective == Perspective::kClient ? 2 : 3) { QUICHE_DCHECK(IsIdOpenedBy(next_outgoing_bidi_stream_, perspective)); QUICHE_DCHECK(IsIdOpenedBy(next_outgoing_unidi_stream_, perspective)); } void EncapsulatedSession::InitializeClient( std::unique_ptr<SessionVisitor> visitor, quiche::HttpHeaderBlock& , quiche::WriteStream* writer, quiche::ReadStream* reader) { if (state_ != kUninitialized) { OnFatalError("Called InitializeClient() in an invalid state"); return; } if (perspective_ != Perspective::kClient) { OnFatalError("Called InitializeClient() on a server session"); return; } visitor_ = std::move(visitor); writer_ = writer; reader_ = reader; state_ = kWaitingForHeaders; } void EncapsulatedSession::InitializeServer( std::unique_ptr<SessionVisitor> visitor, const quiche::HttpHeaderBlock& , quiche::HttpHeaderBlock& , quiche::WriteStream* writer, quiche::ReadStream* reader) { if (state_ != kUninitialized) { OnFatalError("Called InitializeServer() in an invalid state"); return; } if (perspective_ != Perspective::kServer) { OnFatalError("Called InitializeServer() on a client session"); return; } visitor_ = std::move(visitor); writer_ = writer; reader_ = reader; OpenSession(); } void EncapsulatedSession::ProcessIncomingServerHeaders( const quiche::HttpHeaderBlock& ) { if (state_ != kWaitingForHeaders) { OnFatalError("Called ProcessIncomingServerHeaders() in an invalid state"); return; } OpenSession(); } void EncapsulatedSession::CloseSession(SessionErrorCode error_code, absl::string_view error_message) { switch (state_) { case kUninitialized: case kWaitingForHeaders: OnFatalError(absl::StrCat( "Attempted to close a session before it opened with error 0x", absl::Hex(error_code), ": ", error_message)); return; case kSessionClosing: case kSessionClosed: OnFatalError(absl::StrCat( "Attempted to close a session that is already closed with error 0x", absl::Hex(error_code), ": ", error_message)); return; case kSessionOpen: break; } state_ = kSessionClosing; buffered_session_close_ = BufferedClose{error_code, std::string(error_message)}; OnCanWrite(); } Stream* EncapsulatedSession::AcceptIncomingStream( quiche::QuicheCircularDeque<StreamId>& queue) { while (!queue.empty()) { StreamId id = queue.front(); queue.pop_front(); Stream* stream = GetStreamById(id); if (stream == nullptr) { continue; } return stream; } return nullptr; } Stream* EncapsulatedSession::AcceptIncomingBidirectionalStream() { return AcceptIncomingStream(incoming_bidirectional_streams_); } Stream* EncapsulatedSession::AcceptIncomingUnidirectionalStream() { return AcceptIncomingStream(incoming_unidirectional_streams_); } bool EncapsulatedSession::CanOpenNextOutgoingBidirectionalStream() { return true; } bool EncapsulatedSession::CanOpenNextOutgoingUnidirectionalStream() { return true; } Stream* EncapsulatedSession::OpenOutgoingStream(StreamId& counter) { StreamId stream_id = counter; counter += 4; auto [it, inserted] = streams_.emplace( std::piecewise_construct, std::forward_as_tuple(stream_id), std::forward_as_tuple(this, stream_id)); QUICHE_DCHECK(inserted); return &it->second; } Stream* EncapsulatedSession::OpenOutgoingBidirectionalStream() { if (!CanOpenNextOutgoingBidirectionalStream()) { return nullptr; } return OpenOutgoingStream(next_outgoing_bidi_stream_); } Stream* EncapsulatedSession::OpenOutgoingUnidirectionalStream() { if (!CanOpenNextOutgoingUnidirectionalStream()) { return nullptr; } return OpenOutgoingStream(next_outgoing_unidi_stream_); } Stream* EncapsulatedSession::GetStreamById(StreamId id) { auto it = streams_.find(id); if (it == streams_.end()) { return nullptr; } return &it->second; } DatagramStats EncapsulatedSession::GetDatagramStats() { DatagramStats stats; stats.expired_outgoing = 0; stats.lost_outgoing = 0; return stats; } SessionStats EncapsulatedSession::GetSessionStats() { return SessionStats(); } void EncapsulatedSession::NotifySessionDraining() { SendControlCapsule(quiche::DrainWebTransportSessionCapsule()); OnCanWrite(); } void EncapsulatedSession::SetOnDraining( quiche::SingleUseCallback<void()> callback) { draining_callback_ = std::move(callback); } DatagramStatus EncapsulatedSession::SendOrQueueDatagram( absl::string_view datagram) { if (datagram.size() > GetMaxDatagramSize()) { return DatagramStatus{ DatagramStatusCode::kTooBig, absl::StrCat("Datagram is ", datagram.size(), " bytes long, while the specified maximum size is ", GetMaxDatagramSize())}; } bool write_blocked; switch (state_) { case kUninitialized: write_blocked = true; break; case kWaitingForHeaders: case kSessionOpen: write_blocked = !writer_->CanWrite(); break; case kSessionClosing: case kSessionClosed: return DatagramStatus{DatagramStatusCode::kInternalError, "Writing into an already closed session"}; } if (write_blocked) { control_capsule_queue_.push_back( quiche::SerializeCapsule(Capsule::Datagram(datagram), allocator_)); return DatagramStatus{DatagramStatusCode::kSuccess, ""}; } quiche::QuicheBuffer buffer = quiche::SerializeDatagramCapsuleHeader(datagram.size(), allocator_); std::array spans = {buffer.AsStringView(), datagram}; absl::Status write_status = writer_->Writev(absl::MakeConstSpan(spans), quiche::StreamWriteOptions()); if (!write_status.ok()) { OnWriteError(write_status); return DatagramStatus{ DatagramStatusCode::kInternalError, absl::StrCat("Write error for datagram: ", write_status.ToString())}; } return DatagramStatus{DatagramStatusCode::kSuccess, ""}; } uint64_t EncapsulatedSession::GetMaxDatagramSize() const { return kEncapsulatedMaxDatagramSize; } void EncapsulatedSession::SetDatagramMaxTimeInQueue( absl::Duration ) { } void EncapsulatedSession::OnCanWrite() { if (state_ == kUninitialized || !writer_) { OnFatalError("Trying to write before the session is initialized"); return; } if (state_ == kSessionClosed) { OnFatalError("Trying to write before the session is closed"); return; } if (state_ == kSessionClosing) { if (writer_->CanWrite()) { CloseWebTransportSessionCapsule capsule{ buffered_session_close_.error_code, buffered_session_close_.error_message}; quiche::QuicheBuffer buffer = quiche::SerializeCapsule(Capsule(std::move(capsule)), allocator_); absl::Status write_status = SendFin(buffer.AsStringView()); if (!write_status.ok()) { OnWriteError(quiche::AppendToStatus(write_status, " while writing WT_CLOSE_SESSION")); return; } OnSessionClosed(buffered_session_close_.error_code, buffered_session_close_.error_message); } return; } while (writer_->CanWrite() && !control_capsule_queue_.empty()) { absl::Status write_status = quiche::WriteIntoStream( *writer_, control_capsule_queue_.front().AsStringView()); if (!write_status.ok()) { OnWriteError(write_status); return; } control_capsule_queue_.pop_front(); } while (writer_->CanWrite()) { absl::StatusOr<StreamId> next_id = scheduler_.PopFront(); if (!next_id.ok()) { QUICHE_DCHECK_EQ(next_id.status().code(), absl::StatusCode::kNotFound); return; } auto it = streams_.find(*next_id); if (it == streams_.end()) { QUICHE_BUG(WT_H2_NextStreamNotInTheMap); OnFatalError("Next scheduled stream is not in the map"); return; } QUICHE_DCHECK(it->second.HasPendingWrite()); it->second.FlushPendingWrite(); } } void EncapsulatedSession::OnCanRead() { if (state_ == kSessionClosed || state_ == kSessionClosing) { return; } bool has_fin = quiche::ProcessAllReadableRegions( *reader_, [&](absl::string_view fragment) { capsule_parser_.IngestCapsuleFragment(fragment); }); if (has_fin) { capsule_parser_.ErrorIfThereIsRemainingBufferedData(); OnSessionClosed(0, ""); } if (state_ == kSessionOpen) { GarbageCollectStreams(); } } bool EncapsulatedSession::OnCapsule(const quiche::Capsule& capsule) { switch (capsule.capsule_type()) { case CapsuleType::DATAGRAM: visitor_->OnDatagramReceived( capsule.datagram_capsule().http_datagram_payload); break; case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: if (draining_callback_) { std::move(draining_callback_)(); } break; case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: OnSessionClosed( capsule.close_web_transport_session_capsule().error_code, std::string( capsule.close_web_transport_session_capsule().error_message)); break; case CapsuleType::WT_STREAM: case CapsuleType::WT_STREAM_WITH_FIN: ProcessStreamCapsule(capsule, capsule.web_transport_stream_data().stream_id); break; case CapsuleType::WT_RESET_STREAM: ProcessStreamCapsule(capsule, capsule.web_transport_reset_stream().stream_id); break; case CapsuleType::WT_STOP_SENDING: ProcessStreamCapsule(capsule, capsule.web_transport_stop_sending().stream_id); break; default: break; } return state_ != kSessionClosed; } void EncapsulatedSession::OnCapsuleParseFailure( absl::string_view error_message) { if (state_ == kSessionClosed) { return; } OnFatalError(absl::StrCat("Stream parse error: ", error_message)); } void EncapsulatedSession::ProcessStreamCapsule(const quiche::Capsule& capsule, StreamId stream_id) { bool new_stream_created = false; auto it = streams_.find(stream_id); if (it == streams_.end()) { if (IsOutgoing(stream_id)) { return; } it = streams_.emplace_hint(it, std::piecewise_construct, std::forward_as_tuple(stream_id), std::forward_as_tuple(this, stream_id)); new_stream_created = true; } InnerStream& stream = it->second; stream.ProcessCapsule(capsule); if (new_stream_created) { if (IsBidirectionalId(stream_id)) { incoming_bidirectional_streams_.push_back(stream_id); visitor_->OnIncomingBidirectionalStreamAvailable(); } else { incoming_unidirectional_streams_.push_back(stream_id); visitor_->OnIncomingUnidirectionalStreamAvailable(); } } } void EncapsulatedSession::InnerStream::ProcessCapsule( const quiche::Capsule& capsule) { switch (capsule.capsule_type()) { case CapsuleType::WT_STREAM: case CapsuleType::WT_STREAM_WITH_FIN: { if (fin_received_) { session_->OnFatalError( "Received stream data for a stream that has already received a " "FIN"); return; } if (read_side_closed_) { return; } fin_received_ = capsule.capsule_type() == CapsuleType::WT_STREAM_WITH_FIN; const quiche::WebTransportStreamDataCapsule& data = capsule.web_transport_stream_data(); if (!data.data.empty()) { incoming_reads_.push_back(IncomingRead{data.data, std::string()}); } if (visitor_ != nullptr) { visitor_->OnCanRead(); } for (IncomingRead& read : incoming_reads_) { QUICHE_DCHECK(!read.data.empty()); if (read.storage.empty()) { read.storage = std::string(read.data); read.data = read.storage; } } return; } case CapsuleType::WT_RESET_STREAM: CloseReadSide(capsule.web_transport_reset_stream().error_code); return; case CapsuleType::WT_STOP_SENDING: CloseWriteSide(capsule.web_transport_stop_sending().error_code); return; default: QUICHE_BUG(WT_H2_ProcessStreamCapsule_Unknown) << "Unexpected capsule dispatched to InnerStream: " << capsule; session_->OnFatalError( "Internal error: Unexpected capsule dispatched to InnerStream"); return; } } void EncapsulatedSession::OpenSession() { state_ = kSessionOpen; visitor_->OnSessionReady(); OnCanWrite(); OnCanRead(); } absl::Status EncapsulatedSession::SendFin(absl::string_view data) { QUICHE_DCHECK(!fin_sent_); fin_sent_ = true; quiche::StreamWriteOptions options; options.set_send_fin(true); return quiche::WriteIntoStream(*writer_, data, options); } void EncapsulatedSession::OnSessionClosed(SessionErrorCode error_code, const std::string& error_message) { if (!fin_sent_) { absl::Status status = SendFin(""); if (!status.ok()) { OnWriteError(status); return; } } if (session_close_notified_) { QUICHE_DCHECK_EQ(state_, kSessionClosed); return; } state_ = kSessionClosed; session_close_notified_ = true; if (visitor_ != nullptr) { visitor_->OnSessionClosed(error_code, error_message); } } void EncapsulatedSession::OnFatalError(absl::string_view error_message) { QUICHE_DLOG(ERROR) << "Fatal error in encapsulated WebTransport: " << error_message; state_ = kSessionClosed; if (fatal_error_callback_) { std::move(fatal_error_callback_)(error_message); fatal_error_callback_ = nullptr; } } void EncapsulatedSession::OnWriteError(absl::Status error) { OnFatalError(absl::StrCat( error, " while trying to write encapsulated WebTransport data")); } EncapsulatedSession::InnerStream::InnerStream(EncapsulatedSession* session, StreamId id) : session_(session), id_(id), read_side_closed_(IsUnidirectionalId(id) && IsIdOpenedBy(id, session->perspective_)), write_side_closed_(IsUnidirectionalId(id) && !IsIdOpenedBy(id, session->perspective_)) { if (!write_side_closed_) { absl::Status status = session_->scheduler_.Register(id_, kDefaultPriority); if (!status.ok()) { QUICHE_BUG(WT_H2_FailedToRegisterNewStream) << status; session_->OnFatalError( "Failed to register new stream with the scheduler"); return; } } } quiche::ReadStream::ReadResult EncapsulatedSession::InnerStream::Read( absl::Span<char> output) { const size_t total_size = output.size(); for (const IncomingRead& read : incoming_reads_) { size_t size_to_read = std::min(read.size(), output.size()); if (size_to_read == 0) { break; } memcpy(output.data(), read.data.data(), size_to_read); output = output.subspan(size_to_read); } bool fin_consumed = SkipBytes(total_size); return ReadResult{total_size, fin_consumed}; } quiche::ReadStream::ReadResult EncapsulatedSession::InnerStream::Read( std::string* output) { const size_t total_size = ReadableBytes(); const size_t initial_offset = output->size(); output->resize(initial_offset + total_size); return Read(absl::Span<char>(&((*output)[initial_offset]), total_size)); } size_t EncapsulatedSession::InnerStream::ReadableBytes() const { size_t total_size = 0; for (const IncomingRead& read : incoming_reads_) { total_size += read.size(); } return total_size; } quiche::ReadStream::PeekResult EncapsulatedSession::InnerStream::PeekNextReadableRegion() const { if (incoming_reads_.empty()) { return PeekResult{absl::string_view(), fin_received_, fin_received_}; } return PeekResult{incoming_reads_.front().data, fin_received_ && incoming_reads_.size() == 1, fin_received_}; } bool EncapsulatedSession::InnerStream::SkipBytes(size_t bytes) { size_t remaining = bytes; while (remaining > 0) { if (incoming_reads_.empty()) { QUICHE_BUG(WT_H2_SkipBytes_toomuch) << "Requested to skip " << remaining << " bytes that are not present in the read buffer."; return false; } IncomingRead& current = incoming_reads_.front(); if (remaining < current.size()) { current.data = current.data.substr(remaining); return false; } remaining -= current.size(); incoming_reads_.pop_front(); } if (incoming_reads_.empty() && fin_received_) { fin_consumed_ = true; CloseReadSide(std::nullopt); return true; } return false; } absl::Status EncapsulatedSession::InnerStream::Writev( const absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { if (write_side_closed_) { return absl::FailedPreconditionError( "Trying to write into an already-closed stream"); } if (fin_buffered_) { return absl::FailedPreconditionError("FIN already buffered"); } if (!CanWrite()) { return absl::FailedPreconditionError( "Trying to write into a stream when CanWrite() = false"); } const absl::StatusOr<bool> should_yield = session_->scheduler_.ShouldYield(id_); if (!should_yield.ok()) { QUICHE_BUG(WT_H2_Writev_NotRegistered) << should_yield.status(); session_->OnFatalError("Stream not registered with the scheduler"); return absl::InternalError("Stream not registered with the scheduler"); } const bool write_blocked = !session_->writer_->CanWrite() || *should_yield || !pending_write_.empty(); if (write_blocked) { fin_buffered_ = options.send_fin(); for (absl::string_view chunk : data) { absl::StrAppend(&pending_write_, chunk); } absl::Status status = session_->scheduler_.Schedule(id_); if (!status.ok()) { QUICHE_BUG(WT_H2_Writev_CantSchedule) << status; session_->OnFatalError("Could not schedule a write-blocked stream"); return absl::InternalError("Could not schedule a write-blocked stream"); } return absl::OkStatus(); } size_t bytes_written = WriteInner(data, options.send_fin()); QUICHE_DCHECK(bytes_written == 0 || bytes_written == quiche::TotalStringViewSpanSize(data)); if (bytes_written == 0) { for (absl::string_view chunk : data) { absl::StrAppend(&pending_write_, chunk); } } if (options.send_fin()) { CloseWriteSide(std::nullopt); } return absl::OkStatus(); } bool EncapsulatedSession::InnerStream::CanWrite() const { return session_->state_ != EncapsulatedSession::kSessionClosed && !write_side_closed_ && (pending_write_.size() <= session_->max_stream_data_buffered_); } void EncapsulatedSession::InnerStream::FlushPendingWrite() { QUICHE_DCHECK(!write_side_closed_); QUICHE_DCHECK(session_->writer_->CanWrite()); QUICHE_DCHECK(!pending_write_.empty()); absl::string_view to_write = pending_write_; size_t bytes_written = WriteInner(absl::MakeSpan(&to_write, 1), fin_buffered_); if (bytes_written < to_write.size()) { pending_write_ = pending_write_.substr(bytes_written); return; } pending_write_.clear(); if (fin_buffered_) { CloseWriteSide(std::nullopt); } if (!write_side_closed_ && visitor_ != nullptr) { visitor_->OnCanWrite(); } } size_t EncapsulatedSession::InnerStream::WriteInner( absl::Span<const absl::string_view> data, bool fin) { size_t total_size = quiche::TotalStringViewSpanSize(data); if (total_size == 0 && !fin) { session_->OnFatalError("Attempted to make an empty write with fin=false"); return 0; } quiche::QuicheBuffer header = quiche::SerializeWebTransportStreamCapsuleHeader(id_, fin, total_size, session_->allocator_); std::vector<absl::string_view> views_to_write; views_to_write.reserve(data.size() + 1); views_to_write.push_back(header.AsStringView()); absl::c_copy(data, std::back_inserter(views_to_write)); absl::Status write_status = session_->writer_->Writev( views_to_write, quiche::kDefaultStreamWriteOptions); if (!write_status.ok()) { session_->OnWriteError(write_status); return 0; } return total_size; } void EncapsulatedSession::InnerStream::AbruptlyTerminate(absl::Status error) { QUICHE_DLOG(INFO) << "Abruptly terminating the stream due to error: " << error; ResetDueToInternalError(); } void EncapsulatedSession::InnerStream::ResetWithUserCode( StreamErrorCode error) { if (reset_frame_sent_) { return; } reset_frame_sent_ = true; session_->SendControlCapsule( quiche::WebTransportResetStreamCapsule{id_, error}); CloseWriteSide(std::nullopt); } void EncapsulatedSession::InnerStream::SendStopSending(StreamErrorCode error) { if (stop_sending_sent_) { return; } stop_sending_sent_ = true; session_->SendControlCapsule( quiche::WebTransportStopSendingCapsule{id_, error}); CloseReadSide(std::nullopt); } void EncapsulatedSession::InnerStream::CloseReadSide( std::optional<StreamErrorCode> error) { if (read_side_closed_) { return; } read_side_closed_ = true; incoming_reads_.clear(); if (error.has_value() && visitor_ != nullptr) { visitor_->OnResetStreamReceived(*error); } if (CanBeGarbageCollected()) { session_->streams_to_garbage_collect_.push_back(id_); } } void EncapsulatedSession::InnerStream::CloseWriteSide( std::optional<StreamErrorCode> error) { if (write_side_closed_) { return; } write_side_closed_ = true; pending_write_.clear(); absl::Status status = session_->scheduler_.Unregister(id_); if (!status.ok()) { session_->OnFatalError("Failed to unregister closed stream"); return; } if (error.has_value() && visitor_ != nullptr) { visitor_->OnStopSendingReceived(*error); } if (CanBeGarbageCollected()) { session_->streams_to_garbage_collect_.push_back(id_); } } void EncapsulatedSession::GarbageCollectStreams() { for (StreamId id : streams_to_garbage_collect_) { streams_.erase(id); } streams_to_garbage_collect_.clear(); } void EncapsulatedSession::InnerStream::SetPriority( const StreamPriority& priority) { absl::Status status; status = session_->scheduler_.UpdateSendGroup(id_, priority.send_group_id); QUICHE_BUG_IF(EncapsulatedWebTransport_SetPriority_group, !status.ok()) << status; status = session_->scheduler_.UpdateSendOrder(id_, priority.send_order); QUICHE_BUG_IF(EncapsulatedWebTransport_SetPriority_order, !status.ok()) << status; } }
#include "quiche/web_transport/encapsulated/encapsulated_web_transport.h" #include <array> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/common/capsule.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_stream.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/mock_streams.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/web_transport/test_tools/mock_web_transport.h" #include "quiche/web_transport/web_transport.h" namespace webtransport::test { namespace { using ::quiche::Capsule; using ::quiche::CapsuleType; using ::quiche::test::StatusIs; using ::testing::_; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Return; using ::testing::StrEq; class EncapsulatedWebTransportTest : public quiche::test::QuicheTest, public quiche::CapsuleParser::Visitor { public: EncapsulatedWebTransportTest() : parser_(this), reader_(&read_buffer_) { ON_CALL(fatal_error_callback_, Call(_)) .WillByDefault([](absl::string_view error) { ADD_FAILURE() << "Fatal session error: " << error; }); ON_CALL(writer_, Writev(_, _)) .WillByDefault([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { for (absl::string_view fragment : data) { parser_.IngestCapsuleFragment(fragment); } writer_.ProcessOptions(options); return absl::OkStatus(); }); } std::unique_ptr<EncapsulatedSession> CreateTransport( Perspective perspective) { auto transport = std::make_unique<EncapsulatedSession>( perspective, fatal_error_callback_.AsStdFunction()); session_ = transport.get(); return transport; } std::unique_ptr<SessionVisitor> CreateAndStoreVisitor() { auto visitor = std::make_unique<testing::StrictMock<MockSessionVisitor>>(); visitor_ = visitor.get(); return visitor; } MOCK_METHOD(bool, OnCapsule, (const Capsule&), (override)); void OnCapsuleParseFailure(absl::string_view error_message) override { ADD_FAILURE() << "Written an invalid capsule: " << error_message; } void ProcessIncomingCapsule(const Capsule& capsule) { quiche::QuicheBuffer buffer = quiche::SerializeCapsule(capsule, quiche::SimpleBufferAllocator::Get()); read_buffer_.append(buffer.data(), buffer.size()); session_->OnCanRead(); } template <typename CapsuleType> void ProcessIncomingCapsule(const CapsuleType& capsule) { quiche::QuicheBuffer buffer = quiche::SerializeCapsule( quiche::Capsule(capsule), quiche::SimpleBufferAllocator::Get()); read_buffer_.append(buffer.data(), buffer.size()); session_->OnCanRead(); } void DefaultHandshakeForClient(EncapsulatedSession& session) { quiche::HttpHeaderBlock outgoing_headers, incoming_headers; session.InitializeClient(CreateAndStoreVisitor(), outgoing_headers, &writer_, &reader_); EXPECT_CALL(*visitor_, OnSessionReady()); session.ProcessIncomingServerHeaders(incoming_headers); } protected: quiche::CapsuleParser parser_; quiche::test::MockWriteStream writer_; std::string read_buffer_; quiche::test::ReadStreamFromString reader_; MockSessionVisitor* visitor_ = nullptr; EncapsulatedSession* session_ = nullptr; testing::MockFunction<void(absl::string_view)> fatal_error_callback_; }; TEST_F(EncapsulatedWebTransportTest, IsOpenedBy) { EXPECT_EQ(IsIdOpenedBy(0x00, Perspective::kClient), true); EXPECT_EQ(IsIdOpenedBy(0x01, Perspective::kClient), false); EXPECT_EQ(IsIdOpenedBy(0x02, Perspective::kClient), true); EXPECT_EQ(IsIdOpenedBy(0x03, Perspective::kClient), false); EXPECT_EQ(IsIdOpenedBy(0x00, Perspective::kServer), false); EXPECT_EQ(IsIdOpenedBy(0x01, Perspective::kServer), true); EXPECT_EQ(IsIdOpenedBy(0x02, Perspective::kServer), false); EXPECT_EQ(IsIdOpenedBy(0x03, Perspective::kServer), true); } TEST_F(EncapsulatedWebTransportTest, SetupClientSession) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); quiche::HttpHeaderBlock outgoing_headers, incoming_headers; EXPECT_EQ(session->state(), EncapsulatedSession::kUninitialized); session->InitializeClient(CreateAndStoreVisitor(), outgoing_headers, &writer_, &reader_); EXPECT_EQ(session->state(), EncapsulatedSession::kWaitingForHeaders); EXPECT_CALL(*visitor_, OnSessionReady()); session->ProcessIncomingServerHeaders(incoming_headers); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen); } TEST_F(EncapsulatedWebTransportTest, SetupServerSession) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kServer); quiche::HttpHeaderBlock outgoing_headers, incoming_headers; EXPECT_EQ(session->state(), EncapsulatedSession::kUninitialized); std::unique_ptr<SessionVisitor> visitor = CreateAndStoreVisitor(); EXPECT_CALL(*visitor_, OnSessionReady()); session->InitializeServer(std::move(visitor), outgoing_headers, incoming_headers, &writer_, &reader_); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen); } TEST_F(EncapsulatedWebTransportTest, CloseSession) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::CLOSE_WEBTRANSPORT_SESSION); EXPECT_EQ(capsule.close_web_transport_session_capsule().error_code, 0x1234); EXPECT_EQ(capsule.close_web_transport_session_capsule().error_message, "test close"); return true; }); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen); EXPECT_CALL(*visitor_, OnSessionClosed(0x1234, StrEq("test close"))); session->CloseSession(0x1234, "test close"); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionClosed); EXPECT_TRUE(writer_.fin_written()); EXPECT_CALL(fatal_error_callback_, Call(_)) .WillOnce([](absl::string_view error) { EXPECT_THAT(error, HasSubstr("close a session that is already closed")); }); session->CloseSession(0x1234, "test close"); } TEST_F(EncapsulatedWebTransportTest, CloseSessionWriteBlocked) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(false)); EXPECT_CALL(*this, OnCapsule(_)).Times(0); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen); session->CloseSession(0x1234, "test close"); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionClosing); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::CLOSE_WEBTRANSPORT_SESSION); EXPECT_EQ(capsule.close_web_transport_session_capsule().error_code, 0x1234); EXPECT_EQ(capsule.close_web_transport_session_capsule().error_message, "test close"); return true; }); EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(true)); EXPECT_CALL(*visitor_, OnSessionClosed(0x1234, StrEq("test close"))); session->OnCanWrite(); EXPECT_EQ(session->state(), EncapsulatedSession::kSessionClosed); EXPECT_TRUE(writer_.fin_written()); } TEST_F(EncapsulatedWebTransportTest, ReceiveFin) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnSessionClosed(0, IsEmpty())); reader_.set_fin(); session->OnCanRead(); EXPECT_TRUE(writer_.fin_written()); } TEST_F(EncapsulatedWebTransportTest, ReceiveCloseSession) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnSessionClosed(0x1234, StrEq("test"))); ProcessIncomingCapsule(Capsule::CloseWebTransportSession(0x1234, "test")); EXPECT_TRUE(writer_.fin_written()); reader_.set_fin(); session->OnCanRead(); } TEST_F(EncapsulatedWebTransportTest, ReceiveMalformedData) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(fatal_error_callback_, Call(HasSubstr("too much capsule data"))) .WillOnce([] {}); read_buffer_ = std::string(2 * 1024 * 1024, '\xff'); session->OnCanRead(); } TEST_F(EncapsulatedWebTransportTest, SendDatagrams) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), quiche::CapsuleType::DATAGRAM); EXPECT_EQ(capsule.datagram_capsule().http_datagram_payload, "test"); return true; }); DatagramStatus status = session->SendOrQueueDatagram("test"); EXPECT_EQ(status.code, DatagramStatusCode::kSuccess); } TEST_F(EncapsulatedWebTransportTest, SendDatagramsEarly) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); quiche::HttpHeaderBlock outgoing_headers; session->InitializeClient(CreateAndStoreVisitor(), outgoing_headers, &writer_, &reader_); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), quiche::CapsuleType::DATAGRAM); EXPECT_EQ(capsule.datagram_capsule().http_datagram_payload, "test"); return true; }); ASSERT_EQ(session->state(), EncapsulatedSession::kWaitingForHeaders); session->SendOrQueueDatagram("test"); } TEST_F(EncapsulatedWebTransportTest, SendDatagramsBeforeInitialization) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); quiche::HttpHeaderBlock outgoing_headers; EXPECT_CALL(*this, OnCapsule(_)).Times(0); ASSERT_EQ(session->state(), EncapsulatedSession::kUninitialized); session->SendOrQueueDatagram("test"); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::DATAGRAM); EXPECT_EQ(capsule.datagram_capsule().http_datagram_payload, "test"); return true; }); DefaultHandshakeForClient(*session); } TEST_F(EncapsulatedWebTransportTest, SendDatagramsTooBig) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*this, OnCapsule(_)).Times(0); std::string long_string(16 * 1024, 'a'); DatagramStatus status = session->SendOrQueueDatagram(long_string); EXPECT_EQ(status.code, DatagramStatusCode::kTooBig); } TEST_F(EncapsulatedWebTransportTest, ReceiveDatagrams) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnDatagramReceived(_)) .WillOnce([](absl::string_view data) { EXPECT_EQ(data, "test"); }); ProcessIncomingCapsule(Capsule::Datagram("test")); } TEST_F(EncapsulatedWebTransportTest, SendDraining) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::DRAIN_WEBTRANSPORT_SESSION); return true; }); session->NotifySessionDraining(); } TEST_F(EncapsulatedWebTransportTest, ReceiveDraining) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); testing::MockFunction<void()> callback; session->SetOnDraining(callback.AsStdFunction()); EXPECT_CALL(callback, Call()); ProcessIncomingCapsule(Capsule(quiche::DrainWebTransportSessionCapsule())); } TEST_F(EncapsulatedWebTransportTest, WriteErrorDatagram) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(writer_, Writev(_, _)) .WillOnce(Return(absl::InternalError("Test write error"))); EXPECT_CALL(fatal_error_callback_, Call(_)) .WillOnce([](absl::string_view error) { EXPECT_THAT(error, HasSubstr("Test write error")); }); DatagramStatus status = session->SendOrQueueDatagram("test"); EXPECT_EQ(status.code, DatagramStatusCode::kInternalError); } TEST_F(EncapsulatedWebTransportTest, WriteErrorControlCapsule) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(writer_, Writev(_, _)) .WillOnce(Return(absl::InternalError("Test write error"))); EXPECT_CALL(fatal_error_callback_, Call(_)) .WillOnce([](absl::string_view error) { EXPECT_THAT(error, HasSubstr("Test write error")); }); session->NotifySessionDraining(); } TEST_F(EncapsulatedWebTransportTest, SimpleRead) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); bool stream_received = false; EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()) .WillOnce([&] { stream_received = true; }); std::string data = "test"; ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, data, false}); data[0] = 'q'; EXPECT_TRUE(stream_received); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_EQ(stream->GetStreamId(), 1u); EXPECT_EQ(stream->visitor(), nullptr); EXPECT_EQ(stream->ReadableBytes(), 4u); quiche::ReadStream::PeekResult peek = stream->PeekNextReadableRegion(); EXPECT_EQ(peek.peeked_data, "test"); EXPECT_FALSE(peek.fin_next); EXPECT_FALSE(peek.all_data_received); std::string buffer; quiche::ReadStream::ReadResult read = stream->Read(&buffer); EXPECT_EQ(read.bytes_read, 4); EXPECT_FALSE(read.fin); EXPECT_EQ(buffer, "test"); EXPECT_EQ(stream->ReadableBytes(), 0u); } class MockStreamVisitorWithDestructor : public MockStreamVisitor { public: ~MockStreamVisitorWithDestructor() { OnDelete(); } MOCK_METHOD(void, OnDelete, (), ()); }; MockStreamVisitorWithDestructor* SetupVisitor(Stream& stream) { auto visitor = std::make_unique<MockStreamVisitorWithDestructor>(); MockStreamVisitorWithDestructor* result = visitor.get(); stream.SetVisitor(std::move(visitor)); return result; } TEST_F(EncapsulatedWebTransportTest, ImmediateRead) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); ProcessIncomingCapsule( quiche::WebTransportStreamDataCapsule{1, "abcd", false}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_EQ(stream->ReadableBytes(), 4u); MockStreamVisitor* visitor = SetupVisitor(*stream); EXPECT_CALL(*visitor, OnCanRead()).WillOnce([&] { std::string output; (void)stream->Read(&output); EXPECT_EQ(output, "abcdef"); }); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "ef", false}); } TEST_F(EncapsulatedWebTransportTest, FinPeek) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); ProcessIncomingCapsule( quiche::WebTransportStreamDataCapsule{1, "abcd", false}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_EQ(stream->ReadableBytes(), 4u); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "ef", true}); quiche::ReadStream::PeekResult peek = stream->PeekNextReadableRegion(); EXPECT_EQ(peek.peeked_data, "abcd"); EXPECT_FALSE(peek.fin_next); EXPECT_TRUE(peek.all_data_received); EXPECT_FALSE(stream->SkipBytes(2)); peek = stream->PeekNextReadableRegion(); EXPECT_FALSE(peek.fin_next); EXPECT_TRUE(peek.all_data_received); EXPECT_FALSE(stream->SkipBytes(2)); peek = stream->PeekNextReadableRegion(); EXPECT_EQ(peek.peeked_data, "ef"); EXPECT_TRUE(peek.fin_next); EXPECT_TRUE(peek.all_data_received); EXPECT_TRUE(stream->SkipBytes(2)); } TEST_F(EncapsulatedWebTransportTest, FinRead) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); ProcessIncomingCapsule( quiche::WebTransportStreamDataCapsule{1, "abcdef", true}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_EQ(stream->ReadableBytes(), 6u); std::array<char, 3> buffer; quiche::ReadStream::ReadResult read = stream->Read(absl::MakeSpan(buffer)); EXPECT_THAT(buffer, ElementsAre('a', 'b', 'c')); EXPECT_EQ(read.bytes_read, 3); EXPECT_FALSE(read.fin); read = stream->Read(absl::MakeSpan(buffer)); EXPECT_THAT(buffer, ElementsAre('d', 'e', 'f')); EXPECT_EQ(read.bytes_read, 3); EXPECT_TRUE(read.fin); } TEST_F(EncapsulatedWebTransportTest, LargeRead) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{ 1, std::string(64 * 1024, 'a'), true}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_EQ(stream->ReadableBytes(), 65536u); for (int i = 0; i < 64; i++) { std::array<char, 1024> buffer; quiche::ReadStream::ReadResult read = stream->Read(absl::MakeSpan(buffer)); EXPECT_EQ(read.bytes_read, 1024); EXPECT_EQ(read.fin, i == 63); } } TEST_F(EncapsulatedWebTransportTest, DoubleFinReceived) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "abc", true}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_CALL(fatal_error_callback_, Call(_)) .WillOnce([](absl::string_view error) { EXPECT_THAT(error, HasSubstr("has already received a FIN")); }); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "def", true}); } TEST_F(EncapsulatedWebTransportTest, CanWriteUnidiBidi) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "abc", true}); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "abc", true}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_TRUE(stream->CanWrite()); stream = session->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_FALSE(stream->CanWrite()); stream = session->OpenOutgoingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_TRUE(stream->CanWrite()); stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_TRUE(stream->CanWrite()); } TEST_F(EncapsulatedWebTransportTest, ReadOnlyGarbageCollection) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "abc", true}); Stream* stream = session->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_TRUE(stream->SkipBytes(3)); MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream); bool deleted = false; EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; }); session->GarbageCollectStreams(); EXPECT_TRUE(deleted); } TEST_F(EncapsulatedWebTransportTest, WriteOnlyGarbageCollection) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream); bool deleted = false; EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; }); EXPECT_CALL(*this, OnCapsule(_)).WillOnce(Return(true)); quiche::StreamWriteOptions options; options.set_send_fin(true); EXPECT_THAT(stream->Writev(absl::Span<const absl::string_view>(), options), StatusIs(absl::StatusCode::kOk)); session->GarbageCollectStreams(); EXPECT_TRUE(deleted); } TEST_F(EncapsulatedWebTransportTest, SimpleWrite) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "", true}); Stream* stream = session->AcceptIncomingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM); EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 1u); EXPECT_EQ(capsule.web_transport_stream_data().fin, false); EXPECT_EQ(capsule.web_transport_stream_data().data, "test"); return true; }); absl::Status status = quiche::WriteIntoStream(*stream, "test"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); } TEST_F(EncapsulatedWebTransportTest, WriteWithFin) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM_WITH_FIN); EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u); EXPECT_EQ(capsule.web_transport_stream_data().fin, true); EXPECT_EQ(capsule.web_transport_stream_data().data, "test"); return true; }); quiche::StreamWriteOptions options; options.set_send_fin(true); EXPECT_TRUE(stream->CanWrite()); absl::Status status = quiche::WriteIntoStream(*stream, "test", options); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); EXPECT_FALSE(stream->CanWrite()); } TEST_F(EncapsulatedWebTransportTest, FinOnlyWrite) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM_WITH_FIN); EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u); EXPECT_EQ(capsule.web_transport_stream_data().fin, true); EXPECT_EQ(capsule.web_transport_stream_data().data, ""); return true; }); quiche::StreamWriteOptions options; options.set_send_fin(true); EXPECT_TRUE(stream->CanWrite()); absl::Status status = stream->Writev(absl::Span<const absl::string_view>(), options); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); EXPECT_FALSE(stream->CanWrite()); } TEST_F(EncapsulatedWebTransportTest, BufferedWriteThenUnbuffer) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(false)); absl::Status status = quiche::WriteIntoStream(*stream, "abc"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); EXPECT_TRUE(stream->CanWrite()); EXPECT_CALL(writer_, CanWrite()).WillRepeatedly(Return(true)); status = quiche::WriteIntoStream(*stream, "def"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM); EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u); EXPECT_EQ(capsule.web_transport_stream_data().data, "abcdef"); return true; }); session_->OnCanWrite(); } TEST_F(EncapsulatedWebTransportTest, BufferedWriteThenFlush) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_CALL(writer_, CanWrite()).Times(2).WillRepeatedly(Return(false)); absl::Status status = quiche::WriteIntoStream(*stream, "abc"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); status = quiche::WriteIntoStream(*stream, "def"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); EXPECT_CALL(writer_, CanWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM); EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u); EXPECT_EQ(capsule.web_transport_stream_data().data, "abcdef"); return true; }); session_->OnCanWrite(); } TEST_F(EncapsulatedWebTransportTest, BufferedStreamBlocksAnother) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream1 = session->OpenOutgoingUnidirectionalStream(); Stream* stream2 = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream1 != nullptr); ASSERT_TRUE(stream2 != nullptr); EXPECT_CALL(*this, OnCapsule(_)).Times(0); EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(false)); absl::Status status = quiche::WriteIntoStream(*stream1, "abc"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); EXPECT_CALL(writer_, CanWrite()).WillRepeatedly(Return(true)); status = quiche::WriteIntoStream(*stream2, "abc"); EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk)); std::vector<StreamId> writes; EXPECT_CALL(*this, OnCapsule(_)).WillRepeatedly([&](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM); writes.push_back(capsule.web_transport_stream_data().stream_id); return true; }); session_->OnCanWrite(); EXPECT_THAT(writes, ElementsAre(2, 6)); } TEST_F(EncapsulatedWebTransportTest, SendReset) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([&](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_RESET_STREAM); EXPECT_EQ(capsule.web_transport_reset_stream().stream_id, 2u); EXPECT_EQ(capsule.web_transport_reset_stream().error_code, 1234u); return true; }); stream->ResetWithUserCode(1234u); bool deleted = false; EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; }); session->GarbageCollectStreams(); EXPECT_TRUE(deleted); } TEST_F(EncapsulatedWebTransportTest, ReceiveReset) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "", true}); Stream* stream = session->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream); EXPECT_CALL(*visitor, OnResetStreamReceived(1234u)); EXPECT_TRUE(session->GetStreamById(3) != nullptr); ProcessIncomingCapsule(quiche::WebTransportResetStreamCapsule{3u, 1234u}); EXPECT_TRUE(session->GetStreamById(3) == nullptr); } TEST_F(EncapsulatedWebTransportTest, SendStopSending) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable()); ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "", true}); Stream* stream = session->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream); EXPECT_CALL(*this, OnCapsule(_)).WillOnce([&](const Capsule& capsule) { EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STOP_SENDING); EXPECT_EQ(capsule.web_transport_stop_sending().stream_id, 3u); EXPECT_EQ(capsule.web_transport_stop_sending().error_code, 1234u); return true; }); stream->SendStopSending(1234u); bool deleted = false; EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; }); session->GarbageCollectStreams(); EXPECT_TRUE(deleted); } TEST_F(EncapsulatedWebTransportTest, ReceiveStopSending) { std::unique_ptr<EncapsulatedSession> session = CreateTransport(Perspective::kClient); DefaultHandshakeForClient(*session); Stream* stream = session->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream); EXPECT_CALL(*visitor, OnStopSendingReceived(1234u)); EXPECT_TRUE(session->GetStreamById(2) != nullptr); ProcessIncomingCapsule(quiche::WebTransportStopSendingCapsule{2u, 1234u}); EXPECT_TRUE(session->GetStreamById(2) == nullptr); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/web_transport/encapsulated/encapsulated_web_transport.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/web_transport/encapsulated/encapsulated_web_transport_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
15dff040-9d15-4863-8bdf-21b9008d68d1
cpp
google/quiche
balsa_frame
quiche/balsa/balsa_frame.cc
quiche/balsa/balsa_frame_test.cc
#include "quiche/balsa/balsa_frame.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <limits> #include <memory> #include <string> #include <utility> #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" #include "quiche/balsa/balsa_enums.h" #include "quiche/balsa/balsa_headers.h" #include "quiche/balsa/balsa_visitor_interface.h" #include "quiche/balsa/header_properties.h" #include "quiche/common/platform/api/quiche_logging.h" #define CHAR_LT(a, b) \ (static_cast<unsigned char>(a) < static_cast<unsigned char>(b)) #define CHAR_LE(a, b) \ (static_cast<unsigned char>(a) <= static_cast<unsigned char>(b)) #define CHAR_GT(a, b) \ (static_cast<unsigned char>(a) > static_cast<unsigned char>(b)) #define CHAR_GE(a, b) \ (static_cast<unsigned char>(a) >= static_cast<unsigned char>(b)) #define QUICHE_DCHECK_CHAR_GE(a, b) \ QUICHE_DCHECK_GE(static_cast<unsigned char>(a), static_cast<unsigned char>(b)) namespace quiche { namespace { using FirstLineValidationOption = HttpValidationPolicy::FirstLineValidationOption; constexpr size_t kContinueStatusCode = 100; constexpr size_t kSwitchingProtocolsStatusCode = 101; constexpr absl::string_view kChunked = "chunked"; constexpr absl::string_view kContentLength = "content-length"; constexpr absl::string_view kIdentity = "identity"; constexpr absl::string_view kTransferEncoding = "transfer-encoding"; bool IsInterimResponse(size_t response_code) { return response_code >= 100 && response_code < 200; } bool IsObsTextChar(char c) { return static_cast<uint8_t>(c) >= 0x80; } } void BalsaFrame::Reset() { last_char_was_slash_r_ = false; saw_non_newline_char_ = false; start_was_space_ = true; chunk_length_character_extracted_ = false; allow_reading_until_close_for_request_ = false; chunk_length_remaining_ = 0; content_length_remaining_ = 0; last_slash_n_idx_ = 0; term_chars_ = 0; parse_state_ = BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE; last_error_ = BalsaFrameEnums::BALSA_NO_ERROR; lines_.clear(); if (continue_headers_ != nullptr) { continue_headers_->Clear(); } if (headers_ != nullptr) { headers_->Clear(); } trailer_lines_.clear(); start_of_trailer_line_ = 0; trailer_length_ = 0; if (trailers_ != nullptr) { trailers_->Clear(); } is_valid_target_uri_ = true; } namespace { inline char* ParseOneIsland(char* current, char* begin, char* end, size_t* first_whitespace, size_t* first_nonwhite) { *first_whitespace = current - begin; while (current < end && CHAR_LE(*current, ' ')) { ++current; } *first_nonwhite = current - begin; while (current < end && CHAR_GT(*current, ' ')) { ++current; } return current; } } bool ParseHTTPFirstLine(char* begin, char* end, bool is_request, BalsaHeaders* headers, BalsaFrameEnums::ErrorCode* error_code, FirstLineValidationOption whitespace_option) { while (begin < end && (end[-1] == '\n' || end[-1] == '\r')) { --end; } if (whitespace_option != FirstLineValidationOption::NONE) { constexpr absl::string_view kBadWhitespace = "\r\t"; char* pos = std::find_first_of(begin, end, kBadWhitespace.begin(), kBadWhitespace.end()); if (pos != end) { if (whitespace_option == FirstLineValidationOption::REJECT) { *error_code = static_cast<BalsaFrameEnums::ErrorCode>( BalsaFrameEnums::INVALID_WS_IN_STATUS_LINE + static_cast<int>(is_request)); return false; } QUICHE_DCHECK(whitespace_option == FirstLineValidationOption::SANITIZE); std::replace_if( pos, end, [](char c) { return c == '\r' || c == '\t'; }, ' '); } } char* current = ParseOneIsland(begin, begin, end, &headers->whitespace_1_idx_, &headers->non_whitespace_1_idx_); current = ParseOneIsland(current, begin, end, &headers->whitespace_2_idx_, &headers->non_whitespace_2_idx_); current = ParseOneIsland(current, begin, end, &headers->whitespace_3_idx_, &headers->non_whitespace_3_idx_); const char* last = end; while (current <= last && CHAR_LE(*last, ' ')) { --last; } headers->whitespace_4_idx_ = last - begin + 1; QUICHE_DCHECK(begin == end || static_cast<unsigned char>(*begin) > ' '); QUICHE_DCHECK_EQ(0u, headers->whitespace_1_idx_); QUICHE_DCHECK_EQ(0u, headers->non_whitespace_1_idx_); QUICHE_DCHECK(begin == end || headers->non_whitespace_1_idx_ < headers->whitespace_2_idx_); if (headers->non_whitespace_2_idx_ == headers->whitespace_3_idx_) { *error_code = static_cast<BalsaFrameEnums::ErrorCode>( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION + static_cast<int>(is_request)); if (!is_request) { return false; } } if (headers->whitespace_3_idx_ == headers->non_whitespace_3_idx_) { if (*error_code == BalsaFrameEnums::BALSA_NO_ERROR) { *error_code = static_cast<BalsaFrameEnums::ErrorCode>( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE + static_cast<int>(is_request)); } } if (!is_request) { headers->parsed_response_code_ = 0; if (headers->non_whitespace_2_idx_ < headers->whitespace_3_idx_) { if (!absl::SimpleAtoi( absl::string_view(begin + headers->non_whitespace_2_idx_, headers->non_whitespace_3_idx_ - headers->non_whitespace_2_idx_), &headers->parsed_response_code_)) { *error_code = BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT; return false; } } } return true; } namespace { bool IsValidTargetUri(absl::string_view method, absl::string_view target_uri) { if (target_uri.empty()) { QUICHE_CODE_COUNT(invalid_target_uri_empty); return false; } if (target_uri == "*") { if (method == "OPTIONS") { return true; } QUICHE_CODE_COUNT(invalid_target_uri_asterisk_not_options); return false; } if (method == "CONNECT") { size_t index = target_uri.find_last_of(':'); if (index == absl::string_view::npos || index == 0) { QUICHE_CODE_COUNT(invalid_target_uri_connect_missing_port); return false; } if (target_uri[0] == '[' && target_uri[index - 1] != ']') { QUICHE_CODE_COUNT(invalid_target_uri_connect_bad_v6_literal); return false; } int port; if (!absl::SimpleAtoi(target_uri.substr(index + 1), &port) || port < 0 || port > 65535) { QUICHE_CODE_COUNT(invalid_target_uri_connect_bad_port); return false; } return true; } if (target_uri[0] == '/' || absl::StrContains(target_uri, ": return true; } QUICHE_CODE_COUNT(invalid_target_uri_bad_path); return false; } } void BalsaFrame::ProcessFirstLine(char* begin, char* end) { BalsaFrameEnums::ErrorCode previous_error = last_error_; if (!ParseHTTPFirstLine( begin, end, is_request_, headers_, &last_error_, http_validation_policy().sanitize_cr_tab_in_first_line)) { parse_state_ = BalsaFrameEnums::ERROR; HandleError(last_error_); return; } if (previous_error != last_error_) { HandleWarning(last_error_); } const absl::string_view line_input( begin + headers_->non_whitespace_1_idx_, headers_->whitespace_4_idx_ - headers_->non_whitespace_1_idx_); const absl::string_view part1( begin + headers_->non_whitespace_1_idx_, headers_->whitespace_2_idx_ - headers_->non_whitespace_1_idx_); const absl::string_view part2( begin + headers_->non_whitespace_2_idx_, headers_->whitespace_3_idx_ - headers_->non_whitespace_2_idx_); const absl::string_view part3( begin + headers_->non_whitespace_3_idx_, headers_->whitespace_4_idx_ - headers_->non_whitespace_3_idx_); if (is_request_) { is_valid_target_uri_ = IsValidTargetUri(part1, part2); if (http_validation_policy().disallow_invalid_target_uris && !is_valid_target_uri_) { parse_state_ = BalsaFrameEnums::ERROR; last_error_ = BalsaFrameEnums::INVALID_TARGET_URI; HandleError(last_error_); return; } visitor_->OnRequestFirstLineInput(line_input, part1, part2, part3); if (part3.empty()) { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; } return; } visitor_->OnResponseFirstLineInput(line_input, part1, part2, part3); } void BalsaFrame::CleanUpKeyValueWhitespace( const char* stream_begin, const char* line_begin, const char* current, const char* line_end, HeaderLineDescription* current_header_line) { const char* colon_loc = current; QUICHE_DCHECK_LT(colon_loc, line_end); QUICHE_DCHECK_EQ(':', *colon_loc); QUICHE_DCHECK_EQ(':', *current); QUICHE_DCHECK_CHAR_GE(' ', *line_end) << "\"" << std::string(line_begin, line_end) << "\""; --current; while (current > line_begin && CHAR_LE(*current, ' ')) { --current; } current += static_cast<int>(current != colon_loc); current_header_line->key_end_idx = current - stream_begin; current = colon_loc; QUICHE_DCHECK_EQ(':', *current); ++current; while (current < line_end && CHAR_LE(*current, ' ')) { ++current; } current_header_line->value_begin_idx = current - stream_begin; QUICHE_DCHECK_GE(current_header_line->key_end_idx, current_header_line->first_char_idx); QUICHE_DCHECK_GE(current_header_line->value_begin_idx, current_header_line->key_end_idx); QUICHE_DCHECK_GE(current_header_line->last_char_idx, current_header_line->value_begin_idx); } bool BalsaFrame::FindColonsAndParseIntoKeyValue(const Lines& lines, bool is_trailer, BalsaHeaders* headers) { QUICHE_DCHECK(!lines.empty()); const char* stream_begin = headers->OriginalHeaderStreamBegin(); const Lines::size_type lines_size_m1 = lines.size() - 1; int first_header_idx = (is_trailer ? 0 : 1); const char* current = stream_begin + lines[first_header_idx].first; for (Lines::size_type i = first_header_idx; i < lines_size_m1;) { const char* line_begin = stream_begin + lines[i].first; for (++i; i < lines_size_m1; ++i) { const char c = *(stream_begin + lines[i].first); if (CHAR_GT(c, ' ')) { break; } if ((c != ' ' && c != '\t') || http_validation_policy().disallow_header_continuation_lines) { HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_FORMAT : BalsaFrameEnums::INVALID_HEADER_FORMAT); return false; } } const char* line_end = stream_begin + lines[i - 1].second; QUICHE_DCHECK_LT(line_begin - stream_begin, line_end - stream_begin); --line_end; QUICHE_DCHECK_EQ('\n', *line_end) << "\"" << std::string(line_begin, line_end) << "\""; while (CHAR_LE(*line_end, ' ') && line_end > line_begin) { --line_end; } ++line_end; QUICHE_DCHECK_CHAR_GE(' ', *line_end); QUICHE_DCHECK_LT(line_begin, line_end); headers->header_lines_.push_back(HeaderLineDescription( line_begin - stream_begin, line_end - stream_begin, line_end - stream_begin, line_end - stream_begin, 0)); if (current >= line_end) { if (http_validation_policy().require_header_colon) { HandleError(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON : BalsaFrameEnums::HEADER_MISSING_COLON); return false; } HandleWarning(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON : BalsaFrameEnums::HEADER_MISSING_COLON); continue; } if (current < line_begin) { current = line_begin; } for (; current < line_end; ++current) { const char c = *current; if (c == ':') { break; } if (http_validation_policy().disallow_double_quote_in_header_name) { if (header_properties::IsInvalidHeaderKeyChar(c)) { HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER : BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); return false; } } else if (header_properties::IsInvalidHeaderKeyCharAllowDoubleQuote(c)) { HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER : BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); return false; } if (http_validation_policy().disallow_obs_text_in_field_names && IsObsTextChar(c)) { HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER : BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); return false; } } if (current == line_end) { if (http_validation_policy().require_header_colon) { HandleError(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON : BalsaFrameEnums::HEADER_MISSING_COLON); return false; } HandleWarning(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON : BalsaFrameEnums::HEADER_MISSING_COLON); continue; } QUICHE_DCHECK_EQ(*current, ':'); QUICHE_DCHECK_LE(current - stream_begin, line_end - stream_begin); QUICHE_DCHECK_LE(stream_begin - stream_begin, current - stream_begin); HeaderLineDescription& current_header_line = headers->header_lines_.back(); current_header_line.key_end_idx = current - stream_begin; current_header_line.value_begin_idx = current_header_line.key_end_idx; if (current < line_end) { ++current_header_line.key_end_idx; CleanUpKeyValueWhitespace(stream_begin, line_begin, current, line_end, &current_header_line); } } return true; } void BalsaFrame::HandleWarning(BalsaFrameEnums::ErrorCode error_code) { last_error_ = error_code; visitor_->HandleWarning(last_error_); } void BalsaFrame::HandleError(BalsaFrameEnums::ErrorCode error_code) { last_error_ = error_code; parse_state_ = BalsaFrameEnums::ERROR; visitor_->HandleError(last_error_); } BalsaHeadersEnums::ContentLengthStatus BalsaFrame::ProcessContentLengthLine( HeaderLines::size_type line_idx, size_t* length) { const HeaderLineDescription& header_line = headers_->header_lines_[line_idx]; const char* stream_begin = headers_->OriginalHeaderStreamBegin(); const char* line_end = stream_begin + header_line.last_char_idx; const char* value_begin = (stream_begin + header_line.value_begin_idx); if (value_begin >= line_end) { QUICHE_DVLOG(1) << "invalid content-length -- no non-whitespace value data"; return BalsaHeadersEnums::INVALID_CONTENT_LENGTH; } *length = 0; while (value_begin < line_end) { if (*value_begin < '0' || *value_begin > '9') { QUICHE_DVLOG(1) << "invalid content-length - non numeric character detected"; return BalsaHeadersEnums::INVALID_CONTENT_LENGTH; } const size_t kMaxDiv10 = std::numeric_limits<size_t>::max() / 10; size_t length_x_10 = *length * 10; const size_t c = *value_begin - '0'; if (*length > kMaxDiv10 || (std::numeric_limits<size_t>::max() - length_x_10) < c) { QUICHE_DVLOG(1) << "content-length overflow"; return BalsaHeadersEnums::CONTENT_LENGTH_OVERFLOW; } *length = length_x_10 + c; ++value_begin; } QUICHE_DVLOG(1) << "content_length parsed: " << *length; return BalsaHeadersEnums::VALID_CONTENT_LENGTH; } void BalsaFrame::ProcessTransferEncodingLine(HeaderLines::size_type line_idx) { const HeaderLineDescription& header_line = headers_->header_lines_[line_idx]; const char* stream_begin = headers_->OriginalHeaderStreamBegin(); const absl::string_view transfer_encoding( stream_begin + header_line.value_begin_idx, header_line.last_char_idx - header_line.value_begin_idx); if (absl::EqualsIgnoreCase(transfer_encoding, kChunked)) { headers_->transfer_encoding_is_chunked_ = true; return; } if (absl::EqualsIgnoreCase(transfer_encoding, kIdentity)) { headers_->transfer_encoding_is_chunked_ = false; return; } if (http_validation_policy().validate_transfer_encoding) { HandleError(BalsaFrameEnums::UNKNOWN_TRANSFER_ENCODING); } } bool BalsaFrame::CheckHeaderLinesForInvalidChars(const Lines& lines, const BalsaHeaders* headers) { const char* stream_begin = headers->OriginalHeaderStreamBegin() + lines.front().first; const char* stream_end = headers->OriginalHeaderStreamBegin() + lines.back().second; bool found_invalid = false; for (const char* c = stream_begin; c < stream_end; c++) { if (header_properties::IsInvalidHeaderChar(*c)) { found_invalid = true; } if (*c == '\r' && http_validation_policy().disallow_lone_cr_in_request_headers && c + 1 < stream_end && *(c + 1) != '\n') { found_invalid = true; } } return found_invalid; } void BalsaFrame::ProcessHeaderLines(const Lines& lines, bool is_trailer, BalsaHeaders* headers) { QUICHE_DCHECK(!lines.empty()); QUICHE_DVLOG(1) << "******@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@**********\n"; if (invalid_chars_error_enabled() && CheckHeaderLinesForInvalidChars(lines, headers)) { HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER); return; } if (lines.size() <= (is_trailer ? 1 : 2)) { return; } HeaderLines::size_type content_length_idx = 0; HeaderLines::size_type transfer_encoding_idx = 0; const char* stream_begin = headers->OriginalHeaderStreamBegin(); if (!FindColonsAndParseIntoKeyValue(lines, is_trailer, headers)) { return; } const HeaderLines::size_type lines_size = headers->header_lines_.size(); for (HeaderLines::size_type i = 0; i < lines_size; ++i) { const HeaderLineDescription& line = headers->header_lines_[i]; const absl::string_view key(stream_begin + line.first_char_idx, line.key_end_idx - line.first_char_idx); QUICHE_DVLOG(2) << "[" << i << "]: " << key << " key_len: " << key.length(); if (key.empty() || key[0] == ' ') { parse_state_ = BalsaFrameEnums::ERROR; HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_FORMAT : BalsaFrameEnums::INVALID_HEADER_FORMAT); return; } if (is_trailer) { continue; } if (absl::EqualsIgnoreCase(key, kContentLength)) { size_t length = 0; BalsaHeadersEnums::ContentLengthStatus content_length_status = ProcessContentLengthLine(i, &length); if (content_length_idx == 0) { content_length_idx = i + 1; headers->content_length_status_ = content_length_status; headers->content_length_ = length; content_length_remaining_ = length; continue; } if ((headers->content_length_status_ != content_length_status) || ((headers->content_length_status_ == BalsaHeadersEnums::VALID_CONTENT_LENGTH) && (http_validation_policy().disallow_multiple_content_length || length != headers->content_length_))) { HandleError(BalsaFrameEnums::MULTIPLE_CONTENT_LENGTH_KEYS); return; } continue; } if (absl::EqualsIgnoreCase(key, kTransferEncoding)) { if (http_validation_policy().validate_transfer_encoding && transfer_encoding_idx != 0) { HandleError(BalsaFrameEnums::MULTIPLE_TRANSFER_ENCODING_KEYS); return; } transfer_encoding_idx = i + 1; } } if (!is_trailer) { if (http_validation_policy().validate_transfer_encoding && http_validation_policy() .disallow_transfer_encoding_with_content_length && content_length_idx != 0 && transfer_encoding_idx != 0) { HandleError(BalsaFrameEnums::BOTH_TRANSFER_ENCODING_AND_CONTENT_LENGTH); return; } if (headers->transfer_encoding_is_chunked_) { headers->content_length_ = 0; headers->content_length_status_ = BalsaHeadersEnums::NO_CONTENT_LENGTH; content_length_remaining_ = 0; } if (transfer_encoding_idx != 0) { ProcessTransferEncodingLine(transfer_encoding_idx - 1); } } } void BalsaFrame::AssignParseStateAfterHeadersHaveBeenParsed() { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; int response_code = headers_->parsed_response_code_; if (!is_request_ && (request_was_head_ || !BalsaHeaders::ResponseCanHaveBody(response_code))) { return; } if (headers_->transfer_encoding_is_chunked_) { parse_state_ = BalsaFrameEnums::READING_CHUNK_LENGTH; return; } switch (headers_->content_length_status_) { case BalsaHeadersEnums::VALID_CONTENT_LENGTH: if (headers_->content_length_ == 0) { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; } else { parse_state_ = BalsaFrameEnums::READING_CONTENT; } break; case BalsaHeadersEnums::CONTENT_LENGTH_OVERFLOW: case BalsaHeadersEnums::INVALID_CONTENT_LENGTH: HandleError(BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH); break; case BalsaHeadersEnums::NO_CONTENT_LENGTH: if (is_request_) { const absl::string_view method = headers_->request_method(); if ((method != "POST" && method != "PUT") || !http_validation_policy().require_content_length_if_body_required) { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; break; } else if (!allow_reading_until_close_for_request_) { HandleError(BalsaFrameEnums::REQUIRED_BODY_BUT_NO_CONTENT_LENGTH); break; } } parse_state_ = BalsaFrameEnums::READING_UNTIL_CLOSE; HandleWarning(BalsaFrameEnums::MAYBE_BODY_BUT_NO_CONTENT_LENGTH); break; default: QUICHE_LOG(FATAL) << "Saw a content_length_status: " << headers_->content_length_status_ << " which is unknown."; } } size_t BalsaFrame::ProcessHeaders(const char* message_start, size_t message_length) { const char* const original_message_start = message_start; const char* const message_end = message_start + message_length; const char* message_current = message_start; const char* checkpoint = message_start; if (message_length == 0) { return message_current - original_message_start; } while (message_current < message_end) { size_t base_idx = headers_->GetReadableBytesFromHeaderStream(); if (!saw_non_newline_char_) { do { const char c = *message_current; if (c != '\r' && c != '\n') { if (CHAR_LE(c, ' ')) { HandleError(BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST); return message_current - original_message_start; } break; } ++message_current; if (message_current == message_end) { return message_current - original_message_start; } } while (true); saw_non_newline_char_ = true; message_start = message_current; checkpoint = message_current; } while (message_current < message_end) { if (*message_current != '\n') { ++message_current; continue; } const size_t relative_idx = message_current - message_start; const size_t message_current_idx = 1 + base_idx + relative_idx; lines_.push_back(std::make_pair(last_slash_n_idx_, message_current_idx)); if (lines_.size() == 1) { headers_->WriteFromFramer(checkpoint, 1 + message_current - checkpoint); checkpoint = message_current + 1; char* begin = headers_->OriginalHeaderStreamBegin(); QUICHE_DVLOG(1) << "First line " << std::string(begin, lines_[0].second); QUICHE_DVLOG(1) << "is_request_: " << is_request_; ProcessFirstLine(begin, begin + lines_[0].second); if (parse_state_ == BalsaFrameEnums::MESSAGE_FULLY_READ) { break; } if (parse_state_ == BalsaFrameEnums::ERROR) { return message_current - original_message_start; } } const size_t chars_since_last_slash_n = (message_current_idx - last_slash_n_idx_); last_slash_n_idx_ = message_current_idx; if (chars_since_last_slash_n > 2) { ++message_current; continue; } if ((chars_since_last_slash_n == 1) || (((message_current > message_start) && (*(message_current - 1) == '\r')) || (last_char_was_slash_r_))) { break; } ++message_current; } if (message_current == message_end) { continue; } ++message_current; QUICHE_DCHECK(message_current >= message_start); if (message_current > message_start) { headers_->WriteFromFramer(checkpoint, message_current - checkpoint); } if (headers_->GetReadableBytesFromHeaderStream() > max_header_length_) { HandleHeadersTooLongError(); return message_current - original_message_start; } headers_->DoneWritingFromFramer(); visitor_->OnHeaderInput(headers_->GetReadablePtrFromHeaderStream()); ProcessHeaderLines(lines_, false , headers_); if (parse_state_ == BalsaFrameEnums::ERROR) { return message_current - original_message_start; } if (use_interim_headers_callback_ && IsInterimResponse(headers_->parsed_response_code()) && headers_->parsed_response_code() != kSwitchingProtocolsStatusCode) { visitor_->OnInterimHeaders( std::make_unique<BalsaHeaders>(std::move(*headers_))); Reset(); checkpoint = message_start = message_current; continue; } if (continue_headers_ != nullptr && headers_->parsed_response_code_ == kContinueStatusCode) { BalsaHeaders saved_continue_headers = std::move(*headers_); Reset(); *continue_headers_ = std::move(saved_continue_headers); visitor_->ContinueHeaderDone(); checkpoint = message_start = message_current; continue; } AssignParseStateAfterHeadersHaveBeenParsed(); if (parse_state_ == BalsaFrameEnums::ERROR) { return message_current - original_message_start; } visitor_->ProcessHeaders(*headers_); visitor_->HeaderDone(); if (parse_state_ == BalsaFrameEnums::MESSAGE_FULLY_READ) { visitor_->MessageDone(); } return message_current - original_message_start; } last_char_was_slash_r_ = (*(message_end - 1) == '\r'); QUICHE_DCHECK(message_current >= message_start); if (message_current > message_start) { headers_->WriteFromFramer(checkpoint, message_current - checkpoint); } return message_current - original_message_start; } size_t BalsaFrame::BytesSafeToSplice() const { switch (parse_state_) { case BalsaFrameEnums::READING_CHUNK_DATA: return chunk_length_remaining_; case BalsaFrameEnums::READING_UNTIL_CLOSE: return std::numeric_limits<size_t>::max(); case BalsaFrameEnums::READING_CONTENT: return content_length_remaining_; default: return 0; } } void BalsaFrame::BytesSpliced(size_t bytes_spliced) { switch (parse_state_) { case BalsaFrameEnums::READING_CHUNK_DATA: if (chunk_length_remaining_ < bytes_spliced) { HandleError(BalsaFrameEnums:: CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT); return; } chunk_length_remaining_ -= bytes_spliced; if (chunk_length_remaining_ == 0) { parse_state_ = BalsaFrameEnums::READING_CHUNK_TERM; } return; case BalsaFrameEnums::READING_UNTIL_CLOSE: return; case BalsaFrameEnums::READING_CONTENT: if (content_length_remaining_ < bytes_spliced) { HandleError(BalsaFrameEnums:: CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT); return; } content_length_remaining_ -= bytes_spliced; if (content_length_remaining_ == 0) { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; visitor_->MessageDone(); } return; default: HandleError(BalsaFrameEnums::CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO); return; } } size_t BalsaFrame::ProcessInput(const char* input, size_t size) { const char* current = input; const char* on_entry = current; const char* end = current + size; QUICHE_DCHECK(headers_ != nullptr); if (headers_ == nullptr) { return 0; } if (parse_state_ == BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE) { const size_t header_length = headers_->GetReadableBytesFromHeaderStream(); if (header_length > max_header_length_ || (header_length == max_header_length_ && size > 0)) { HandleHeadersTooLongError(); return current - input; } const size_t bytes_to_process = std::min(max_header_length_ - header_length, size); current += ProcessHeaders(input, bytes_to_process); if (parse_state_ == BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE) { const size_t header_length_after = headers_->GetReadableBytesFromHeaderStream(); if (header_length_after >= max_header_length_) { HandleHeadersTooLongError(); } } return current - input; } if (parse_state_ == BalsaFrameEnums::MESSAGE_FULLY_READ || parse_state_ == BalsaFrameEnums::ERROR) { return current - input; } QUICHE_DCHECK_LE(current, end); if (current == end) { return current - input; } while (true) { switch (parse_state_) { case BalsaFrameEnums::READING_CHUNK_LENGTH: QUICHE_DCHECK_LE(current, end); while (true) { if (current == end) { visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); return current - input; } const char c = *current; ++current; static const signed char kBad = -1; static const signed char kDelimiter = -2; signed char addition = kBad; switch (c) { case '0': addition = 0; break; case '1': addition = 1; break; case '2': addition = 2; break; case '3': addition = 3; break; case '4': addition = 4; break; case '5': addition = 5; break; case '6': addition = 6; break; case '7': addition = 7; break; case '8': addition = 8; break; case '9': addition = 9; break; case 'a': addition = 0xA; break; case 'b': addition = 0xB; break; case 'c': addition = 0xC; break; case 'd': addition = 0xD; break; case 'e': addition = 0xE; break; case 'f': addition = 0xF; break; case 'A': addition = 0xA; break; case 'B': addition = 0xB; break; case 'C': addition = 0xC; break; case 'D': addition = 0xD; break; case 'E': addition = 0xE; break; case 'F': addition = 0xF; break; case '\t': case '\n': case '\r': case ' ': case ';': addition = kDelimiter; break; default: break; } if (addition >= 0) { chunk_length_character_extracted_ = true; size_t length_x_16 = chunk_length_remaining_ * 16; const size_t kMaxDiv16 = std::numeric_limits<size_t>::max() / 16; if ((chunk_length_remaining_ > kMaxDiv16) || (std::numeric_limits<size_t>::max() - length_x_16) < static_cast<size_t>(addition)) { visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); HandleError(BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW); return current - input; } chunk_length_remaining_ = length_x_16 + addition; continue; } if (!chunk_length_character_extracted_ || addition == kBad) { visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); HandleError(BalsaFrameEnums::INVALID_CHUNK_LENGTH); return current - input; } break; } --current; parse_state_ = BalsaFrameEnums::READING_CHUNK_EXTENSION; last_char_was_slash_r_ = false; visitor_->OnChunkLength(chunk_length_remaining_); continue; case BalsaFrameEnums::READING_CHUNK_EXTENSION: { const char* extensions_start = current; size_t extensions_length = 0; QUICHE_DCHECK_LE(current, end); while (true) { if (current == end) { visitor_->OnChunkExtensionInput( absl::string_view(extensions_start, extensions_length)); visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); return current - input; } const char c = *current; if (http_validation_policy_.disallow_lone_cr_in_chunk_extension) { const bool cr_followed_by_non_lf = c == '\r' && current + 1 < end && *(current + 1) != '\n'; const bool previous_cr_followed_by_non_lf = last_char_was_slash_r_ && current == input && c != '\n'; if (cr_followed_by_non_lf || previous_cr_followed_by_non_lf) { HandleError(BalsaFrameEnums::INVALID_CHUNK_EXTENSION); return current - input; } if (current + 1 == end) { last_char_was_slash_r_ = c == '\r'; } } if (c == '\r' || c == '\n') { extensions_length = (extensions_start == current) ? 0 : current - extensions_start - 1; } ++current; if (c == '\n') { break; } } chunk_length_character_extracted_ = false; visitor_->OnChunkExtensionInput( absl::string_view(extensions_start, extensions_length)); if (chunk_length_remaining_ != 0) { parse_state_ = BalsaFrameEnums::READING_CHUNK_DATA; continue; } HeaderFramingFound('\n'); parse_state_ = BalsaFrameEnums::READING_LAST_CHUNK_TERM; continue; } case BalsaFrameEnums::READING_CHUNK_DATA: while (current < end) { if (chunk_length_remaining_ == 0) { break; } size_t bytes_remaining = end - current; size_t consumed_bytes = (chunk_length_remaining_ < bytes_remaining) ? chunk_length_remaining_ : bytes_remaining; const char* tmp_current = current + consumed_bytes; visitor_->OnRawBodyInput( absl::string_view(on_entry, tmp_current - on_entry)); visitor_->OnBodyChunkInput( absl::string_view(current, consumed_bytes)); on_entry = current = tmp_current; chunk_length_remaining_ -= consumed_bytes; } if (chunk_length_remaining_ == 0) { parse_state_ = BalsaFrameEnums::READING_CHUNK_TERM; continue; } visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); return current - input; case BalsaFrameEnums::READING_CHUNK_TERM: QUICHE_DCHECK_LE(current, end); while (true) { if (current == end) { visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); return current - input; } const char c = *current; ++current; if (c == '\n') { break; } } parse_state_ = BalsaFrameEnums::READING_CHUNK_LENGTH; continue; case BalsaFrameEnums::READING_LAST_CHUNK_TERM: QUICHE_DCHECK_LE(current, end); while (true) { if (current == end) { visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); return current - input; } const char c = *current; if (HeaderFramingFound(c) != 0) { ++current; parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); visitor_->MessageDone(); return current - input; } if (!HeaderFramingMayBeFound()) { break; } ++current; } parse_state_ = BalsaFrameEnums::READING_TRAILER; visitor_->OnRawBodyInput( absl::string_view(on_entry, current - on_entry)); on_entry = current; continue; case BalsaFrameEnums::READING_TRAILER: while (current < end) { const char c = *current; ++current; ++trailer_length_; if (trailers_ != nullptr) { if (trailer_length_ > max_header_length_) { --current; HandleError(BalsaFrameEnums::TRAILER_TOO_LONG); return current - input; } if (LineFramingFound(c)) { trailer_lines_.push_back( std::make_pair(start_of_trailer_line_, trailer_length_)); start_of_trailer_line_ = trailer_length_; } } if (HeaderFramingFound(c) != 0) { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; if (trailers_ != nullptr) { trailers_->WriteFromFramer(on_entry, current - on_entry); trailers_->DoneWritingFromFramer(); ProcessHeaderLines(trailer_lines_, true , trailers_.get()); if (parse_state_ == BalsaFrameEnums::ERROR) { return current - input; } visitor_->OnTrailers(std::move(trailers_)); trailers_ = std::make_unique<BalsaHeaders>(); } visitor_->OnTrailerInput( absl::string_view(on_entry, current - on_entry)); visitor_->MessageDone(); return current - input; } } if (trailers_ != nullptr) { trailers_->WriteFromFramer(on_entry, current - on_entry); } visitor_->OnTrailerInput( absl::string_view(on_entry, current - on_entry)); return current - input; case BalsaFrameEnums::READING_UNTIL_CLOSE: { const size_t bytes_remaining = end - current; if (bytes_remaining > 0) { visitor_->OnRawBodyInput(absl::string_view(current, bytes_remaining)); visitor_->OnBodyChunkInput( absl::string_view(current, bytes_remaining)); current += bytes_remaining; } return current - input; } case BalsaFrameEnums::READING_CONTENT: while ((content_length_remaining_ != 0u) && current < end) { const size_t bytes_remaining = end - current; const size_t consumed_bytes = (content_length_remaining_ < bytes_remaining) ? content_length_remaining_ : bytes_remaining; visitor_->OnRawBodyInput(absl::string_view(current, consumed_bytes)); visitor_->OnBodyChunkInput( absl::string_view(current, consumed_bytes)); current += consumed_bytes; content_length_remaining_ -= consumed_bytes; } if (content_length_remaining_ == 0) { parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ; visitor_->MessageDone(); } return current - input; default: QUICHE_LOG(FATAL) << "Unknown state: " << parse_state_ << " memory corruption?!"; } } } void BalsaFrame::HandleHeadersTooLongError() { if (parse_truncated_headers_even_when_headers_too_long_) { const size_t len = headers_->GetReadableBytesFromHeaderStream(); const char* stream_begin = headers_->OriginalHeaderStreamBegin(); if (last_slash_n_idx_ < len && stream_begin[last_slash_n_idx_] != '\r') { static const absl::string_view kTwoLineEnds = "\r\n\r\n"; headers_->WriteFromFramer(kTwoLineEnds.data(), kTwoLineEnds.size()); lines_.push_back(std::make_pair(last_slash_n_idx_, len + 2)); lines_.push_back(std::make_pair(len + 2, len + 4)); } ProcessHeaderLines(lines_, false, headers_); } HandleError(BalsaFrameEnums::HEADERS_TOO_LONG); } const int32_t BalsaFrame::kValidTerm1; const int32_t BalsaFrame::kValidTerm1Mask; const int32_t BalsaFrame::kValidTerm2; const int32_t BalsaFrame::kValidTerm2Mask; } #undef CHAR_LT #undef CHAR_LE #undef CHAR_GT #undef CHAR_GE #undef QUICHE_DCHECK_CHAR_GE
#include "quiche/balsa/balsa_frame.h" #include <stdlib.h> #include <cstdint> #include <limits> #include <map> #include <memory> #include <random> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "quiche/balsa/balsa_enums.h" #include "quiche/balsa/balsa_headers.h" #include "quiche/balsa/balsa_visitor_interface.h" #include "quiche/balsa/http_validation_policy.h" #include "quiche/balsa/noop_balsa_visitor.h" #include "quiche/balsa/simple_buffer.h" #include "quiche/common/platform/api/quiche_command_line_flags.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_flags.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::InSequence; using ::testing::IsEmpty; using ::testing::Mock; using ::testing::NiceMock; using ::testing::Pointee; using ::testing::Property; using ::testing::Range; using ::testing::StrEq; using ::testing::StrictMock; DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, randseed, "", "This is the seed for Pseudo-random number" " generator used when generating random messages for unittests"); namespace quiche::test { using RandomEngine = std::mt19937; class BalsaFrameTestPeer { public: static int32_t HeaderFramingFound(BalsaFrame* balsa_frame, char c) { return balsa_frame->HeaderFramingFound(c); } static void FindColonsAndParseIntoKeyValue(BalsaFrame* balsa_frame, const BalsaFrame::Lines& lines, bool is_trailer, BalsaHeaders* headers) { balsa_frame->FindColonsAndParseIntoKeyValue(lines, is_trailer, headers); } }; class BalsaHeadersTestPeer { public: static void WriteFromFramer(BalsaHeaders* headers, const char* ptr, size_t size) { headers->WriteFromFramer(ptr, size); } }; namespace { class TestSeed { public: TestSeed() : test_seed_(0), user_supplied_seed_(false) {} void Initialize(const std::string& seed_flag) { if (!seed_flag.empty()) { ASSERT_TRUE(absl::SimpleAtoi(seed_flag, &test_seed_)); user_supplied_seed_ = true; } } int GetSeed() const { int seed = (user_supplied_seed_ ? test_seed_ : testing::UnitTest::GetInstance()->random_seed()); QUICHE_LOG(INFO) << "**** The current seed is " << seed << " ****"; return seed; } private: int test_seed_; bool user_supplied_seed_; }; static bool RandomBool(RandomEngine& rng) { return rng() % 2 != 0; } std::string EscapeString(absl::string_view message) { return absl::StrReplaceAll( message, {{"\n", "\\\\n\n"}, {"\\r", "\\\\r"}, {"\\t", "\\\\t"}}); } char random_lws(RandomEngine& rng) { if (RandomBool(rng)) { return '\t'; } return ' '; } const char* random_line_term(RandomEngine& rng) { if (RandomBool(rng)) { return "\r\n"; } return "\n"; } void AppendRandomWhitespace(RandomEngine& rng, std::stringstream* s) { for (int i = 0; i < 1000 && RandomBool(rng); ++i) { *s << random_lws(rng); } } std::string CreateFirstLine(const char* tokens[3], const char* whitespace[4], const char* line_ending) { QUICHE_CHECK(tokens != nullptr); QUICHE_CHECK(whitespace != nullptr); QUICHE_CHECK(line_ending != nullptr); QUICHE_CHECK(std::string(line_ending) == "\n" || std::string(line_ending) == "\r\n") << "line_ending: " << EscapeString(line_ending); SimpleBuffer firstline_buffer; firstline_buffer.WriteString(whitespace[0]); for (int i = 0; i < 3; ++i) { firstline_buffer.WriteString(tokens[i]); firstline_buffer.WriteString(whitespace[i + 1]); } firstline_buffer.WriteString(line_ending); return std::string(firstline_buffer.GetReadableRegion()); } std::string CreateMessage(const char* firstline, const std::pair<std::string, std::string>* headers, size_t headers_len, const char* colon, const char* line_ending, const char* body) { SimpleBuffer request_buffer; request_buffer.WriteString(firstline); if (headers_len > 0) { QUICHE_CHECK(headers != nullptr); QUICHE_CHECK(colon != nullptr); } QUICHE_CHECK(line_ending != nullptr); QUICHE_CHECK(std::string(line_ending) == "\n" || std::string(line_ending) == "\r\n") << "line_ending: " << EscapeString(line_ending); QUICHE_CHECK(body != nullptr); for (size_t i = 0; i < headers_len; ++i) { bool only_whitespace_in_key = true; { const char* tmp_key = headers[i].first.c_str(); while (*tmp_key != '\0') { if (*tmp_key > ' ') { only_whitespace_in_key = false; break; } ++tmp_key; } } const char* tmp_colon = colon; if (only_whitespace_in_key) { while (*tmp_colon != ':') { ++tmp_colon; } } request_buffer.WriteString(headers[i].first); request_buffer.WriteString(tmp_colon); request_buffer.WriteString(headers[i].second); request_buffer.WriteString(line_ending); } request_buffer.WriteString(line_ending); request_buffer.WriteString(body); return std::string(request_buffer.GetReadableRegion()); } void VerifyRequestFirstLine(const char* tokens[3], const BalsaHeaders& headers) { EXPECT_EQ(tokens[0], headers.request_method()); EXPECT_EQ(tokens[1], headers.request_uri()); EXPECT_EQ(0u, headers.parsed_response_code()); EXPECT_EQ(tokens[2], headers.request_version()); } void VerifyResponseFirstLine(const char* tokens[3], size_t expected_response_code, const BalsaHeaders& headers) { EXPECT_EQ(tokens[0], headers.response_version()); EXPECT_EQ(tokens[1], headers.response_code()); EXPECT_EQ(expected_response_code, headers.parsed_response_code()); EXPECT_EQ(tokens[2], headers.response_reason_phrase()); } void VerifyHeaderLines( const std::pair<std::string, std::string>* expected_headers, size_t headers_len, const BalsaHeaders& headers) { BalsaHeaders::const_header_lines_iterator it = headers.lines().begin(); for (size_t i = 0; it != headers.lines().end(); ++it, ++i) { ASSERT_GT(headers_len, i); std::string actual_key; std::string actual_value; if (!it->first.empty()) { actual_key = std::string(it->first); } if (!it->second.empty()) { actual_value = std::string(it->second); } EXPECT_THAT(actual_key, StrEq(expected_headers[i].first)); EXPECT_THAT(actual_value, StrEq(expected_headers[i].second)); } EXPECT_TRUE(headers.lines().end() == it); } void FirstLineParsedCorrectlyHelper(const char* tokens[3], size_t expected_response_code, bool is_request, const char* whitespace) { BalsaHeaders headers; BalsaFrame framer; framer.set_is_request(is_request); framer.set_balsa_headers(&headers); const char* tmp_tokens[3] = {tokens[0], tokens[1], tokens[2]}; const char* tmp_whitespace[4] = {"", whitespace, whitespace, ""}; for (int j = 2; j >= 0; --j) { framer.Reset(); std::string firstline = CreateFirstLine(tmp_tokens, tmp_whitespace, "\n"); std::string message = CreateMessage(firstline.c_str(), nullptr, 0, nullptr, "\n", ""); SCOPED_TRACE(absl::StrFormat("input: \n%s", EscapeString(message))); EXPECT_GE(message.size(), framer.ProcessInput(message.data(), message.size())); if (is_request || j >= 1) { EXPECT_FALSE(framer.Error()); if (is_request) { EXPECT_TRUE(framer.MessageFullyRead()); } if (j == 0) { expected_response_code = 0; } if (is_request) { VerifyRequestFirstLine(tmp_tokens, *framer.headers()); } else { VerifyResponseFirstLine(tmp_tokens, expected_response_code, *framer.headers()); } } else { EXPECT_TRUE(framer.Error()); } tmp_tokens[j] = ""; tmp_whitespace[j] = ""; } } TEST(HTTPBalsaFrame, ParseStateToString) { EXPECT_STREQ("ERROR", BalsaFrameEnums::ParseStateToString(BalsaFrameEnums::ERROR)); EXPECT_STREQ("READING_HEADER_AND_FIRSTLINE", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE)); EXPECT_STREQ("READING_CHUNK_LENGTH", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_CHUNK_LENGTH)); EXPECT_STREQ("READING_CHUNK_EXTENSION", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_CHUNK_EXTENSION)); EXPECT_STREQ("READING_CHUNK_DATA", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_CHUNK_DATA)); EXPECT_STREQ("READING_CHUNK_TERM", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_CHUNK_TERM)); EXPECT_STREQ("READING_LAST_CHUNK_TERM", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_LAST_CHUNK_TERM)); EXPECT_STREQ("READING_TRAILER", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_TRAILER)); EXPECT_STREQ("READING_UNTIL_CLOSE", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_UNTIL_CLOSE)); EXPECT_STREQ("READING_CONTENT", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::READING_CONTENT)); EXPECT_STREQ("MESSAGE_FULLY_READ", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::MESSAGE_FULLY_READ)); EXPECT_STREQ("UNKNOWN_STATE", BalsaFrameEnums::ParseStateToString( BalsaFrameEnums::NUM_STATES)); EXPECT_STREQ("UNKNOWN_STATE", BalsaFrameEnums::ParseStateToString( static_cast<BalsaFrameEnums::ParseState>(-1))); for (int i = 0; i < BalsaFrameEnums::NUM_STATES; ++i) { EXPECT_STRNE("UNKNOWN_STATE", BalsaFrameEnums::ParseStateToString( static_cast<BalsaFrameEnums::ParseState>(i))); } } TEST(HTTPBalsaFrame, ErrorCodeToString) { EXPECT_STREQ("NO_STATUS_LINE_IN_RESPONSE", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::NO_STATUS_LINE_IN_RESPONSE)); EXPECT_STREQ("NO_REQUEST_LINE_IN_REQUEST", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST)); EXPECT_STREQ("FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION)); EXPECT_STREQ("FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD)); EXPECT_STREQ( "FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE)); EXPECT_STREQ( "FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI)); EXPECT_STREQ( "FAILED_TO_FIND_NL_AFTER_RESPONSE_REASON_PHRASE", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_TO_FIND_NL_AFTER_RESPONSE_REASON_PHRASE)); EXPECT_STREQ( "FAILED_TO_FIND_NL_AFTER_REQUEST_HTTP_VERSION", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_TO_FIND_NL_AFTER_REQUEST_HTTP_VERSION)); EXPECT_STREQ("FAILED_CONVERTING_STATUS_CODE_TO_INT", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT)); EXPECT_STREQ("HEADERS_TOO_LONG", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::HEADERS_TOO_LONG)); EXPECT_STREQ("UNPARSABLE_CONTENT_LENGTH", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH)); EXPECT_STREQ("MAYBE_BODY_BUT_NO_CONTENT_LENGTH", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::MAYBE_BODY_BUT_NO_CONTENT_LENGTH)); EXPECT_STREQ("HEADER_MISSING_COLON", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::HEADER_MISSING_COLON)); EXPECT_STREQ("INVALID_CHUNK_LENGTH", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::INVALID_CHUNK_LENGTH)); EXPECT_STREQ("CHUNK_LENGTH_OVERFLOW", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW)); EXPECT_STREQ("CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO)); EXPECT_STREQ("CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums:: CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT)); EXPECT_STREQ("MULTIPLE_CONTENT_LENGTH_KEYS", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::MULTIPLE_CONTENT_LENGTH_KEYS)); EXPECT_STREQ("MULTIPLE_TRANSFER_ENCODING_KEYS", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::MULTIPLE_TRANSFER_ENCODING_KEYS)); EXPECT_STREQ("INVALID_HEADER_FORMAT", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::INVALID_HEADER_FORMAT)); EXPECT_STREQ("INVALID_TRAILER_FORMAT", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::INVALID_TRAILER_FORMAT)); EXPECT_STREQ("TRAILER_TOO_LONG", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::TRAILER_TOO_LONG)); EXPECT_STREQ("TRAILER_MISSING_COLON", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::TRAILER_MISSING_COLON)); EXPECT_STREQ("INTERNAL_LOGIC_ERROR", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::INTERNAL_LOGIC_ERROR)); EXPECT_STREQ("INVALID_HEADER_CHARACTER", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::INVALID_HEADER_CHARACTER)); EXPECT_STREQ("UNKNOWN_ERROR", BalsaFrameEnums::ErrorCodeToString( BalsaFrameEnums::NUM_ERROR_CODES)); EXPECT_STREQ("UNKNOWN_ERROR", BalsaFrameEnums::ErrorCodeToString( static_cast<BalsaFrameEnums::ErrorCode>(-1))); for (int i = 0; i < BalsaFrameEnums::NUM_ERROR_CODES; ++i) { EXPECT_STRNE("UNKNOWN_ERROR", BalsaFrameEnums::ErrorCodeToString( static_cast<BalsaFrameEnums::ErrorCode>(i))); } } class FakeHeaders { public: struct KeyValuePair { KeyValuePair(const std::string& key, const std::string& value) : key(key), value(value) {} KeyValuePair() {} std::string key; std::string value; }; typedef std::vector<KeyValuePair> KeyValuePairs; KeyValuePairs key_value_pairs_; bool operator==(const FakeHeaders& other) const { if (key_value_pairs_.size() != other.key_value_pairs_.size()) { return false; } for (KeyValuePairs::size_type i = 0; i < key_value_pairs_.size(); ++i) { if (key_value_pairs_[i].key != other.key_value_pairs_[i].key) { return false; } if (key_value_pairs_[i].value != other.key_value_pairs_[i].value) { return false; } } return true; } void AddKeyValue(const std::string& key, const std::string& value) { key_value_pairs_.push_back(KeyValuePair(key, value)); } }; class BalsaVisitorMock : public BalsaVisitorInterface { public: ~BalsaVisitorMock() override = default; void ProcessHeaders(const BalsaHeaders& headers) override { FakeHeaders fake_headers; GenerateFakeHeaders(headers, &fake_headers); ProcessHeaders(fake_headers); } void OnTrailers(std::unique_ptr<BalsaHeaders> trailers) override { FakeHeaders fake_trailers; GenerateFakeHeaders(*trailers, &fake_trailers); OnTrailers(fake_trailers); } MOCK_METHOD(void, OnRawBodyInput, (absl::string_view input), (override)); MOCK_METHOD(void, OnBodyChunkInput, (absl::string_view input), (override)); MOCK_METHOD(void, OnHeaderInput, (absl::string_view input), (override)); MOCK_METHOD(void, OnTrailerInput, (absl::string_view input), (override)); MOCK_METHOD(void, ProcessHeaders, (const FakeHeaders& headers)); MOCK_METHOD(void, OnTrailers, (const FakeHeaders& trailers)); MOCK_METHOD(void, OnRequestFirstLineInput, (absl::string_view line_input, absl::string_view method_input, absl::string_view request_uri, absl::string_view version_input), (override)); MOCK_METHOD(void, OnResponseFirstLineInput, (absl::string_view line_input, absl::string_view version_input, absl::string_view status_input, absl::string_view reason_input), (override)); MOCK_METHOD(void, OnChunkLength, (size_t length), (override)); MOCK_METHOD(void, OnChunkExtensionInput, (absl::string_view input), (override)); MOCK_METHOD(void, OnInterimHeaders, (std::unique_ptr<BalsaHeaders> headers), (override)); MOCK_METHOD(void, ContinueHeaderDone, (), (override)); MOCK_METHOD(void, HeaderDone, (), (override)); MOCK_METHOD(void, MessageDone, (), (override)); MOCK_METHOD(void, HandleError, (BalsaFrameEnums::ErrorCode error_code), (override)); MOCK_METHOD(void, HandleWarning, (BalsaFrameEnums::ErrorCode error_code), (override)); private: static void GenerateFakeHeaders(const BalsaHeaders& headers, FakeHeaders* fake_headers) { for (const auto& line : headers.lines()) { fake_headers->AddKeyValue(std::string(line.first), std::string(line.second)); } } }; class HTTPBalsaFrameTest : public QuicheTest { protected: void SetUp() override { balsa_frame_.set_balsa_headers(&headers_); balsa_frame_.set_balsa_visitor(&visitor_mock_); balsa_frame_.set_is_request(true); balsa_frame_.EnableTrailers(); } void VerifyFirstLineParsing(const std::string& firstline, BalsaFrameEnums::ErrorCode error_code) { balsa_frame_.ProcessInput(firstline.data(), firstline.size()); EXPECT_EQ(error_code, balsa_frame_.ErrorCode()); } BalsaHeaders headers_; BalsaFrame balsa_frame_; NiceMock<BalsaVisitorMock> visitor_mock_; }; TEST_F(HTTPBalsaFrameTest, TestHeaderFramingFound) { EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, ' ')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r')); EXPECT_EQ(BalsaFrame::kValidTerm1, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\t')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r')); EXPECT_EQ(BalsaFrame::kValidTerm1, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, 'a')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(BalsaFrame::kValidTerm2, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '1')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(BalsaFrame::kValidTerm2, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, ':')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r')); EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n')); } TEST_F(HTTPBalsaFrameTest, MissingColonInTrailer) { const absl::string_view trailer = "kv\r\n\r\n"; BalsaFrame::Lines lines; lines.push_back({0, 4}); lines.push_back({4, trailer.length()}); BalsaHeaders trailers; BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(), trailer.length()); BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue( &balsa_frame_, lines, true , &trailers); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::TRAILER_MISSING_COLON, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FindColonsAndParseIntoKeyValueInTrailer) { const absl::string_view trailer_line1 = "Fraction: 0.23\r\n"; const absl::string_view trailer_line2 = "Some:junk \r\n"; const absl::string_view trailer_line3 = "\r\n"; const std::string trailer = absl::StrCat(trailer_line1, trailer_line2, trailer_line3); BalsaFrame::Lines lines; lines.push_back({0, trailer_line1.length()}); lines.push_back({trailer_line1.length(), trailer_line1.length() + trailer_line2.length()}); lines.push_back( {trailer_line1.length() + trailer_line2.length(), trailer.length()}); BalsaHeaders trailers; BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(), trailer.length()); BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue( &balsa_frame_, lines, true , &trailers); EXPECT_FALSE(balsa_frame_.Error()); absl::string_view fraction = trailers.GetHeader("Fraction"); EXPECT_EQ("0.23", fraction); absl::string_view some = trailers.GetHeader("Some"); EXPECT_EQ("junk", some); } TEST_F(HTTPBalsaFrameTest, InvalidTrailer) { const absl::string_view trailer_line1 = "Fraction : 0.23\r\n"; const absl::string_view trailer_line2 = "Some\t :junk \r\n"; const absl::string_view trailer_line3 = "\r\n"; const std::string trailer = absl::StrCat(trailer_line1, trailer_line2, trailer_line3); BalsaFrame::Lines lines; lines.push_back({0, trailer_line1.length()}); lines.push_back({trailer_line1.length(), trailer_line1.length() + trailer_line2.length()}); lines.push_back( {trailer_line1.length() + trailer_line2.length(), trailer.length()}); BalsaHeaders trailers; BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(), trailer.length()); BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue( &balsa_frame_, lines, true , &trailers); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, OneCharacterFirstLineParsedAsExpected) { VerifyFirstLineParsing( "a\r\n\r\n", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD); } TEST_F(HTTPBalsaFrameTest, OneCharacterFirstLineWithWhitespaceParsedAsExpected) { VerifyFirstLineParsing( "a \r\n\r\n", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD); } TEST_F(HTTPBalsaFrameTest, WhitespaceOnlyFirstLineIsNotACompleteHeader) { VerifyFirstLineParsing(" \n\n", BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST); } TEST(HTTPBalsaFrame, RequestFirstLineParsedCorrectly) { const char* request_tokens[3] = {"GET", "/jjsdjrqk", "HTTP/1.0"}; FirstLineParsedCorrectlyHelper(request_tokens, 0, true, " "); FirstLineParsedCorrectlyHelper(request_tokens, 0, true, "\t"); FirstLineParsedCorrectlyHelper(request_tokens, 0, true, "\t "); FirstLineParsedCorrectlyHelper(request_tokens, 0, true, " \t"); FirstLineParsedCorrectlyHelper(request_tokens, 0, true, " \t \t "); } TEST(HTTPBalsaFrame, RequestLineSanitizedProperly) { SCOPED_TRACE("Testing that the request line is properly sanitized."); using enum HttpValidationPolicy::FirstLineValidationOption; using FirstLineValidationOption = HttpValidationPolicy::FirstLineValidationOption; struct TestCase { const absl::string_view input; const absl::string_view parsed; FirstLineValidationOption option; BalsaFrameEnums::ErrorCode expected_error; }; const std::vector<TestCase> cases = { {"GET / HTTP/1.1\r\n", "GET / HTTP/1.1", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET / HTTP/1.1\r\n", "GET / HTTP/1.1", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET / HTTP/1.1\r\n", "GET / HTTP/1.1", REJECT, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET /\rHTTP/1.1\r\n", "GET /\rHTTP/1.1", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET /\rHTTP/1.1\r\n", "GET / HTTP/1.1", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET /\rHTTP/1.1\r\n", "", REJECT, BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE}, {"GET \t/ HTTP/1.1\r\n", "GET \t/ HTTP/1.1", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET \t/ HTTP/1.1\r\n", "GET / HTTP/1.1", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET \t/ HTTP/1.1\r\n", "", REJECT, BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE}, {"GET \t/\rHTTP/1.1 \r\n", "GET \t/\rHTTP/1.1", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET \t/\rHTTP/1.1 \r\n", "GET / HTTP/1.1", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"GET \t/\rHTTP/1.1 \r\n", "", REJECT, BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE}, }; const absl::string_view kHeaderLineAndEnding = "Foo: bar\r\n\r\n"; for (auto& [firstline, parsed, ws_option, expected_error] : cases) { SCOPED_TRACE( absl::StrCat("Input: ", absl::CEscape(firstline), " Expected output: ", absl::CEscape(parsed), " whitespace option: ", static_cast<int>(ws_option))); const std::string input = absl::StrCat(firstline, kHeaderLineAndEnding); BalsaHeaders headers; BalsaFrame framer; HttpValidationPolicy policy; policy.sanitize_cr_tab_in_first_line = ws_option; framer.set_http_validation_policy(policy); framer.set_is_request(true); framer.set_balsa_headers(&headers); framer.ProcessInput(input.data(), input.size()); EXPECT_EQ(headers.first_line(), parsed); EXPECT_EQ(framer.ErrorCode(), expected_error); } } TEST_F(HTTPBalsaFrameTest, NonnumericResponseCode) { balsa_frame_.set_is_request(false); VerifyFirstLineParsing("HTTP/1.1 0x3 Digits only\r\n\r\n", BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT); EXPECT_EQ("HTTP/1.1 0x3 Digits only", headers_.first_line()); } TEST_F(HTTPBalsaFrameTest, NegativeResponseCode) { balsa_frame_.set_is_request(false); VerifyFirstLineParsing("HTTP/1.1 -11 No sign allowed\r\n\r\n", BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT); EXPECT_EQ("HTTP/1.1 -11 No sign allowed", headers_.first_line()); } TEST_F(HTTPBalsaFrameTest, WithoutTrailingWhitespace) { balsa_frame_.set_is_request(false); VerifyFirstLineParsing( "HTTP/1.1 101\r\n\r\n", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE); EXPECT_EQ("HTTP/1.1 101", headers_.first_line()); } TEST_F(HTTPBalsaFrameTest, TrailingWhitespace) { balsa_frame_.set_is_request(false); std::string firstline = "HTTP/1.1 101 \r\n\r\n"; balsa_frame_.ProcessInput(firstline.data(), firstline.size()); EXPECT_EQ("HTTP/1.1 101 ", headers_.first_line()); } TEST(HTTPBalsaFrame, ResponseFirstLineParsedCorrectly) { const char* response_tokens[3] = {"HTTP/1.1", "200", "A reason\tphrase"}; FirstLineParsedCorrectlyHelper(response_tokens, 200, false, " "); FirstLineParsedCorrectlyHelper(response_tokens, 200, false, "\t"); FirstLineParsedCorrectlyHelper(response_tokens, 200, false, "\t "); FirstLineParsedCorrectlyHelper(response_tokens, 200, false, " \t"); FirstLineParsedCorrectlyHelper(response_tokens, 200, false, " \t \t "); response_tokens[1] = "312"; FirstLineParsedCorrectlyHelper(response_tokens, 312, false, " "); FirstLineParsedCorrectlyHelper(response_tokens, 312, false, "\t"); FirstLineParsedCorrectlyHelper(response_tokens, 312, false, "\t "); FirstLineParsedCorrectlyHelper(response_tokens, 312, false, " \t"); FirstLineParsedCorrectlyHelper(response_tokens, 312, false, " \t \t "); response_tokens[1] = "4242"; FirstLineParsedCorrectlyHelper(response_tokens, 4242, false, " "); FirstLineParsedCorrectlyHelper(response_tokens, 4242, false, "\t"); FirstLineParsedCorrectlyHelper(response_tokens, 4242, false, "\t "); FirstLineParsedCorrectlyHelper(response_tokens, 4242, false, " \t"); FirstLineParsedCorrectlyHelper(response_tokens, 4242, false, " \t \t "); } TEST(HTTPBalsaFrame, StatusLineSanitizedProperly) { SCOPED_TRACE("Testing that the status line is properly sanitized."); using enum HttpValidationPolicy::FirstLineValidationOption; using FirstLineValidationOption = HttpValidationPolicy::FirstLineValidationOption; struct TestCase { const absl::string_view input; const absl::string_view parsed; FirstLineValidationOption option; BalsaFrameEnums::ErrorCode expected_error; }; const std::vector<TestCase> cases = { {"HTTP/1.1 200 OK\r\n", "HTTP/1.1 200 OK", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 200 OK\r\n", "HTTP/1.1 200 OK", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 200 OK\r\n", "HTTP/1.1 200 OK", REJECT, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 200\rOK\r\n", "HTTP/1.1 200\rOK", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 200\rOK\r\n", "HTTP/1.1 200 OK", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 200\rOK\r\n", "", REJECT, BalsaFrameEnums::INVALID_WS_IN_STATUS_LINE}, {"HTTP/1.1 \t200 OK\r\n", "HTTP/1.1 \t200 OK", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 \t200 OK\r\n", "HTTP/1.1 200 OK", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 \t200 OK\r\n", "", REJECT, BalsaFrameEnums::INVALID_WS_IN_STATUS_LINE}, {"HTTP/1.1 \t200\rOK \r\n", "HTTP/1.1 \t200\rOK", NONE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 \t200\rOK \r\n", "HTTP/1.1 200 OK", SANITIZE, BalsaFrameEnums::BALSA_NO_ERROR}, {"HTTP/1.1 \t200\rOK \r\n", "", REJECT, BalsaFrameEnums::INVALID_WS_IN_STATUS_LINE}, }; const absl::string_view kHeaderLineAndEnding = "Foo: bar\r\nContent-Length: 0\r\n\r\n"; for (auto& [firstline, parsed, ws_option, expected_error] : cases) { SCOPED_TRACE( absl::StrCat("Input: ", absl::CEscape(firstline), " Expected output: ", absl::CEscape(parsed), " whitespace option: ", static_cast<int>(ws_option))); const std::string input = absl::StrCat(firstline, kHeaderLineAndEnding); BalsaHeaders headers; BalsaFrame framer; HttpValidationPolicy policy; policy.sanitize_cr_tab_in_first_line = ws_option; framer.set_http_validation_policy(policy); framer.set_is_request(false); framer.set_balsa_headers(&headers); framer.ProcessInput(input.data(), input.size()); EXPECT_EQ(headers.first_line(), parsed); EXPECT_EQ(framer.ErrorCode(), expected_error); } } void HeaderLineTestHelper(const char* firstline, bool is_request, const std::pair<std::string, std::string>* headers, size_t headers_len, const char* colon, const char* line_ending) { BalsaHeaders balsa_headers; BalsaFrame framer; framer.set_is_request(is_request); framer.set_balsa_headers(&balsa_headers); std::string message = CreateMessage(firstline, headers, headers_len, colon, line_ending, ""); SCOPED_TRACE(EscapeString(message)); size_t bytes_consumed = framer.ProcessInput(message.data(), message.size()); EXPECT_EQ(message.size(), bytes_consumed); VerifyHeaderLines(headers, headers_len, *framer.headers()); } TEST(HTTPBalsaFrame, RequestLinesParsedProperly) { SCOPED_TRACE("Testing that lines are properly parsed."); const char firstline[] = "GET / HTTP/1.1\r\n"; const std::pair<std::string, std::string> headers[] = { std::pair<std::string, std::string>("foo", "bar"), std::pair<std::string, std::string>("duck", "water"), std::pair<std::string, std::string>("goose", "neck"), std::pair<std::string, std::string>("key_is_fine", "value:includes:colons"), std::pair<std::string, std::string>("trucks", "along\rvalue\rincluding\rslash\rrs"), std::pair<std::string, std::string>("monster", "truck"), std::pair<std::string, std::string>("another_key", ":colons in value"), std::pair<std::string, std::string>("another_key", "colons in value:"), std::pair<std::string, std::string>("another_key", "value includes\r\n continuation"), std::pair<std::string, std::string>("key_without_continuations", "multiple\n in\r\n the\n value"), std::pair<std::string, std::string>("key_without_value", ""), std::pair<std::string, std::string>("", "value without key"), std::pair<std::string, std::string>("", ""), std::pair<std::string, std::string>("normal_key", "normal_value"), }; const size_t headers_len = ABSL_ARRAYSIZE(headers); HeaderLineTestHelper(firstline, true, headers, headers_len, ":", "\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ": ", "\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ": ", "\r\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t", "\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t", "\r\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t ", "\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t ", "\r\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t\t", "\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t\t", "\r\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t \t", "\n"); HeaderLineTestHelper(firstline, true, headers, headers_len, ":\t \t", "\r\n"); } TEST(HTTPBalsaFrame, CarriageReturnIllegalInHeaders) { HttpValidationPolicy policy{.disallow_lone_cr_in_request_headers = true}; BalsaHeaders balsa_headers; BalsaFrame framer; framer.set_is_request(true); framer.set_balsa_headers(&balsa_headers); framer.set_http_validation_policy(policy); framer.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::pair<std::string, std::string> headers[] = { std::pair<std::string, std::string>("foo", "bar"), std::pair<std::string, std::string>("trucks", "value-has-solo-\r-in it"), }; std::string message = CreateMessage("GET / \rHTTP/1.1\r\n", headers, 2, ":", "\r\n", ""); framer.ProcessInput(message.data(), message.size()); EXPECT_EQ(framer.ErrorCode(), BalsaFrameEnums::INVALID_HEADER_CHARACTER); } TEST(HTTPBalsaFrame, CarriageReturnIllegalInFirstLineOnInputBoundary) { HttpValidationPolicy policy{.disallow_lone_cr_in_request_headers = true}; BalsaHeaders balsa_headers; BalsaFrame framer; framer.set_is_request(true); framer.set_balsa_headers(&balsa_headers); framer.set_http_validation_policy(policy); framer.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); constexpr absl::string_view message1("GET / \r"); constexpr absl::string_view message2("HTTP/1.1\r\n\r\n"); EXPECT_EQ(message1.size(), framer.ProcessInput(message1.data(), message1.size())); EXPECT_EQ(message2.size(), framer.ProcessInput(message2.data(), message2.size())); EXPECT_EQ(framer.ErrorCode(), BalsaFrameEnums::INVALID_HEADER_CHARACTER); } TEST(HTTPBalsaFrame, CarriageReturnIllegalInHeaderValueOnInputBoundary) { HttpValidationPolicy policy{.disallow_lone_cr_in_request_headers = true}; BalsaHeaders balsa_headers; BalsaFrame framer; framer.set_is_request(true); framer.set_balsa_headers(&balsa_headers); framer.set_http_validation_policy(policy); framer.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); constexpr absl::string_view message1("GET / HTTP/1.1\r\nfoo: b\r"); constexpr absl::string_view message2("ar\r\n\r\n"); EXPECT_EQ(message1.size(), framer.ProcessInput(message1.data(), message1.size())); EXPECT_EQ(message2.size(), framer.ProcessInput(message2.data(), message2.size())); EXPECT_EQ(framer.ErrorCode(), BalsaFrameEnums::INVALID_HEADER_CHARACTER); } TEST(HTTPBalsaFrame, CarriageReturnIllegalInHeaderKey) { BalsaHeaders balsa_headers; BalsaFrame framer; framer.set_is_request(true); framer.set_balsa_headers(&balsa_headers); framer.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::pair<std::string, std::string> headers[] = { std::pair<std::string, std::string>("tru\rcks", "along"), }; std::string message = CreateMessage("GET / HTTP/1.1\r\n", headers, 1, ":", "\r\n", ""); framer.ProcessInput(message.data(), message.size()); EXPECT_EQ(framer.ErrorCode(), BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); } TEST(HTTPBalsaFrame, ResponseLinesParsedProperly) { SCOPED_TRACE("ResponseLineParsedProperly"); const char firstline[] = "HTTP/1.0 200 A reason\tphrase\r\n"; const std::pair<std::string, std::string> headers[] = { std::pair<std::string, std::string>("foo", "bar"), std::pair<std::string, std::string>("duck", "water"), std::pair<std::string, std::string>("goose", "neck"), std::pair<std::string, std::string>("key_is_fine", "value:includes:colons"), std::pair<std::string, std::string>("trucks", "along\rvalue\rincluding\rslash\rrs"), std::pair<std::string, std::string>("monster", "truck"), std::pair<std::string, std::string>("another_key", ":colons in value"), std::pair<std::string, std::string>("another_key", "colons in value:"), std::pair<std::string, std::string>("another_key", "value includes\r\n continuation"), std::pair<std::string, std::string>("key_includes_no_continuations", "multiple\n in\r\n the\n value"), std::pair<std::string, std::string>("key_without_value", ""), std::pair<std::string, std::string>("", "value without key"), std::pair<std::string, std::string>("", ""), std::pair<std::string, std::string>("normal_key", "normal_value"), }; const size_t headers_len = ABSL_ARRAYSIZE(headers); HeaderLineTestHelper(firstline, false, headers, headers_len, ":", "\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ": ", "\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ": ", "\r\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t", "\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t", "\r\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t ", "\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t ", "\r\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t\t", "\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t\t", "\r\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t \t", "\n"); HeaderLineTestHelper(firstline, false, headers, headers_len, ":\t \t", "\r\n"); } void WhitespaceHeaderTestHelper( const std::string& message, bool is_request, BalsaFrameEnums::ErrorCode expected_error_code) { BalsaHeaders balsa_headers; BalsaFrame framer; framer.set_is_request(is_request); framer.set_balsa_headers(&balsa_headers); SCOPED_TRACE(EscapeString(message)); size_t bytes_consumed = framer.ProcessInput(message.data(), message.size()); EXPECT_EQ(message.size(), bytes_consumed); if (expected_error_code == BalsaFrameEnums::BALSA_NO_ERROR) { EXPECT_EQ(false, framer.Error()); } else { EXPECT_EQ(true, framer.Error()); } EXPECT_EQ(expected_error_code, framer.ErrorCode()); } TEST(HTTPBalsaFrame, WhitespaceInRequestsProcessedProperly) { SCOPED_TRACE( "Test that a request header with a line with spaces and no " "data generates an error."); WhitespaceHeaderTestHelper( "GET / HTTP/1.1\r\n" " \r\n" "\r\n", true, BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); WhitespaceHeaderTestHelper( "GET / HTTP/1.1\r\n" " \r\n" "test: test\r\n" "\r\n", true, BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); SCOPED_TRACE("Test proper handling for line continuation in requests."); WhitespaceHeaderTestHelper( "GET / HTTP/1.1\r\n" "test: test\r\n" " continued\r\n" "\r\n", true, BalsaFrameEnums::BALSA_NO_ERROR); WhitespaceHeaderTestHelper( "GET / HTTP/1.1\r\n" "test: test\r\n" " \r\n" "\r\n", true, BalsaFrameEnums::BALSA_NO_ERROR); SCOPED_TRACE( "Test a confusing and ambiguous case: is it a line continuation or a new " "header field?"); WhitespaceHeaderTestHelper( "GET / HTTP/1.1\r\n" "test: test\r\n" " confusing:continued\r\n" "\r\n", true, BalsaFrameEnums::BALSA_NO_ERROR); } TEST(HTTPBalsaFrame, WhitespaceInResponsesProcessedProperly) { SCOPED_TRACE( "Test that a response header with a line with spaces and no " "data generates an error."); WhitespaceHeaderTestHelper( "HTTP/1.0 200 Reason\r\n" " \r\nContent-Length: 0\r\n" "\r\n", false, BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER); SCOPED_TRACE("Test proper handling for line continuation in responses."); WhitespaceHeaderTestHelper( "HTTP/1.0 200 Reason\r\n" "test: test\r\n" " continued\r\n" "Content-Length: 0\r\n" "\r\n", false, BalsaFrameEnums::BALSA_NO_ERROR); WhitespaceHeaderTestHelper( "HTTP/1.0 200 Reason\r\n" "test: test\r\n" " \r\n" "Content-Length: 0\r\n" "\r\n", false, BalsaFrameEnums::BALSA_NO_ERROR); SCOPED_TRACE( "Test a confusing and ambiguous case: is it a line continuation or a new " "header field?"); WhitespaceHeaderTestHelper( "HTTP/1.0 200 Reason\r\n" "test: test\r\n" " confusing:continued\r\n" "Content-Length: 0\r\n" "\r\n", false, BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForTrivialRequest) { std::string message = "GET /foobar HTTP/1.0\r\n\n"; FakeHeaders fake_headers; { InSequence s; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET /foobar HTTP/1.0", "GET", "/foobar", "HTTP/1.0")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithBlankLines) { std::string message = "\n\n\r\n\nGET /foobar HTTP/1.0\r\n\n"; FakeHeaders fake_headers; { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET /foobar HTTP/1.0", "GET", "/foobar", "HTTP/1.0")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput("GET /foobar HTTP/1.0\r\n\n")); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithSplitBlankLines) { std::string blanks = "\n" "\n" "\r\n" "\n"; std::string header_input = "GET /foobar HTTP/1.0\r\n\n"; FakeHeaders fake_headers; { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET /foobar HTTP/1.0", "GET", "/foobar", "HTTP/1.0")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput("GET /foobar HTTP/1.0\r\n\n")); ASSERT_EQ(blanks.size(), balsa_frame_.ProcessInput(blanks.data(), blanks.size())); ASSERT_EQ(header_input.size(), balsa_frame_.ProcessInput( header_input.data(), header_input.size())); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithZeroContentLength) { std::string message = "PUT /search?q=fo HTTP/1.1\n" "content-length: 0 \n" "\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "0"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT /search?q=fo HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithMissingContentLength) { std::string message = "PUT /search?q=fo HTTP/1.1\n" "\n"; auto error_code = BalsaFrameEnums::BalsaFrameEnums::REQUIRED_BODY_BUT_NO_CONTENT_LENGTH; EXPECT_CALL(visitor_mock_, HandleError(error_code)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(error_code, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, ContentLengthNotRequired) { HttpValidationPolicy http_validation_policy; http_validation_policy.require_content_length_if_body_required = false; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "PUT /search?q=fo HTTP/1.1\n" "\n"; balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForPermittedMissingContentLength) { std::string message = "PUT /search?q=fo HTTP/1.1\n" "\n"; FakeHeaders fake_headers; { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT /search?q=fo HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); } ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenNothingInConnectionLine) { std::string message = "PUT \t /search?q=fo \t HTTP/1.1 \t \r\n" "Connection:\r\n" "content-length: 0\r\n" "\r\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", ""); fake_headers.AddKeyValue("content-length", "0"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT \t /search?q=fo \t HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenOnlyCommentsInConnectionLine) { std::string message = "PUT \t /search?q=fo \t HTTP/1.1 \t \r\n" "Connection: ,,,,,,,,\r\n" "content-length: 0\r\n" "\r\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", ",,,,,,,,"); fake_headers.AddKeyValue("content-length", "0"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT \t /search?q=fo \t HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithZeroContentLengthMk2) { std::string message = "PUT \t /search?q=fo \t HTTP/1.1 \t \r\n" "Connection: \t close \t\r\n" "content-length: \t\t 0 \t\t \r\n" "\r\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", "close"); fake_headers.AddKeyValue("content-length", "0"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT \t /search?q=fo \t HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenNoVisitorIsAssigned) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\r\n"; balsa_frame_.set_balsa_visitor(nullptr); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, RequestWithTrailers) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\r\n"; InSequence s; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", "close"); fake_headers.AddKeyValue("transfer-encoding", "chunked"); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); testing::Mock::VerifyAndClearExpectations(&visitor_mock_); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); FakeHeaders fake_trailers; fake_trailers.AddKeyValue("crass", "monkeys"); fake_trailers.AddKeyValue("funky", "monkeys"); EXPECT_CALL(visitor_mock_, OnTrailers(fake_trailers)); EXPECT_CALL(visitor_mock_, OnTrailerInput(_)).Times(AtLeast(1)); EXPECT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenNoVisitorIsAssignedInResponse) { std::string headers = "HTTP/1.1 502 Bad Gateway\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.set_balsa_visitor(nullptr); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, TransferEncodingIdentityIsIgnored) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: identity\r\n" "content-length: 10\r\n" "\r\n"; std::string body = "1234567890"; std::string message = (headers + body); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); ASSERT_EQ(body.size(), balsa_frame_.ProcessInput(body.data(), body.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenAVisitorIsChangedToNULLInMidParsing) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); balsa_frame_.set_balsa_visitor(nullptr); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); ASSERT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenAVisitorIsChangedToNULLInMidParsingInTrailer) { std::string headers = "HTTP/1.1 503 Server Not Available\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; balsa_frame_.set_is_request(false); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); balsa_frame_.set_balsa_visitor(nullptr); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); ASSERT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWhenNoVisitorAssignedAndChunkingErrorOccurs) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); balsa_frame_.set_balsa_visitor(nullptr); EXPECT_GE(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FramerRecognizesSemicolonAsChunkSizeDelimiter) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "8; foo=bar\r\n" "deadbeef\r\n" "0\r\n" "\r\n"; ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); balsa_frame_.set_balsa_visitor(&visitor_mock_); EXPECT_CALL(visitor_mock_, OnChunkLength(8)); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput("; foo=bar")); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput("")); EXPECT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, NonAsciiCharacterInChunkLength) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "555\xAB\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", "close"); fake_headers.AddKeyValue("transfer-encoding", "chunked"); auto error_code = BalsaFrameEnums::INVALID_CHUNK_LENGTH; { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET / HTTP/1.1", "GET", "/", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnRawBodyInput("555\xAB")); EXPECT_CALL(visitor_mock_, HandleError(error_code)); } ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); EXPECT_EQ(strlen("555\xAB"), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_CHUNK_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorCalledAsExpectedWhenChunkingOverflowOccurs) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; const char* chunk_read_before_overflow = "FFFFFFFFFFFFFFFFF"; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", "close"); fake_headers.AddKeyValue("transfer-encoding", "chunked"); auto error_code = BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW; { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET / HTTP/1.1", "GET", "/", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnRawBodyInput(chunk_read_before_overflow)); EXPECT_CALL(visitor_mock_, HandleError(error_code)); } ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); EXPECT_EQ(strlen(chunk_read_before_overflow), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorCalledAsExpectedWhenInvalidChunkLengthOccurs) { std::string headers = "GET / HTTP/1.1\r\n" "Connection: close\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "12z123 \r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("Connection", "close"); fake_headers.AddKeyValue("transfer-encoding", "chunked"); auto error_code = BalsaFrameEnums::INVALID_CHUNK_LENGTH; { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET / HTTP/1.1", "GET", "/", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnRawBodyInput("12z")); EXPECT_CALL(visitor_mock_, HandleError(error_code)); } ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); EXPECT_EQ(3u, balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_CHUNK_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithContentLength) { std::string message_headers = "PUT \t /search?q=fo \t HTTP/1.1 \t \r\n" "content-length: \t\t 20 \t\t \r\n" "\r\n"; std::string message_body = "12345678901234567890"; std::string message = std::string(message_headers) + std::string(message_body); FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "20"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT \t /search?q=fo \t HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnRawBodyInput(message_body)); EXPECT_CALL(visitor_mock_, OnBodyChunkInput(message_body)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); ASSERT_EQ(message_body.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithOneCharContentLength) { std::string message_headers = "PUT \t /search?q=fo \t HTTP/1.1 \t \r\n" "content-length: \t\t 2 \t\t \r\n" "\r\n"; std::string message_body = "12"; std::string message = std::string(message_headers) + std::string(message_body); FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "2"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("PUT \t /search?q=fo \t HTTP/1.1", "PUT", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnRawBodyInput(message_body)); EXPECT_CALL(visitor_mock_, OnBodyChunkInput(message_body)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); ASSERT_EQ(message_body.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, InvalidChunkExtensionWithCarriageReturn) { balsa_frame_.set_http_validation_policy( HttpValidationPolicy{.disallow_lone_cr_in_chunk_extension = true}); std::string message_headers = "POST /potato?salad=withmayo HTTP/1.1\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string message_body = "9; bad\rextension\r\n" "012345678\r\n" "0\r\n" "\r\n"; std::string message = std::string(message_headers) + std::string(message_body); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_CHUNK_EXTENSION)); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size()); } TEST_F(HTTPBalsaFrameTest, ChunkExtensionCarriageReturnLineFeedAtBoundary) { balsa_frame_.set_http_validation_policy( HttpValidationPolicy{.disallow_lone_cr_in_chunk_extension = true}); EXPECT_CALL(visitor_mock_, ProcessHeaders(_)); EXPECT_CALL(visitor_mock_, HeaderDone()); constexpr absl::string_view headers( "POST / HTTP/1.1\r\n" "transfer-encoding: chunked\r\n\r\n"); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); constexpr absl::string_view body1("3\r"); ASSERT_EQ(body1.size(), balsa_frame_.ProcessInput(body1.data(), body1.size())); ASSERT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); constexpr absl::string_view body2( "\nfoo\r\n" "0\r\n\r\n"); EXPECT_CALL(visitor_mock_, OnBodyChunkInput("foo")); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(body2.size(), balsa_frame_.ProcessInput(body2.data(), body2.size())); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, ChunkExtensionLoneCarriageReturnAtBoundary) { balsa_frame_.set_http_validation_policy( HttpValidationPolicy{.disallow_lone_cr_in_chunk_extension = true}); EXPECT_CALL(visitor_mock_, ProcessHeaders(_)); EXPECT_CALL(visitor_mock_, HeaderDone()); constexpr absl::string_view headers( "POST / HTTP/1.1\r\n" "transfer-encoding: chunked\r\n\r\n"); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); constexpr absl::string_view body1("3\r"); ASSERT_EQ(body1.size(), balsa_frame_.ProcessInput(body1.data(), body1.size())); ASSERT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); constexpr absl::string_view body2("a"); EXPECT_EQ(0, balsa_frame_.ProcessInput(body2.data(), body2.size())); EXPECT_EQ(BalsaFrameEnums::INVALID_CHUNK_EXTENSION, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithTransferEncoding) { std::string message_headers = "DELETE /search?q=fo \t HTTP/1.1 \t \r\n" "trAnsfer-eNcoding: chunked\r\n" "\r\n"; std::string message_body = "A chunkjed extension \r\n" "01234567890 more crud including numbers 123123\r\n" "3f\n" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" "0 last one\r\n" "\r\n"; std::string message_body_data = "0123456789" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; std::string message = std::string(message_headers) + std::string(message_body); FakeHeaders fake_headers; fake_headers.AddKeyValue("trAnsfer-eNcoding", "chunked"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("DELETE /search?q=fo \t HTTP/1.1", "DELETE", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnChunkLength(10)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput(" chunkjed extension ")); EXPECT_CALL(visitor_mock_, OnChunkLength(63)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput("")); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput(" last one")); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); std::string body_input; EXPECT_CALL(visitor_mock_, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); std::string body_data; EXPECT_CALL(visitor_mock_, OnBodyChunkInput(_)) .WillRepeatedly([&body_data](absl::string_view input) { absl::StrAppend(&body_data, input); }); EXPECT_CALL(visitor_mock_, OnTrailerInput(_)).Times(0); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_EQ(message_body.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ(message_body, body_input); EXPECT_EQ(message_body_data, body_data); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForRequestWithTransferEncodingAndTrailers) { std::string message_headers = "DELETE /search?q=fo \t HTTP/1.1 \t \r\n" "trAnsfer-eNcoding: chunked\r\n" "another_random_header: \r\n" " \t \n" " \t includes a continuation\n" "\r\n"; std::string message_body = "A chunkjed extension \r\n" "01234567890 more crud including numbers 123123\r\n" "3f\n" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" "1 \r\n" "x \r\n" "0 last one\r\n"; std::string trailer_data = "a_trailer_key: and a trailer value\r\n" "\r\n"; std::string message_body_data = "0123456789" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; std::string message = (std::string(message_headers) + std::string(message_body) + std::string(trailer_data)); FakeHeaders fake_headers; fake_headers.AddKeyValue("trAnsfer-eNcoding", "chunked"); fake_headers.AddKeyValue("another_random_header", "includes a continuation"); FakeHeaders fake_trailers; fake_trailers.AddKeyValue("a_trailer_key", "and a trailer value"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("DELETE /search?q=fo \t HTTP/1.1", "DELETE", "/search?q=fo", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnChunkLength(10)); EXPECT_CALL(visitor_mock_, OnChunkLength(63)); EXPECT_CALL(visitor_mock_, OnChunkLength(1)); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnTrailers(fake_trailers)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); std::string body_input; EXPECT_CALL(visitor_mock_, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); std::string body_data; EXPECT_CALL(visitor_mock_, OnBodyChunkInput(_)) .WillRepeatedly([&body_data](absl::string_view input) { absl::StrAppend(&body_data, input); }); EXPECT_CALL(visitor_mock_, OnTrailerInput(trailer_data)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput(_)).Times(AnyNumber()); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_EQ(message_body.size() + trailer_data.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ(message_body, body_input); EXPECT_EQ(message_body_data, body_data); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyWithRequestFirstLineWarningWithOnlyMethod) { std::string message = "GET\n"; FakeHeaders fake_headers; auto error_code = BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD; { InSequence s; EXPECT_CALL(visitor_mock_, HandleWarning(error_code)); EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET", "GET", "", "")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyWithRequestFirstLineWarningWithOnlyMethodAndWS) { std::string message = "GET \n"; FakeHeaders fake_headers; auto error_code = BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD; { InSequence s; EXPECT_CALL(visitor_mock_, HandleWarning(error_code)); EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET ", "GET", "", "")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AbsoluteFormTargetUri) { std::string message = "GET http: "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ("http: balsa_frame_.headers()->request_uri()); EXPECT_EQ("example.com", balsa_frame_.headers()->GetHeader("host")); } TEST_F(HTTPBalsaFrameTest, InvalidAbsoluteFormTargetUri) { std::string message = "GET -pwn/index.html HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.is_valid_target_uri()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ("-pwn/index.html", balsa_frame_.headers()->request_uri()); EXPECT_EQ("example.com", balsa_frame_.headers()->GetHeader("host")); } TEST_F(HTTPBalsaFrameTest, RejectInvalidAbsoluteFormTargetUri) { HttpValidationPolicy http_validation_policy{.disallow_invalid_target_uris = true}; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "GET -pwn/index.html HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); const size_t end_of_first_line = message.find_first_of("\r\n") + 1; EXPECT_EQ(end_of_first_line, balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_TARGET_URI, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, RejectStarForNonOptions) { HttpValidationPolicy http_validation_policy{.disallow_invalid_target_uris = true}; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "GET * HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); const size_t end_of_first_line = message.find_first_of("\r\n") + 1; EXPECT_EQ(end_of_first_line, balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_TARGET_URI, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AllowStarForOptions) { HttpValidationPolicy http_validation_policy{.disallow_invalid_target_uris = true}; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "OPTIONS * HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, RejectConnectWithNoPort) { HttpValidationPolicy http_validation_policy{.disallow_invalid_target_uris = true}; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "CONNECT example.com HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); const size_t end_of_first_line = message.find_first_of("\r\n") + 1; EXPECT_EQ(end_of_first_line, balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_TARGET_URI, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, RejectConnectWithInvalidPort) { HttpValidationPolicy http_validation_policy{.disallow_invalid_target_uris = true}; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "CONNECT example.com:443z HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); const size_t end_of_first_line = message.find_first_of("\r\n") + 1; EXPECT_EQ(end_of_first_line, balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_TARGET_URI, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AllowConnectWithValidPort) { HttpValidationPolicy http_validation_policy{.disallow_invalid_target_uris = true}; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string message = "CONNECT example.com:443 HTTP/1.1\r\n" "Host: example.com\r\n" "\r\n"; balsa_frame_.set_is_request(true); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyWithRequestFirstLineWarningWithMethodAndURI) { std::string message = "GET /uri\n"; FakeHeaders fake_headers; auto error_code = BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI; { InSequence s; EXPECT_CALL(visitor_mock_, HandleWarning(error_code)); EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET /uri", "GET", "/uri", "")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyWithResponseFirstLineError) { std::string message = "HTTP/1.1\n\n"; FakeHeaders fake_headers; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION; { InSequence s; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput).Times(0); EXPECT_CALL(visitor_mock_, ProcessHeaders(_)).Times(0); EXPECT_CALL(visitor_mock_, HeaderDone()).Times(0); EXPECT_CALL(visitor_mock_, MessageDone()).Times(0); } EXPECT_CALL(visitor_mock_, OnHeaderInput(_)).Times(0); EXPECT_GE(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FlagsErrorWithContentLengthOverflow) { std::string message = "HTTP/1.0 200 OK\r\n" "content-length: 9999999999999999999999999999999999999999\n" "\n"; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FlagsErrorWithInvalidResponseCode) { std::string message = "HTTP/1.0 x OK\r\n" "\n"; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_GE(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FlagsErrorWithOverflowingResponseCode) { std::string message = "HTTP/1.0 999999999999999999999999999999999999999 OK\r\n" "\n"; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_GE(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FlagsErrorWithInvalidContentLength) { std::string message = "HTTP/1.0 200 OK\r\n" "content-length: xxx\n" "\n"; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FlagsErrorWithNegativeContentLengthValue) { std::string message = "HTTP/1.0 200 OK\r\n" "content-length: -20\n" "\n"; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FlagsErrorWithEmptyContentLengthValue) { std::string message = "HTTP/1.0 200 OK\r\n" "content-length: \n" "\n"; balsa_frame_.set_is_request(false); auto error_code = BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH; EXPECT_CALL(visitor_mock_, HandleError(error_code)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForTrivialResponse) { std::string message = "HTTP/1.0 200 OK\r\n" "content-length: 0\n" "\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "0"); balsa_frame_.set_is_request(false); { InSequence s; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput( "HTTP/1.0 200 OK", "HTTP/1.0", "200", "OK")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForResponseWithSplitBlankLines) { std::string blanks = "\n" "\r\n" "\r\n"; std::string header_input = "HTTP/1.0 200 OK\r\n" "content-length: 0\n" "\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "0"); balsa_frame_.set_is_request(false); { InSequence s; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput( "HTTP/1.0 200 OK", "HTTP/1.0", "200", "OK")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(header_input)); EXPECT_EQ(blanks.size(), balsa_frame_.ProcessInput(blanks.data(), blanks.size())); EXPECT_EQ(header_input.size(), balsa_frame_.ProcessInput( header_input.data(), header_input.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForResponseWithBlankLines) { std::string blanks = "\n" "\r\n" "\n" "\n" "\r\n" "\r\n"; std::string header_input = "HTTP/1.0 200 OK\r\n" "content-length: 0\n" "\n"; std::string message = blanks + header_input; FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "0"); balsa_frame_.set_is_request(false); { InSequence s; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput( "HTTP/1.0 200 OK", "HTTP/1.0", "200", "OK")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(header_input)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForResponseWithContentLength) { std::string message_headers = "HTTP/1.1 \t 200 Ok all is well\r\n" "content-length: \t\t 20 \t\t \r\n" "\r\n"; std::string message_body = "12345678901234567890"; std::string message = std::string(message_headers) + std::string(message_body); FakeHeaders fake_headers; fake_headers.AddKeyValue("content-length", "20"); balsa_frame_.set_is_request(false); { InSequence s1; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput("HTTP/1.1 \t 200 Ok all is well", "HTTP/1.1", "200", "Ok all is well")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnRawBodyInput(message_body)); EXPECT_CALL(visitor_mock_, OnBodyChunkInput(message_body)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_EQ(message_body.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForResponseWithTransferEncoding) { std::string message_headers = "HTTP/1.1 \t 200 Ok all is well\r\n" "trAnsfer-eNcoding: chunked\r\n" "\r\n"; std::string message_body = "A chunkjed extension \r\n" "01234567890 more crud including numbers 123123\r\n" "3f\n" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" "0 last one\r\n" "\r\n"; std::string message_body_data = "0123456789" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; std::string message = std::string(message_headers) + std::string(message_body); FakeHeaders fake_headers; fake_headers.AddKeyValue("trAnsfer-eNcoding", "chunked"); balsa_frame_.set_is_request(false); { InSequence s1; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput("HTTP/1.1 \t 200 Ok all is well", "HTTP/1.1", "200", "Ok all is well")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnChunkLength(10)); EXPECT_CALL(visitor_mock_, OnChunkLength(63)); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); std::string body_input; EXPECT_CALL(visitor_mock_, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); std::string body_data; EXPECT_CALL(visitor_mock_, OnBodyChunkInput(_)) .WillRepeatedly([&body_data](absl::string_view input) { absl::StrAppend(&body_data, input); }); EXPECT_CALL(visitor_mock_, OnTrailerInput(_)).Times(0); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_EQ(message_body.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ(message_body, body_input); EXPECT_EQ(message_body_data, body_data); } TEST_F(HTTPBalsaFrameTest, VisitorInvokedProperlyForResponseWithTransferEncodingAndTrailers) { std::string message_headers = "HTTP/1.1 \t 200 Ok all is well\r\n" "trAnsfer-eNcoding: chunked\r\n" "\r\n"; std::string message_body = "A chunkjed extension \r\n" "01234567890 more crud including numbers 123123\r\n" "3f\n" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" "0 last one\r\n"; std::string trailer_data = "a_trailer_key: and a trailer value\r\n" "\r\n"; std::string message_body_data = "0123456789" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; std::string message = (std::string(message_headers) + std::string(message_body) + std::string(trailer_data)); FakeHeaders fake_headers; fake_headers.AddKeyValue("trAnsfer-eNcoding", "chunked"); FakeHeaders fake_headers_in_trailer; fake_headers_in_trailer.AddKeyValue("a_trailer_key", "and a trailer value"); balsa_frame_.set_is_request(false); { InSequence s1; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput("HTTP/1.1 \t 200 Ok all is well", "HTTP/1.1", "200", "Ok all is well")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnChunkLength(10)); EXPECT_CALL(visitor_mock_, OnChunkLength(63)); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnTrailers(fake_headers_in_trailer)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); std::string body_input; EXPECT_CALL(visitor_mock_, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); std::string body_data; EXPECT_CALL(visitor_mock_, OnBodyChunkInput(_)) .WillRepeatedly([&body_data](absl::string_view input) { absl::StrAppend(&body_data, input); }); EXPECT_CALL(visitor_mock_, OnTrailerInput(trailer_data)); ASSERT_EQ(message_headers.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_EQ(message_body.size() + trailer_data.size(), balsa_frame_.ProcessInput(message.data() + message_headers.size(), message.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ(message_body, body_input); EXPECT_EQ(message_body_data, body_data); } TEST_F( HTTPBalsaFrameTest, VisitorInvokedProperlyForResponseWithTransferEncodingAndTrailersBytePer) { std::string message_headers = "HTTP/1.1 \t 200 Ok all is well\r\n" "trAnsfer-eNcoding: chunked\r\n" "\r\n"; std::string message_body = "A chunkjed extension \r\n" "01234567890 more crud including numbers 123123\r\n" "3f\n" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" "0 last one\r\n"; std::string trailer_data = "a_trailer_key: and a trailer value\r\n" "\r\n"; std::string message_body_data = "0123456789" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; std::string message = (std::string(message_headers) + std::string(message_body) + std::string(trailer_data)); FakeHeaders fake_headers; fake_headers.AddKeyValue("trAnsfer-eNcoding", "chunked"); FakeHeaders fake_headers_in_trailer; fake_headers_in_trailer.AddKeyValue("a_trailer_key", "and a trailer value"); balsa_frame_.set_is_request(false); { InSequence s1; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput("HTTP/1.1 \t 200 Ok all is well", "HTTP/1.1", "200", "Ok all is well")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnChunkLength(10)); EXPECT_CALL(visitor_mock_, OnChunkLength(63)); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnTrailers(fake_headers_in_trailer)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(message_headers)); std::string body_input; EXPECT_CALL(visitor_mock_, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); std::string body_data; EXPECT_CALL(visitor_mock_, OnBodyChunkInput(_)) .WillRepeatedly([&body_data](absl::string_view input) { absl::StrAppend(&body_data, input); }); std::string trailer_input; EXPECT_CALL(visitor_mock_, OnTrailerInput(_)) .WillRepeatedly([&trailer_input](absl::string_view input) { absl::StrAppend(&trailer_input, input); }); for (size_t i = 0; i < message.size(); ++i) { ASSERT_EQ(1u, balsa_frame_.ProcessInput(message.data() + i, 1)); } EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ(message_body, body_input); EXPECT_EQ(message_body_data, body_data); EXPECT_EQ(trailer_data, trailer_input); } TEST(HTTPBalsaFrame, VisitorInvokedProperlyForResponseWithTransferEncodingAndTrailersRandom) { TestSeed seed; seed.Initialize(GetQuicheCommandLineFlag(FLAGS_randseed)); RandomEngine rng; rng.seed(seed.GetSeed()); for (int i = 0; i < 1000; ++i) { std::string message_headers = "HTTP/1.1 \t 200 Ok all is well\r\n" "trAnsfer-eNcoding: chunked\r\n" "\r\n"; std::string message_body = "A chunkjed extension \r\n" "01234567890 more crud including numbers 123123\r\n" "3f\n" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" "0 last one\r\n"; std::string trailer_data = "a_trailer_key: and a trailer value\r\n" "\r\n"; std::string message_body_data = "0123456789" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; std::string message = (std::string(message_headers) + std::string(message_body) + std::string(trailer_data)); FakeHeaders fake_headers; fake_headers.AddKeyValue("trAnsfer-eNcoding", "chunked"); FakeHeaders fake_headers_in_trailer; fake_headers_in_trailer.AddKeyValue("a_trailer_key", "and a trailer value"); StrictMock<BalsaVisitorMock> visitor_mock; BalsaHeaders headers; BalsaFrame balsa_frame; balsa_frame.set_is_request(false); balsa_frame.set_balsa_headers(&headers); balsa_frame.EnableTrailers(); balsa_frame.set_balsa_visitor(&visitor_mock); { InSequence s1; EXPECT_CALL(visitor_mock, OnResponseFirstLineInput( "HTTP/1.1 \t 200 Ok all is well", "HTTP/1.1", "200", "Ok all is well")); EXPECT_CALL(visitor_mock, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock, HeaderDone()); EXPECT_CALL(visitor_mock, OnTrailers(fake_headers_in_trailer)); EXPECT_CALL(visitor_mock, MessageDone()); } EXPECT_CALL(visitor_mock, OnHeaderInput(message_headers)); std::string body_input; EXPECT_CALL(visitor_mock, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); std::string body_data; EXPECT_CALL(visitor_mock, OnBodyChunkInput(_)) .WillRepeatedly([&body_data](absl::string_view input) { absl::StrAppend(&body_data, input); }); std::string trailer_input; EXPECT_CALL(visitor_mock, OnTrailerInput(_)) .WillRepeatedly([&trailer_input](absl::string_view input) { absl::StrAppend(&trailer_input, input); }); EXPECT_CALL(visitor_mock, OnChunkLength(_)).Times(AtLeast(1)); EXPECT_CALL(visitor_mock, OnChunkExtensionInput(_)).Times(AtLeast(1)); size_t count = 0; size_t total_processed = 0; for (size_t j = 0; j < message.size();) { auto dist = std::uniform_int_distribution<>(0, message.size() - j + 1); count = dist(rng); size_t processed = balsa_frame.ProcessInput(message.data() + j, count); ASSERT_GE(count, processed); total_processed += processed; j += processed; } EXPECT_EQ(message.size(), total_processed); EXPECT_TRUE(balsa_frame.MessageFullyRead()); EXPECT_FALSE(balsa_frame.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame.ErrorCode()); EXPECT_EQ(message_body, body_input); EXPECT_EQ(message_body_data, body_data); EXPECT_EQ(trailer_data, trailer_input); } } TEST_F(HTTPBalsaFrameTest, AppropriateActionTakenWhenHeadersTooLongWithTooMuchInput) { const absl::string_view message = "GET /asflkasfdhjsafdkljhasfdlkjhasdflkjhsafdlkjhh HTTP/1.1"; const size_t kAmountLessThanHeaderLen = 10; ASSERT_LE(kAmountLessThanHeaderLen, message.size()); auto error_code = BalsaFrameEnums::HEADERS_TOO_LONG; EXPECT_CALL(visitor_mock_, HandleError(error_code)); balsa_frame_.set_max_header_length(message.size() - kAmountLessThanHeaderLen); ASSERT_EQ(balsa_frame_.max_header_length(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::HEADERS_TOO_LONG, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AppropriateActionTakenWhenHeadersTooLongWithBody) { std::string message = "PUT /foo HTTP/1.1\r\n" "Content-Length: 4\r\n" "header: xxxxxxxxx\r\n\r\n" "B"; auto error_code = BalsaFrameEnums::HEADERS_TOO_LONG; EXPECT_CALL(visitor_mock_, HandleError(error_code)); balsa_frame_.set_max_header_length(message.size() - 2); ASSERT_EQ(balsa_frame_.max_header_length(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::HEADERS_TOO_LONG, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AppropriateActionTakenWhenHeadersTooLongWhenReset) { std::string message = "GET /asflkasfdhjsafdkljhasfdlkjhasdflkjhsafdlkjhh HTTP/1.1\r\n" "\r\n"; const size_t kAmountLessThanHeaderLen = 10; ASSERT_LE(kAmountLessThanHeaderLen, message.size()); auto error_code = BalsaFrameEnums::HEADERS_TOO_LONG; ASSERT_EQ(message.size() - 2, balsa_frame_.ProcessInput(message.data(), message.size() - 2)); balsa_frame_.set_max_header_length(message.size() - kAmountLessThanHeaderLen); EXPECT_CALL(visitor_mock_, HandleError(error_code)); ASSERT_EQ(0u, balsa_frame_.ProcessInput(message.data() + message.size() - 2, 2)); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::HEADERS_TOO_LONG, balsa_frame_.ErrorCode()); } class BalsaFrameParsingTest : public QuicheTest { protected: void SetUp() override { balsa_frame_.set_is_request(true); balsa_frame_.set_balsa_headers(&headers_); balsa_frame_.set_balsa_visitor(&visitor_mock_); } void TestEmptyHeaderKeyHelper(const std::string& message) { InSequence s; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET / HTTP/1.1", "GET", "/", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, OnHeaderInput(_)); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_FORMAT)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); Mock::VerifyAndClearExpectations(&visitor_mock_); } void TestInvalidTrailerFormat(const std::string& trailer, bool invalid_name_char) { balsa_frame_.set_is_request(false); balsa_frame_.EnableTrailers(); std::string headers = "HTTP/1.0 200 ok\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; InSequence s; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput); EXPECT_CALL(visitor_mock_, OnHeaderInput); EXPECT_CALL(visitor_mock_, ProcessHeaders); EXPECT_CALL(visitor_mock_, HeaderDone); EXPECT_CALL(visitor_mock_, OnChunkLength(3)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput); EXPECT_CALL(visitor_mock_, OnRawBodyInput); EXPECT_CALL(visitor_mock_, OnBodyChunkInput); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnChunkExtensionInput); EXPECT_CALL(visitor_mock_, OnRawBodyInput); EXPECT_CALL(visitor_mock_, OnRawBodyInput); const auto expected_error = invalid_name_char ? BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER : BalsaFrameEnums::INVALID_TRAILER_FORMAT; EXPECT_CALL(visitor_mock_, HandleError(expected_error)).Times(1); EXPECT_CALL(visitor_mock_, OnTrailers(_)).Times(0); EXPECT_CALL(visitor_mock_, MessageDone()).Times(0); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(expected_error, balsa_frame_.ErrorCode()); Mock::VerifyAndClearExpectations(&visitor_mock_); } BalsaHeaders headers_; BalsaFrame balsa_frame_; StrictMock<BalsaVisitorMock> visitor_mock_; }; TEST_F(BalsaFrameParsingTest, AppropriateActionTakenWhenHeaderColonsAreFunny) { std::string message = "GET / HTTP/1.1\r\n" "a\r\n" "b\r\n" "c\r\n" "d\r\n" "e\r\n" "f\r\n" "g\r\n" "h\r\n" "i:\r\n" "j\r\n" "k\r\n" "l\r\n" "m\r\n" "n\r\n" "o\r\n" "p\r\n" "q\r\n" "r\r\n" "s\r\n" "t\r\n" "u\r\n" "v\r\n" "w\r\n" "x\r\n" "y\r\n" "z\r\n" "A\r\n" "B\r\n" ": val\r\n" "\r\n"; EXPECT_CALL(visitor_mock_, OnRequestFirstLineInput("GET / HTTP/1.1", "GET", "/", "HTTP/1.1")); EXPECT_CALL(visitor_mock_, OnHeaderInput(_)); EXPECT_CALL(visitor_mock_, HandleWarning(BalsaFrameEnums::HEADER_MISSING_COLON)) .Times(27); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_FORMAT)); ASSERT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); } TEST_F(BalsaFrameParsingTest, ErrorWhenHeaderKeyIsEmpty) { std::string firstKeyIsEmpty = "GET / HTTP/1.1\r\n" ": \r\n" "a:b\r\n" "c:d\r\n" "\r\n"; TestEmptyHeaderKeyHelper(firstKeyIsEmpty); balsa_frame_.Reset(); std::string laterKeyIsEmpty = "GET / HTTP/1.1\r\n" "a:b\r\n" ": \r\n" "c:d\r\n" "\r\n"; TestEmptyHeaderKeyHelper(laterKeyIsEmpty); } TEST_F(BalsaFrameParsingTest, InvalidTrailerFormat) { std::string trailer = ":monkeys\n" "\r\n"; TestInvalidTrailerFormat(trailer, false); balsa_frame_.Reset(); std::string trailer2 = " \r\n" "test: test\r\n" "\r\n"; TestInvalidTrailerFormat(trailer2, true); balsa_frame_.Reset(); std::string trailer3 = "a: b\r\n" ": test\r\n" "\r\n"; TestInvalidTrailerFormat(trailer3, false); } TEST_F(HTTPBalsaFrameTest, EnsureHeaderFramingFoundWithVariousCombinationsOfRN_RN) { const std::string message = "GET / HTTP/1.1\r\n" "content-length: 0\r\n" "a\r\n" "b\r\n" "c\r\n" "d\r\n" "e\r\n" "f\r\n" "g\r\n" "h\r\n" "i\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, EnsureHeaderFramingFoundWithVariousCombinationsOfRN_N) { const std::string message = "GET / HTTP/1.1\n" "content-length: 0\n" "a\n" "b\n" "c\n" "d\n" "e\n" "f\n" "g\n" "h\n" "i\n" "\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, EnsureHeaderFramingFoundWithVariousCombinationsOfRN_RN_N) { const std::string message = "GET / HTTP/1.1\n" "content-length: 0\r\n" "a\r\n" "b\n" "c\r\n" "d\n" "e\r\n" "f\n" "g\r\n" "h\n" "i\r\n" "\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, EnsureHeaderFramingFoundWithVariousCombinationsOfRN_N_RN) { const std::string message = "GET / HTTP/1.1\n" "content-length: 0\r\n" "a\n" "b\r\n" "c\n" "d\r\n" "e\n" "f\r\n" "g\n" "h\r\n" "i\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, ReadUntilCloseStateEnteredAsExpectedAndNotExited) { std::string message = "HTTP/1.1 200 OK\r\n" "\r\n"; balsa_frame_.set_is_request(false); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()); EXPECT_EQ(BalsaFrameEnums::READING_UNTIL_CLOSE, balsa_frame_.ParseState()); std::string gobldygook = "-198324-9182-43981-23498-98342-jasldfn-1294hj"; for (int i = 0; i < 1000; ++i) { EXPECT_EQ(gobldygook.size(), balsa_frame_.ProcessInput(gobldygook.data(), gobldygook.size())); EXPECT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()); EXPECT_EQ(BalsaFrameEnums::READING_UNTIL_CLOSE, balsa_frame_.ParseState()); } } TEST_F(HTTPBalsaFrameTest, BytesSafeToSpliceAndBytesSplicedWorksWithContentLength) { std::string header = "HTTP/1.1 200 OK\r\n" "content-length: 1000\r\n" "\r\n"; balsa_frame_.set_is_request(false); size_t bytes_safe_to_splice = 1000; EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ(header.size(), balsa_frame_.ProcessInput(header.data(), header.size())); EXPECT_EQ(bytes_safe_to_splice, balsa_frame_.BytesSafeToSplice()); while (bytes_safe_to_splice > 0) { balsa_frame_.BytesSpliced(1); bytes_safe_to_splice -= 1; ASSERT_FALSE(balsa_frame_.Error()) << BalsaFrameEnums::ParseStateToString(balsa_frame_.ParseState()) << " " << BalsaFrameEnums::ErrorCodeToString(balsa_frame_.ErrorCode()) << " with bytes_safe_to_splice: " << bytes_safe_to_splice << " and BytesSafeToSplice(): " << balsa_frame_.BytesSafeToSplice(); } EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, BytesSplicedFlagsErrorsWhenNotInProperState) { balsa_frame_.set_is_request(false); balsa_frame_.BytesSpliced(1); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO, balsa_frame_.ErrorCode()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, BytesSplicedFlagsErrorsWhenTooMuchSplicedForContentLen) { std::string header = "HTTP/1.1 200 OK\r\n" "content-length: 1000\r\n" "\r\n"; balsa_frame_.set_is_request(false); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ(header.size(), balsa_frame_.ProcessInput(header.data(), header.size())); EXPECT_EQ(1000u, balsa_frame_.BytesSafeToSplice()); balsa_frame_.BytesSpliced(1001); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ( BalsaFrameEnums::CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT, balsa_frame_.ErrorCode()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, BytesSplicedWorksAsExpectedForReadUntilClose) { std::string header = "HTTP/1.1 200 OK\r\n" "\r\n"; balsa_frame_.set_is_request(false); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ(header.size(), balsa_frame_.ProcessInput(header.data(), header.size())); EXPECT_EQ(BalsaFrameEnums::READING_UNTIL_CLOSE, balsa_frame_.ParseState()); EXPECT_EQ(std::numeric_limits<size_t>::max(), balsa_frame_.BytesSafeToSplice()); for (int i = 0; i < 1000; ++i) { EXPECT_EQ(std::numeric_limits<size_t>::max(), balsa_frame_.BytesSafeToSplice()); balsa_frame_.BytesSpliced(12312312); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } EXPECT_EQ(std::numeric_limits<size_t>::max(), balsa_frame_.BytesSafeToSplice()); } TEST_F(HTTPBalsaFrameTest, BytesSplicedFlagsErrorsWhenTooMuchSplicedForChunked) { std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string body_fragment = "a\r\n"; balsa_frame_.set_is_request(false); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ(header.size(), balsa_frame_.ProcessInput(header.data(), header.size())); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ( body_fragment.size(), balsa_frame_.ProcessInput(body_fragment.data(), body_fragment.size())); EXPECT_EQ(10u, balsa_frame_.BytesSafeToSplice()); balsa_frame_.BytesSpliced(11); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ( BalsaFrameEnums::CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT, balsa_frame_.ErrorCode()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, BytesSafeToSpliceAndBytesSplicedWorksWithChunks) { std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "\r\n"; balsa_frame_.set_is_request(false); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ(header.size(), balsa_frame_.ProcessInput(header.data(), header.size())); { std::string body_fragment = "3e8\r\n"; EXPECT_FALSE(balsa_frame_.MessageFullyRead()); size_t bytes_safe_to_splice = 1000; EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ( body_fragment.size(), balsa_frame_.ProcessInput(body_fragment.data(), body_fragment.size())); EXPECT_EQ(bytes_safe_to_splice, balsa_frame_.BytesSafeToSplice()); while (bytes_safe_to_splice > 0) { balsa_frame_.BytesSpliced(1); bytes_safe_to_splice -= 1; ASSERT_FALSE(balsa_frame_.Error()); } EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_FALSE(balsa_frame_.Error()); } { std::string body_fragment = "\r\n7d0\r\n"; EXPECT_FALSE(balsa_frame_.MessageFullyRead()); size_t bytes_safe_to_splice = 2000; EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ( body_fragment.size(), balsa_frame_.ProcessInput(body_fragment.data(), body_fragment.size())); EXPECT_EQ(bytes_safe_to_splice, balsa_frame_.BytesSafeToSplice()); while (bytes_safe_to_splice > 0) { balsa_frame_.BytesSpliced(1); bytes_safe_to_splice -= 1; ASSERT_FALSE(balsa_frame_.Error()); } EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_FALSE(balsa_frame_.Error()); } { std::string body_fragment = "\r\n1\r\n"; EXPECT_FALSE(balsa_frame_.MessageFullyRead()); size_t bytes_safe_to_splice = 1; EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ( body_fragment.size(), balsa_frame_.ProcessInput(body_fragment.data(), body_fragment.size())); EXPECT_EQ(bytes_safe_to_splice, balsa_frame_.BytesSafeToSplice()); while (bytes_safe_to_splice > 0) { balsa_frame_.BytesSpliced(1); bytes_safe_to_splice -= 1; ASSERT_FALSE(balsa_frame_.Error()); } EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_FALSE(balsa_frame_.Error()); } { std::string body_fragment = "\r\n0\r\n\r\n"; EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_EQ( body_fragment.size(), balsa_frame_.ProcessInput(body_fragment.data(), body_fragment.size())); EXPECT_EQ(0u, balsa_frame_.BytesSafeToSplice()); EXPECT_FALSE(balsa_frame_.Error()); } EXPECT_TRUE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, TwoDifferentContentLengthHeadersIsAnError) { std::string header = "HTTP/1.1 200 OK\r\n" "content-length: 12\r\n" "content-length: 14\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::MULTIPLE_CONTENT_LENGTH_KEYS, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, TwoSameContentLengthHeadersIsNotAnError) { std::string header = "POST / HTTP/1.1\r\n" "content-length: 1\r\n" "content-length: 1\r\n" "\r\n" "1"; balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_FALSE(balsa_frame_.Error()); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, TwoSameContentLengthHeadersIsAnError) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_multiple_content_length = true; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string header = "POST / HTTP/1.1\r\n" "content-length: 1\r\n" "content-length: 1\r\n" "\r\n" "1"; balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::MULTIPLE_CONTENT_LENGTH_KEYS, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, TwoTransferEncodingHeadersIsAnError) { std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "transfer-encoding: identity\r\n" "content-length: 3\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::MULTIPLE_TRANSFER_ENCODING_KEYS, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AcceptTwoTransferEncodingHeaders) { HttpValidationPolicy http_validation_policy; http_validation_policy.validate_transfer_encoding = false; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "transfer-encoding: identity\r\n" "content-length: 3\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, TwoTransferEncodingTokensIsAnError) { std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked, identity\r\n" "content-length: 3\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::UNKNOWN_TRANSFER_ENCODING, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AcceptTwoTransferEncodingTokens) { HttpValidationPolicy http_validation_policy; http_validation_policy.validate_transfer_encoding = false; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked, identity\r\n" "content-length: 3\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, UnknownTransferEncodingTokenIsAnError) { std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked-identity\r\n" "content-length: 3\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::UNKNOWN_TRANSFER_ENCODING, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, AcceptUnknownTransferEncodingToken) { HttpValidationPolicy http_validation_policy; http_validation_policy.validate_transfer_encoding = false; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked-identity\r\n" "content-length: 3\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, MissingContentLength) { std::string header = "HTTP/1.1 200 OK\r\n\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::MAYBE_BODY_BUT_NO_CONTENT_LENGTH, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, MultipleTransferEncodingsWithMissingContentLength) { HttpValidationPolicy http_validation_policy; http_validation_policy.validate_transfer_encoding = false; balsa_frame_.set_http_validation_policy(http_validation_policy); std::string header = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "transfer-encoding: identity\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.ProcessInput(header.data(), header.size()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::MAYBE_BODY_BUT_NO_CONTENT_LENGTH, balsa_frame_.ErrorCode()); } class DetachOnDoneFramer : public NoOpBalsaVisitor { public: DetachOnDoneFramer() { framer_.set_balsa_headers(&headers_); framer_.set_balsa_visitor(this); } void MessageDone() override { framer_.set_balsa_headers(nullptr); } BalsaFrame* framer() { return &framer_; } protected: BalsaFrame framer_; BalsaHeaders headers_; }; TEST(HTTPBalsaFrame, TestDetachOnDone) { DetachOnDoneFramer framer; const char* message = "GET HTTP/1.1\r\n\r\n"; framer.framer()->ProcessInput(message, strlen(message)); EXPECT_TRUE(framer.framer()->MessageFullyRead()); EXPECT_FALSE(framer.framer()->Error()); } class ModifyMaxHeaderLengthFramerInFirstLine : public DetachOnDoneFramer { public: void MessageDone() override {} void OnRequestFirstLineInput(absl::string_view , absl::string_view , absl::string_view , absl::string_view ) override { framer_.set_max_header_length(1); } }; class ModifyMaxHeaderLengthFramerInHeaderDone : public DetachOnDoneFramer { public: void MessageDone() override {} void HeaderDone() override { framer_.set_max_header_length(1); } }; TEST(HTTPBalsaFrame, ChangeMaxHeadersLengthOnFirstLine) { std::string message = "PUT /foo HTTP/1.1\r\n" "Content-Length: 2\r\n" "header: xxxxxxxxx\r\n\r\n" "B"; ModifyMaxHeaderLengthFramerInFirstLine balsa_frame; balsa_frame.framer()->set_is_request(true); balsa_frame.framer()->set_max_header_length(message.size() - 1); balsa_frame.framer()->ProcessInput(message.data(), message.size()); EXPECT_EQ(BalsaFrameEnums::HEADERS_TOO_LONG, balsa_frame.framer()->ErrorCode()); } TEST(HTTPBalsaFrame, ChangeMaxHeadersLengthOnHeaderDone) { std::string message = "PUT /foo HTTP/1.1\r\n" "Content-Length: 2\r\n" "header: xxxxxxxxx\r\n\r\n" "B"; ModifyMaxHeaderLengthFramerInHeaderDone balsa_frame; balsa_frame.framer()->set_is_request(true); balsa_frame.framer()->set_max_header_length(message.size() - 1); balsa_frame.framer()->ProcessInput(message.data(), message.size()); EXPECT_EQ(0, balsa_frame.framer()->ErrorCode()); } TEST(HTTPBalsaFrame, HeadersSizeSameAsMaxLengthIsAccepted) { std::string message = "GET /foo HTTP/1.1\r\n" "header: xxxxxxxxx\r\n\r\n"; ModifyMaxHeaderLengthFramerInHeaderDone balsa_frame; balsa_frame.framer()->set_is_request(true); balsa_frame.framer()->set_max_header_length(message.size()); balsa_frame.framer()->ProcessInput(message.data(), message.size()); EXPECT_EQ(0, balsa_frame.framer()->ErrorCode()); } TEST_F(HTTPBalsaFrameTest, KeyHasSpaces) { const std::string message = "GET / HTTP/1.1\r\n" "key has spaces: lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, SpaceBeforeColon) { const std::string message = "GET / HTTP/1.1\r\n" "key : lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, SpaceBeforeColonNotAfter) { const std::string message = "GET / HTTP/1.1\r\n" "key :lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, KeyHasTabs) { const std::string message = "GET / HTTP/1.1\r\n" "key\thas\ttabs: lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, TabBeforeColon) { const std::string message = "GET / HTTP/1.1\r\n" "key\t: lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, KeyHasContinuation) { const std::string message = "GET / HTTP/1.1\r\n" "key\n includes continuation: but not value\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, KeyHasMultipleContinuations) { const std::string message = "GET / HTTP/1.1\r\n" "key\n includes\r\n multiple\n continuations: but not value\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, KeyHasDoubleQuote) { const std::string message = "GET / HTTP/1.1\r\n" "key\"hasquote: lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_TRUE(headers_.HasHeader("key\"hasquote")); } TEST_F(HTTPBalsaFrameTest, KeyHasDisallowedDoubleQuote) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_double_quote_in_header_name = true; balsa_frame_.set_http_validation_policy(http_validation_policy); const std::string message = "GET / HTTP/1.1\r\n" "key\"hasquote: lock\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, TrailerMissingColon) { std::string headers = "HTTP/1.0 302 Redirect\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass_monkeys\n" "\r\n"; balsa_frame_.set_is_request(false); EXPECT_CALL(visitor_mock_, HandleWarning(BalsaFrameEnums::TRAILER_MISSING_COLON)); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); FakeHeaders fake_trailers; fake_trailers.AddKeyValue("crass_monkeys", ""); EXPECT_CALL(visitor_mock_, OnTrailers(fake_trailers)); EXPECT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::TRAILER_MISSING_COLON, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, MultipleHeadersInTrailer) { std::string headers = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\n" "0\n"; std::map<std::string, std::string> trailer; trailer["X-Trace"] = "http: "foobar.example.com&start=2012-06-03_15:59:06&rpc_duration=0.243349"; trailer["Date"] = "Sun, 03 Jun 2012 22:59:06 GMT"; trailer["Content-Type"] = "text/html"; trailer["X-Backends"] = "127.0.0.1_0,foo.example.com:39359"; trailer["X-Request-Trace"] = "foo.example.com:39359,127.0.0.1_1," "foo.example.com:39359,127.0.0.1_0," "foo.example.com:39359"; trailer["X-Service-Trace"] = "default"; trailer["X-Service"] = "default"; std::map<std::string, std::string>::const_iterator iter; std::string trailer_data; TestSeed seed; seed.Initialize(GetQuicheCommandLineFlag(FLAGS_randseed)); RandomEngine rng; rng.seed(seed.GetSeed()); FakeHeaders fake_headers_in_trailer; for (iter = trailer.begin(); iter != trailer.end(); ++iter) { trailer_data += iter->first; trailer_data += ":"; std::stringstream leading_whitespace_for_value; AppendRandomWhitespace(rng, &leading_whitespace_for_value); trailer_data += leading_whitespace_for_value.str(); trailer_data += iter->second; std::stringstream trailing_whitespace_for_value; AppendRandomWhitespace(rng, &trailing_whitespace_for_value); trailer_data += trailing_whitespace_for_value.str(); trailer_data += random_line_term(rng); fake_headers_in_trailer.AddKeyValue(iter->first, iter->second); } trailer_data += random_line_term(rng); FakeHeaders fake_headers; fake_headers.AddKeyValue("transfer-encoding", "chunked"); { InSequence s1; EXPECT_CALL(visitor_mock_, OnResponseFirstLineInput( "HTTP/1.1 200 OK", "HTTP/1.1", "200", "OK")); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, OnChunkLength(3)); EXPECT_CALL(visitor_mock_, OnChunkLength(0)); EXPECT_CALL(visitor_mock_, OnTrailers(fake_headers_in_trailer)); EXPECT_CALL(visitor_mock_, OnTrailerInput(trailer_data)); EXPECT_CALL(visitor_mock_, MessageDone()); } EXPECT_CALL(visitor_mock_, OnHeaderInput(headers)); std::string body_input; EXPECT_CALL(visitor_mock_, OnRawBodyInput(_)) .WillRepeatedly([&body_input](absl::string_view input) { absl::StrAppend(&body_input, input); }); EXPECT_CALL(visitor_mock_, OnBodyChunkInput("123")); balsa_frame_.set_is_request(false); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_EQ(trailer_data.size(), balsa_frame_.ProcessInput( trailer_data.data(), trailer_data.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_EQ(chunks, body_input); } TEST_F(HTTPBalsaFrameTest, NothingBadHappensWithNULLTrailer) { std::string headers = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "crass: monkeys\r\n" "funky: monkeys\r\n" "\n"; BalsaFrame balsa_frame; balsa_frame.set_balsa_headers(&headers_); balsa_frame.set_is_request(false); balsa_frame.set_balsa_visitor(nullptr); ASSERT_EQ(headers.size(), balsa_frame.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame.ProcessInput(chunks.data(), chunks.size())); ASSERT_EQ(trailer.size(), balsa_frame.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame.MessageFullyRead()); EXPECT_FALSE(balsa_frame.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, FrameAndResetAndFrameAgain) { std::string headers = "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "k: v\n" "\n"; balsa_frame_.set_is_request(false); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); { FakeHeaders fake_trailers; fake_trailers.AddKeyValue("k", "v"); EXPECT_CALL(visitor_mock_, OnTrailers(fake_trailers)); } ASSERT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); balsa_frame_.Reset(); headers = "HTTP/1.1 404 Error\r\n" "transfer-encoding: chunked\r\n" "\r\n"; chunks = "4\r\n" "1234\r\n" "0\r\n"; trailer = "nk: nv\n" "\n"; ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); { FakeHeaders fake_trailers; fake_trailers.AddKeyValue("nk", "nv"); EXPECT_CALL(visitor_mock_, OnTrailers(fake_trailers)); } ASSERT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, InvalidCharsInHeaderValueError) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::string kEscapedInvalid1 = "GET /foo HTTP/1.1\r\n" "Bogus-Head: val\\x00\r\n" "More-Invalid: \\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0E\x0F\r\n" "And-More: \x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D" "\x1E\x1F\r\n\r\n"; std::string message; absl::CUnescape(kEscapedInvalid1, &message); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, InvalidCharsInHeaderNameError) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kOff); const std::string kEscapedInvalid1 = "GET /foo HTTP/1.1\r\n" "Bogus\\x00-Head: val\r\n\r\n"; std::string message; absl::CUnescape(kEscapedInvalid1, &message); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, InvalidCharsInRequestHeaderError) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::string kEscapedInvalid = "GET /foo HTTP/1.1\r\n" "Smuggle-Me: \\x00GET /bar HTTP/1.1\r\n" "Another-Header: value\r\n\r\n"; std::string message; absl::CUnescape(kEscapedInvalid, &message); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, InvalidCharsInResponseHeaderAllowed) { balsa_frame_.set_is_request(false); balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kOff); const absl::string_view headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 5\r\n" "foo: a\022b\r\n" "\r\n"; EXPECT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, InvalidCharsInResponseHeaderError) { balsa_frame_.set_is_request(false); balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const absl::string_view headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 5\r\n" "foo: a\022b\r\n" "\r\n"; EXPECT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_CHARACTER, balsa_frame_.ErrorCode()); } class HTTPBalsaFrameTestOneChar : public HTTPBalsaFrameTest, public testing::WithParamInterface<char> { public: char GetCharUnderTest() { return GetParam(); } }; TEST_P(HTTPBalsaFrameTestOneChar, InvalidCharsErrorSet) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::string kRequest = "GET /foo HTTP/1.1\r\n" "Bogus-Char-Goes-Here: "; const std::string kEnding = "\r\n\r\n"; std::string message = kRequest; const char c = GetCharUnderTest(); message.append(1, c); message.append(kEnding); if (c == 9 || c == 10 || c == 13) { EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)) .Times(0); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); } else { EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } } INSTANTIATE_TEST_SUITE_P(TestInvalidCharSet, HTTPBalsaFrameTestOneChar, Range<char>(0, 32)); TEST_F(HTTPBalsaFrameTest, InvalidCharEndOfLine) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::string kInvalid1 = "GET /foo HTTP/1.1\r\n" "Header-Key: headervalue\\x00\r\n" "Legit-Header: legitvalue\r\n\r\n"; std::string message; absl::CUnescape(kInvalid1, &message); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, InvalidCharInFirstLine) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::string kInvalid1 = "GET /foo \\x00HTTP/1.1\r\n" "Legit-Header: legitvalue\r\n\r\n"; std::string message; absl::CUnescape(kInvalid1, &message); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); balsa_frame_.ProcessInput(message.data(), message.size()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, GibberishInHeadersAndTrailer) { const char kGibberish1[] = {static_cast<char>(138), static_cast<char>(175), static_cast<char>(233), 0}; const char kGibberish2[] = {'?', '?', static_cast<char>(128), static_cast<char>(255), static_cast<char>(129), static_cast<char>(254), 0}; const char kGibberish3[] = "foo: bar : eeep : baz"; std::string gibberish_headers = absl::StrCat(kGibberish1, ":", kGibberish2, "\r\n", kGibberish3, "\r\n"); std::string headers = absl::StrCat( "HTTP/1.1 200 OK\r\n" "transfer-encoding: chunked\r\n", gibberish_headers, "\r\n"); std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = absl::StrCat("k: v\n", gibberish_headers, "\n"); balsa_frame_.set_is_request(false); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); FakeHeaders fake_trailers; fake_trailers.AddKeyValue("k", "v"); fake_trailers.AddKeyValue(kGibberish1, kGibberish2); fake_trailers.AddKeyValue("foo", "bar : eeep : baz"); EXPECT_CALL(visitor_mock_, OnTrailers(fake_trailers)); ASSERT_EQ(trailer.size(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); EXPECT_TRUE(headers_.transfer_encoding_is_chunked()); absl::string_view field_value = headers_.GetHeader(kGibberish1); EXPECT_EQ(kGibberish2, field_value); field_value = headers_.GetHeader("foo"); EXPECT_EQ("bar : eeep : baz", field_value); } TEST_F(HTTPBalsaFrameTest, TrailerTooLong) { std::string headers = "HTTP/1.0 200 ok\r\n" "transfer-encoding: chunked\r\n" "\r\n"; std::string chunks = "3\r\n" "123\r\n" "0\r\n"; std::string trailer = "very : long trailer\n" "should:cause\r\n" "trailer :too long error\n" "\r\n"; balsa_frame_.set_is_request(false); ASSERT_LT(headers.size(), trailer.size()); balsa_frame_.set_max_header_length(headers.size()); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::TRAILER_TOO_LONG)); EXPECT_CALL(visitor_mock_, OnTrailers(_)).Times(0); EXPECT_CALL(visitor_mock_, MessageDone()).Times(0); ASSERT_EQ(headers.size(), balsa_frame_.ProcessInput(headers.data(), headers.size())); ASSERT_EQ(chunks.size(), balsa_frame_.ProcessInput(chunks.data(), chunks.size())); EXPECT_EQ(balsa_frame_.max_header_length(), balsa_frame_.ProcessInput(trailer.data(), trailer.size())); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::TRAILER_TOO_LONG, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, Parse100ContinueNoContinueHeadersNoCallback) { std::string continue_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(false); InSequence s; EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(balsa_frame_.ProcessInput(continue_headers.data(), continue_headers.size()), continue_headers.size()) << balsa_frame_.ErrorCode(); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(headers_.parsed_response_code(), 100); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, Parse100Continue) { std::string continue_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 100)))); EXPECT_CALL(visitor_mock_, HeaderDone()).Times(0); EXPECT_CALL(visitor_mock_, MessageDone()).Times(0); ASSERT_EQ(balsa_frame_.ProcessInput(continue_headers.data(), continue_headers.size()), continue_headers.size()) << balsa_frame_.ErrorCode(); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(headers_.parsed_response_code(), 0u); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); } TEST_F(HTTPBalsaFrameTest, Support100ContinueNoCallback) { std::string initial_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; std::string real_headers = "HTTP/1.1 200 OK\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); BalsaHeaders continue_headers; balsa_frame_.set_continue_headers(&continue_headers); balsa_frame_.set_use_interim_headers_callback(false); ASSERT_EQ(initial_headers.size(), balsa_frame_.ProcessInput(initial_headers.data(), initial_headers.size())); ASSERT_EQ(real_headers.size(), balsa_frame_.ProcessInput(real_headers.data(), real_headers.size())) << balsa_frame_.ErrorCode(); ASSERT_EQ(body.size(), balsa_frame_.ProcessInput(body.data(), body.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, Support100Continue) { std::string initial_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; std::string real_headers = "HTTP/1.1 200 OK\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 100)))); ASSERT_EQ( balsa_frame_.ProcessInput(initial_headers.data(), initial_headers.size()), initial_headers.size()); ASSERT_FALSE(balsa_frame_.Error()); EXPECT_CALL(visitor_mock_, HeaderDone()); ASSERT_EQ(balsa_frame_.ProcessInput(real_headers.data(), real_headers.size()), real_headers.size()) << balsa_frame_.ErrorCode(); EXPECT_EQ(headers_.parsed_response_code(), 200); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(balsa_frame_.ProcessInput(body.data(), body.size()), body.size()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(balsa_frame_.ErrorCode(), BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, InterimHeadersCallbackTakesPrecedence) { std::string initial_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; std::string real_headers = "HTTP/1.1 200 OK\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); BalsaHeaders continue_headers; balsa_frame_.set_continue_headers(&continue_headers); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 100)))); EXPECT_CALL(visitor_mock_, ContinueHeaderDone).Times(0); ASSERT_EQ( balsa_frame_.ProcessInput(initial_headers.data(), initial_headers.size()), initial_headers.size()); EXPECT_EQ(continue_headers.parsed_response_code(), 0u); ASSERT_FALSE(balsa_frame_.Error()); EXPECT_CALL(visitor_mock_, HeaderDone()); ASSERT_EQ(balsa_frame_.ProcessInput(real_headers.data(), real_headers.size()), real_headers.size()) << balsa_frame_.ErrorCode(); EXPECT_EQ(headers_.parsed_response_code(), 200); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(balsa_frame_.ProcessInput(body.data(), body.size()), body.size()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(balsa_frame_.ErrorCode(), BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, Support100Continue401UnauthorizedNoCallback) { std::string initial_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; std::string real_headers = "HTTP/1.1 401 Unauthorized\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); BalsaHeaders continue_headers; balsa_frame_.set_continue_headers(&continue_headers); balsa_frame_.set_use_interim_headers_callback(false); ASSERT_EQ(initial_headers.size(), balsa_frame_.ProcessInput(initial_headers.data(), initial_headers.size())); ASSERT_EQ(real_headers.size(), balsa_frame_.ProcessInput(real_headers.data(), real_headers.size())) << balsa_frame_.ErrorCode(); ASSERT_EQ(body.size(), balsa_frame_.ProcessInput(body.data(), body.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, Support100Continue401Unauthorized) { std::string initial_headers = "HTTP/1.1 100 Continue\r\n" "\r\n"; std::string real_headers = "HTTP/1.1 401 Unauthorized\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 100)))); ASSERT_EQ( balsa_frame_.ProcessInput(initial_headers.data(), initial_headers.size()), initial_headers.size()); ASSERT_FALSE(balsa_frame_.Error()); EXPECT_CALL(visitor_mock_, HeaderDone()); ASSERT_EQ(balsa_frame_.ProcessInput(real_headers.data(), real_headers.size()), real_headers.size()) << balsa_frame_.ErrorCode(); EXPECT_EQ(headers_.parsed_response_code(), 401); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(balsa_frame_.ProcessInput(body.data(), body.size()), body.size()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(balsa_frame_.ErrorCode(), BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, Support100ContinueRunTogetherNoCallback) { std::string both_headers = "HTTP/1.1 100 Continue\r\n" "\r\n" "HTTP/1.1 200 OK\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; { InSequence s; EXPECT_CALL(visitor_mock_, ContinueHeaderDone()); EXPECT_CALL(visitor_mock_, HeaderDone()); EXPECT_CALL(visitor_mock_, MessageDone()); } balsa_frame_.set_is_request(false); BalsaHeaders continue_headers; balsa_frame_.set_continue_headers(&continue_headers); balsa_frame_.set_use_interim_headers_callback(false); ASSERT_EQ(both_headers.size(), balsa_frame_.ProcessInput(both_headers.data(), both_headers.size())) << balsa_frame_.ErrorCode(); ASSERT_EQ(body.size(), balsa_frame_.ProcessInput(body.data(), body.size())); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, Support100ContinueRunTogether) { std::string both_headers = "HTTP/1.1 100 Continue\r\n" "\r\n" "HTTP/1.1 200 OK\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 100)))); EXPECT_CALL(visitor_mock_, HeaderDone()); ASSERT_EQ(balsa_frame_.ProcessInput(both_headers.data(), both_headers.size()), both_headers.size()) << balsa_frame_.ErrorCode(); ASSERT_FALSE(balsa_frame_.Error()); EXPECT_EQ(headers_.parsed_response_code(), 200); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(balsa_frame_.ProcessInput(body.data(), body.size()), body.size()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(balsa_frame_.ErrorCode(), BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, MultipleInterimHeaders) { std::string all_headers = "HTTP/1.1 100 Continue\r\n" "\r\n" "HTTP/1.1 103 Early Hints\r\n" "\r\n" "HTTP/1.1 200 OK\r\n" "content-length: 3\r\n" "\r\n"; std::string body = "foo"; balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 100)))); EXPECT_CALL(visitor_mock_, OnInterimHeaders(Pointee(Property( &BalsaHeaders::parsed_response_code, 103)))); EXPECT_CALL(visitor_mock_, HeaderDone()); ASSERT_EQ(balsa_frame_.ProcessInput(all_headers.data(), all_headers.size()), all_headers.size()) << balsa_frame_.ErrorCode(); ASSERT_FALSE(balsa_frame_.Error()); EXPECT_EQ(headers_.parsed_response_code(), 200); EXPECT_CALL(visitor_mock_, MessageDone()); ASSERT_EQ(balsa_frame_.ProcessInput(body.data(), body.size()), body.size()); EXPECT_TRUE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(balsa_frame_.ErrorCode(), BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, SwitchingProtocols) { const std::string headers = "HTTP/1.1 101 Switching Protocols\r\n" "\r\n"; const std::string body = "Bytes for the new protocol"; const std::string message = absl::StrCat(headers, body); balsa_frame_.set_is_request(false); balsa_frame_.set_use_interim_headers_callback(true); InSequence s; EXPECT_CALL(visitor_mock_, ProcessHeaders); EXPECT_CALL(visitor_mock_, HeaderDone()); ASSERT_EQ(balsa_frame_.ProcessInput(message.data(), message.size()), headers.size()) << balsa_frame_.ErrorCode(); ASSERT_FALSE(balsa_frame_.Error()); EXPECT_EQ(headers_.parsed_response_code(), 101); balsa_frame_.AllowArbitraryBody(); EXPECT_CALL(visitor_mock_, OnRawBodyInput("Bytes for the new protocol")); EXPECT_CALL(visitor_mock_, OnBodyChunkInput("Bytes for the new protocol")); EXPECT_CALL(visitor_mock_, MessageDone()).Times(0); ASSERT_EQ(balsa_frame_.ProcessInput(body.data(), body.size()), body.size()); EXPECT_FALSE(balsa_frame_.MessageFullyRead()); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(balsa_frame_.ErrorCode(), BalsaFrameEnums::BALSA_NO_ERROR); } TEST_F(HTTPBalsaFrameTest, Http09) { constexpr absl::string_view request = "GET /\r\n"; InSequence s; StrictMock<BalsaVisitorMock> visitor_mock; balsa_frame_.set_balsa_visitor(&visitor_mock); EXPECT_CALL( visitor_mock, HandleWarning( BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI)); EXPECT_CALL(visitor_mock, OnRequestFirstLineInput("GET /", "GET", "/", "")); EXPECT_CALL(visitor_mock, OnHeaderInput(request)); EXPECT_CALL(visitor_mock, ProcessHeaders(FakeHeaders{})); EXPECT_CALL(visitor_mock, HeaderDone()); EXPECT_CALL(visitor_mock, MessageDone()); EXPECT_EQ(request.size(), balsa_frame_.ProcessInput(request.data(), request.size())); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, ContinuationAllowed) { const std::string message = "GET / HTTP/1.1\r\n" "key1: \n value starts with obs-fold\r\n" "key2: value\n includes obs-fold\r\n" "key3: value ends in obs-fold \n \r\n" "\r\n"; FakeHeaders fake_headers; fake_headers.AddKeyValue("key1", "value starts with obs-fold"); fake_headers.AddKeyValue("key2", "value\n includes obs-fold"); fake_headers.AddKeyValue("key3", "value ends in obs-fold"); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, ContinuationDisallowed) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_header_continuation_lines = true; balsa_frame_.set_http_validation_policy(http_validation_policy); const std::string message = "GET / HTTP/1.1\r\n" "key: value\n includes obs-fold\r\n" "\r\n"; EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_FORMAT, balsa_frame_.ErrorCode()); } TEST_F(HTTPBalsaFrameTest, NullAtBeginningOrEndOfValue) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); constexpr absl::string_view null_string("\0", 1); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "key1: ", null_string, "value starts with null\r\n", "key2: value ends in null", null_string, "\r\n", "\r\n"); FakeHeaders fake_headers; fake_headers.AddKeyValue("key1", "value starts with null"); fake_headers.AddKeyValue("key2", "value ends in null"); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, NullInMiddleOfValue) { balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); constexpr absl::string_view null_string("\0", 1); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "key: value ", null_string, "includes null\r\n", "\r\n"); FakeHeaders fake_headers; fake_headers.AddKeyValue( "key", absl::StrCat("value ", null_string, "includes null")); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_CHARACTER)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, ObsTextNotFoundIfNotPresent) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_obs_text_in_field_names = true; balsa_frame_.set_http_validation_policy(http_validation_policy); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "key1: key does not contain obs-text\r\n", "\r\n"); FakeHeaders fake_headers; fake_headers.AddKeyValue("key1", "key does not contain obs-text"); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, HeaderFieldNameWithObsTextButPolicyDisabled) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_obs_text_in_field_names = false; balsa_frame_.set_http_validation_policy(http_validation_policy); balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "\x80key1: key starts with obs-text\r\n", "\r\n"); FakeHeaders fake_headers; fake_headers.AddKeyValue("\x80key1", "key starts with obs-text"); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, HeaderFieldNameWithObsTextAndPolicyEnabled) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_obs_text_in_field_names = true; balsa_frame_.set_http_validation_policy(http_validation_policy); balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kOff); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "\x80key1: key starts with obs-text\r\n", "\r\n"); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, HeaderFieldNameWithObsTextAtEndRejected) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_obs_text_in_field_names = true; balsa_frame_.set_http_validation_policy(http_validation_policy); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "key1\x93: key ends with obs-text\r\n", "\r\n"); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, HeaderFieldNameWithObsTextInMiddleRejected) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_obs_text_in_field_names = true; balsa_frame_.set_http_validation_policy(http_validation_policy); const std::string message = absl::StrCat("GET / HTTP/1.1\r\n", "ke\xffy1: key contains obs-text in middle\r\n", "\r\n"); EXPECT_CALL(visitor_mock_, HandleError(BalsaFrameEnums::INVALID_HEADER_NAME_CHARACTER)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_TRUE(balsa_frame_.Error()); } TEST_F(HTTPBalsaFrameTest, ObsTextInReasonPhraseAllowed) { HttpValidationPolicy http_validation_policy; http_validation_policy.disallow_obs_text_in_field_names = true; balsa_frame_.set_http_validation_policy(http_validation_policy); balsa_frame_.set_invalid_chars_level(BalsaFrame::InvalidCharsLevel::kError); balsa_frame_.set_is_request(false); const std::string message = absl::StrCat("HTTP/1.1 200 O\x90K\r\n", "surprising: obs-text allowed in reason phrase\r\n", "content-length: 0\r\n" "\r\n"); FakeHeaders fake_headers; fake_headers.AddKeyValue("surprising", "obs-text allowed in reason phrase"); fake_headers.AddKeyValue("content-length", "0"); EXPECT_CALL(visitor_mock_, ProcessHeaders(fake_headers)); EXPECT_EQ(message.size(), balsa_frame_.ProcessInput(message.data(), message.size())); EXPECT_FALSE(balsa_frame_.Error()); EXPECT_EQ(BalsaFrameEnums::BALSA_NO_ERROR, balsa_frame_.ErrorCode()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/balsa_frame.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/balsa_frame_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bc7bc5ac-8974-4f89-a4c2-2d032f918cc5
cpp
google/quiche
header_properties
quiche/balsa/header_properties.cc
quiche/balsa/header_properties_test.cc
#include "quiche/balsa/header_properties.h" #include <array> #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_text_utils.h" namespace quiche::header_properties { namespace { using MultivaluedHeadersSet = absl::flat_hash_set<absl::string_view, StringPieceCaseHash, StringPieceCaseEqual>; MultivaluedHeadersSet* buildMultivaluedHeaders() { return new MultivaluedHeadersSet({ "accept", "accept-charset", "accept-encoding", "accept-language", "accept-ranges", "access-control-allow-headers", "access-control-allow-methods", "access-control-expose-headers", "access-control-request-headers", "allow", "cache-control", "cdn-cache-control", "connection", "content-encoding", "content-language", "expect", "if-match", "if-none-match", "link", "pragma", "proxy-authenticate", "te", "sec-websocket-extensions", "set-cookie", "trailer", "transfer-encoding", "upgrade", "vary", "via", "warning", "www-authenticate", "x-forwarded-for", "x-go" "ogle-cache-control", }); } std::array<bool, 256> buildInvalidHeaderKeyCharLookupTable() { std::array<bool, 256> invalidCharTable; invalidCharTable.fill(false); for (uint8_t c : kInvalidHeaderKeyCharList) { invalidCharTable[c] = true; } return invalidCharTable; } std::array<bool, 256> buildInvalidHeaderKeyCharLookupTableAllowDoubleQuote() { std::array<bool, 256> invalidCharTable; invalidCharTable.fill(false); for (uint8_t c : kInvalidHeaderKeyCharListAllowDoubleQuote) { invalidCharTable[c] = true; } return invalidCharTable; } std::array<bool, 256> buildInvalidCharLookupTable() { std::array<bool, 256> invalidCharTable; invalidCharTable.fill(false); for (uint8_t c : kInvalidHeaderCharList) { invalidCharTable[c] = true; } return invalidCharTable; } std::array<bool, 256> buildInvalidPathCharLookupTable() { std::array<bool, 256> invalidCharTable; invalidCharTable.fill(true); for (uint8_t c : kValidPathCharList) { invalidCharTable[c] = false; } return invalidCharTable; } } bool IsMultivaluedHeader(absl::string_view header) { static const MultivaluedHeadersSet* const multivalued_headers = buildMultivaluedHeaders(); return multivalued_headers->contains(header); } bool IsInvalidHeaderKeyChar(uint8_t c) { static const std::array<bool, 256> invalidHeaderKeyCharTable = buildInvalidHeaderKeyCharLookupTable(); return invalidHeaderKeyCharTable[c]; } bool IsInvalidHeaderKeyCharAllowDoubleQuote(uint8_t c) { static const std::array<bool, 256> invalidHeaderKeyCharTable = buildInvalidHeaderKeyCharLookupTableAllowDoubleQuote(); return invalidHeaderKeyCharTable[c]; } bool IsInvalidHeaderChar(uint8_t c) { static const std::array<bool, 256> invalidCharTable = buildInvalidCharLookupTable(); return invalidCharTable[c]; } bool HasInvalidHeaderChars(absl::string_view value) { for (const char c : value) { if (IsInvalidHeaderChar(c)) { return true; } } return false; } bool HasInvalidPathChar(absl::string_view value) { static const std::array<bool, 256> invalidCharTable = buildInvalidPathCharLookupTable(); for (const char c : value) { if (invalidCharTable[c]) { return true; } } return false; } }
#include "quiche/balsa/header_properties.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::header_properties::test { namespace { TEST(HeaderPropertiesTest, IsMultivaluedHeaderIsCaseInsensitive) { EXPECT_TRUE(IsMultivaluedHeader("content-encoding")); EXPECT_TRUE(IsMultivaluedHeader("Content-Encoding")); EXPECT_TRUE(IsMultivaluedHeader("set-cookie")); EXPECT_TRUE(IsMultivaluedHeader("sEt-cOOkie")); EXPECT_TRUE(IsMultivaluedHeader("X-Goo" "gle-Cache-Control")); EXPECT_TRUE(IsMultivaluedHeader("access-control-expose-HEADERS")); EXPECT_FALSE(IsMultivaluedHeader("set-cook")); EXPECT_FALSE(IsMultivaluedHeader("content-length")); EXPECT_FALSE(IsMultivaluedHeader("Content-Length")); } TEST(HeaderPropertiesTest, IsInvalidHeaderKeyChar) { EXPECT_TRUE(IsInvalidHeaderKeyChar(0x00)); EXPECT_TRUE(IsInvalidHeaderKeyChar(0x06)); EXPECT_TRUE(IsInvalidHeaderKeyChar(0x09)); EXPECT_TRUE(IsInvalidHeaderKeyChar(0x1F)); EXPECT_TRUE(IsInvalidHeaderKeyChar(0x7F)); EXPECT_TRUE(IsInvalidHeaderKeyChar(' ')); EXPECT_TRUE(IsInvalidHeaderKeyChar('"')); EXPECT_TRUE(IsInvalidHeaderKeyChar('\t')); EXPECT_TRUE(IsInvalidHeaderKeyChar('\r')); EXPECT_TRUE(IsInvalidHeaderKeyChar('\n')); EXPECT_TRUE(IsInvalidHeaderKeyChar('}')); EXPECT_FALSE(IsInvalidHeaderKeyChar('a')); EXPECT_FALSE(IsInvalidHeaderKeyChar('B')); EXPECT_FALSE(IsInvalidHeaderKeyChar('7')); EXPECT_FALSE(IsInvalidHeaderKeyChar(0x42)); EXPECT_FALSE(IsInvalidHeaderKeyChar(0x7C)); EXPECT_FALSE(IsInvalidHeaderKeyChar(0x7E)); } TEST(HeaderPropertiesTest, IsInvalidHeaderKeyCharAllowDoubleQuote) { EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x00)); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x06)); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x09)); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x1F)); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7F)); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(' ')); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\t')); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\r')); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\n')); EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('}')); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('"')); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('a')); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('B')); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('7')); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x42)); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7C)); EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7E)); } TEST(HeaderPropertiesTest, IsInvalidHeaderChar) { EXPECT_TRUE(IsInvalidHeaderChar(0x00)); EXPECT_TRUE(IsInvalidHeaderChar(0x06)); EXPECT_TRUE(IsInvalidHeaderChar(0x1F)); EXPECT_TRUE(IsInvalidHeaderChar(0x7F)); EXPECT_FALSE(IsInvalidHeaderChar(0x09)); EXPECT_FALSE(IsInvalidHeaderChar(' ')); EXPECT_FALSE(IsInvalidHeaderChar('\t')); EXPECT_FALSE(IsInvalidHeaderChar('\r')); EXPECT_FALSE(IsInvalidHeaderChar('\n')); EXPECT_FALSE(IsInvalidHeaderChar('a')); EXPECT_FALSE(IsInvalidHeaderChar('B')); EXPECT_FALSE(IsInvalidHeaderChar('7')); EXPECT_FALSE(IsInvalidHeaderChar(0x42)); EXPECT_FALSE(IsInvalidHeaderChar(0x7D)); } TEST(HeaderPropertiesTest, KeyMoreRestrictiveThanValue) { for (int c = 0; c < 255; ++c) { if (IsInvalidHeaderChar(c)) { EXPECT_TRUE(IsInvalidHeaderKeyChar(c)) << c; } } } TEST(HeaderPropertiesTest, HasInvalidHeaderChars) { const char with_null[] = "Here's l\x00king at you, kid"; EXPECT_TRUE(HasInvalidHeaderChars(std::string(with_null, sizeof(with_null)))); EXPECT_TRUE(HasInvalidHeaderChars("Why's \x06 afraid of \x07? \x07\x08\x09")); EXPECT_TRUE(HasInvalidHeaderChars("\x1Flower power")); EXPECT_TRUE(HasInvalidHeaderChars("\x7Flowers more powers")); EXPECT_FALSE(HasInvalidHeaderChars("Plenty of space")); EXPECT_FALSE(HasInvalidHeaderChars("Keeping \tabs")); EXPECT_FALSE(HasInvalidHeaderChars("Al\right")); EXPECT_FALSE(HasInvalidHeaderChars("\new day")); EXPECT_FALSE(HasInvalidHeaderChars("\x42 is a nice character")); } TEST(HeaderPropertiesTest, HasInvalidPathChar) { EXPECT_FALSE(HasInvalidPathChar("")); EXPECT_FALSE(HasInvalidPathChar("/")); EXPECT_FALSE(HasInvalidPathChar("invalid_path/but/valid/chars")); EXPECT_FALSE(HasInvalidPathChar("/path/with?query;fragment")); EXPECT_FALSE(HasInvalidPathChar("/path2.fun/my_site-root/!&$=,+*()/wow")); EXPECT_FALSE(HasInvalidPathChar("/square[brackets]surprisingly/allowed")); EXPECT_FALSE(HasInvalidPathChar("/curly{braces}surprisingly/allowed")); EXPECT_FALSE(HasInvalidPathChar("/caret^pipe|surprisingly/allowed")); EXPECT_TRUE(HasInvalidPathChar("/path with spaces")); EXPECT_TRUE(HasInvalidPathChar("/path\rwith\tother\nwhitespace")); EXPECT_TRUE(HasInvalidPathChar("/backtick`")); EXPECT_TRUE(HasInvalidPathChar("/angle<brackets>also/bad")); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/header_properties.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/header_properties_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d944fc09-2809-4955-8b7e-fb42464a0952
cpp
google/quiche
balsa_headers
quiche/balsa/balsa_headers.cc
quiche/balsa/balsa_headers_test.cc
#include "quiche/balsa/balsa_headers.h" #include <sys/types.h> #include <cstdint> #include <functional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/balsa/balsa_enums.h" #include "quiche/balsa/header_properties.h" #include "quiche/common/platform/api/quiche_header_policy.h" #include "quiche/common/platform/api/quiche_logging.h" namespace { constexpr absl::string_view kContentLength("Content-Length"); constexpr absl::string_view kCookie("Cookie"); constexpr absl::string_view kHost("Host"); constexpr absl::string_view kTransferEncoding("Transfer-Encoding"); #define ALL_ENVOY_HEADERS(HEADER_FUNC) \ HEADER_FUNC("Accept") \ HEADER_FUNC("Accept-Encoding") \ HEADER_FUNC("Access-Control-Request-Headers") \ HEADER_FUNC("Access-Control-Request-Method") \ HEADER_FUNC("Access-Control-Allow-Origin") \ HEADER_FUNC("Access-Control-Allow-Headers") \ HEADER_FUNC("Access-Control-Allow-Methods") \ HEADER_FUNC("Access-Control-Allow-Credentials") \ HEADER_FUNC("Access-Control-Expose-Headers") \ HEADER_FUNC("Access-Control-Max-Age") \ HEADER_FUNC("Authorization") \ HEADER_FUNC("Cache-Control") \ HEADER_FUNC("X-Client-Trace-Id") \ HEADER_FUNC("Connection") \ HEADER_FUNC("Content-Encoding") \ HEADER_FUNC("Content-Length") \ HEADER_FUNC("Content-Type") \ \ HEADER_FUNC("Envoy-Attempt-Count") \ HEADER_FUNC("Envoy-Degraded") \ HEADER_FUNC("Envoy-Decorator-Operation") \ HEADER_FUNC("Envoy-Downstream-Service-Cluster") \ HEADER_FUNC("Envoy-Downstream-Service-Node") \ HEADER_FUNC("Envoy-Expected-Request-Timeout-Ms") \ HEADER_FUNC("Envoy-External-Address") \ HEADER_FUNC("Envoy-Force-Trace") \ HEADER_FUNC("Envoy-Hedge-On-Per-Try-Timeout") \ HEADER_FUNC("Envoy-Immediate-Health-Check-Fail") \ HEADER_FUNC("Envoy-Internal-Request") \ HEADER_FUNC("Envoy-Ip-Tags") \ HEADER_FUNC("Envoy-Max-Retries") \ HEADER_FUNC("Envoy-Original-Path") \ HEADER_FUNC("Envoy-Original-Url") \ HEADER_FUNC("Envoy-Overloaded") \ HEADER_FUNC("Envoy-Rate-Limited") \ HEADER_FUNC("Envoy-Retry-On") \ HEADER_FUNC("Envoy-Retry-Grpc-On") \ HEADER_FUNC("Envoy-Retriable-StatusCodes") \ HEADER_FUNC("Envoy-Retriable-HeaderNames") \ HEADER_FUNC("Envoy-Upstream-AltStatName") \ HEADER_FUNC("Envoy-Upstream-Canary") \ HEADER_FUNC("Envoy-Upstream-HealthCheckedCluster") \ HEADER_FUNC("Envoy-Upstream-RequestPerTryTimeoutMs") \ HEADER_FUNC("Envoy-Upstream-RequestTimeoutAltResponse") \ HEADER_FUNC("Envoy-Upstream-RequestTimeoutMs") \ HEADER_FUNC("Envoy-Upstream-ServiceTime") \ HEADER_FUNC("Etag") \ HEADER_FUNC("Expect") \ HEADER_FUNC("X-Forwarded-Client-Cert") \ HEADER_FUNC("X-Forwarded-For") \ HEADER_FUNC("X-Forwarded-Proto") \ HEADER_FUNC("Grpc-Accept-Encoding") \ HEADER_FUNC("Grpc-Message") \ HEADER_FUNC("Grpc-Status") \ HEADER_FUNC("Grpc-Timeout") \ HEADER_FUNC("Host") \ HEADER_FUNC("Keep-Alive") \ \ \ HEADER_FUNC("Method") \ HEADER_FUNC("No-Chunks") \ HEADER_FUNC("Origin") \ HEADER_FUNC("X-Ot-Span-Context") \ HEADER_FUNC("Path") \ HEADER_FUNC("Protocol") \ HEADER_FUNC("Proxy-Connection") \ HEADER_FUNC("Referer") \ HEADER_FUNC("X-Request-Id") \ HEADER_FUNC("Scheme") \ HEADER_FUNC("Server") \ HEADER_FUNC("Status") \ HEADER_FUNC("TE") \ HEADER_FUNC("Transfer-Encoding") \ HEADER_FUNC("Upgrade") \ HEADER_FUNC("User-Agent") \ HEADER_FUNC("Vary") \ HEADER_FUNC("Via") #define MULTIVALUE_ENVOY_HEADER(name) {name}, absl::string_view::difference_type FindIgnoreCase(absl::string_view haystack, absl::string_view needle) { absl::string_view::difference_type pos = 0; while (haystack.size() >= needle.size()) { if (absl::StartsWithIgnoreCase(haystack, needle)) { return pos; } ++pos; haystack.remove_prefix(1); } return absl::string_view::npos; } absl::string_view::difference_type RemoveLeadingWhitespace( absl::string_view* text) { size_t count = 0; const char* ptr = text->data(); while (count < text->size() && absl::ascii_isspace(*ptr)) { count++; ptr++; } text->remove_prefix(count); return count; } absl::string_view::difference_type RemoveTrailingWhitespace( absl::string_view* text) { size_t count = 0; const char* ptr = text->data() + text->size() - 1; while (count < text->size() && absl::ascii_isspace(*ptr)) { ++count; --ptr; } text->remove_suffix(count); return count; } absl::string_view::difference_type RemoveWhitespaceContext( absl::string_view* text) { return RemoveLeadingWhitespace(text) + RemoveTrailingWhitespace(text); } } namespace quiche { const size_t BalsaBuffer::kDefaultBlocksize; const BalsaHeaders::MultivaluedHeadersSet& BalsaHeaders::multivalued_envoy_headers() { static const MultivaluedHeadersSet* multivalued_envoy_headers = new MultivaluedHeadersSet({ALL_ENVOY_HEADERS(MULTIVALUE_ENVOY_HEADER)}); return *multivalued_envoy_headers; } void BalsaHeaders::ParseTokenList(absl::string_view header_value, HeaderTokenList* tokens) { if (header_value.empty()) { return; } const char* start = header_value.data(); const char* end = header_value.data() + header_value.size(); while (true) { while (*start == ',' || static_cast<unsigned char>(*start) <= ' ') { ++start; if (start == end) { return; } } const char* nws = start; while (*start != ',' && static_cast<unsigned char>(*start) > ' ') { ++start; if (start == end) { if (nws != start) { tokens->push_back(absl::string_view(nws, start - nws)); } return; } } tokens->push_back(absl::string_view(nws, start - nws)); } } void BalsaHeaders::Clear() { balsa_buffer_.Clear(); transfer_encoding_is_chunked_ = false; content_length_ = 0; content_length_status_ = BalsaHeadersEnums::NO_CONTENT_LENGTH; parsed_response_code_ = 0; firstline_buffer_base_idx_ = 0; whitespace_1_idx_ = 0; non_whitespace_1_idx_ = 0; whitespace_2_idx_ = 0; non_whitespace_2_idx_ = 0; whitespace_3_idx_ = 0; non_whitespace_3_idx_ = 0; whitespace_4_idx_ = 0; header_lines_.clear(); header_lines_.shrink_to_fit(); } void BalsaHeaders::CopyFrom(const BalsaHeaders& other) { if (this == &other) { return; } balsa_buffer_.CopyFrom(other.balsa_buffer_); transfer_encoding_is_chunked_ = other.transfer_encoding_is_chunked_; content_length_ = other.content_length_; content_length_status_ = other.content_length_status_; parsed_response_code_ = other.parsed_response_code_; firstline_buffer_base_idx_ = other.firstline_buffer_base_idx_; whitespace_1_idx_ = other.whitespace_1_idx_; non_whitespace_1_idx_ = other.non_whitespace_1_idx_; whitespace_2_idx_ = other.whitespace_2_idx_; non_whitespace_2_idx_ = other.non_whitespace_2_idx_; whitespace_3_idx_ = other.whitespace_3_idx_; non_whitespace_3_idx_ = other.non_whitespace_3_idx_; whitespace_4_idx_ = other.whitespace_4_idx_; header_lines_ = other.header_lines_; } void BalsaHeaders::AddAndMakeDescription(absl::string_view key, absl::string_view value, HeaderLineDescription* d) { QUICHE_CHECK(d != nullptr); if (enforce_header_policy_) { QuicheHandleHeaderPolicy(key); } size_t line_size = key.size() + 2 + value.size(); BalsaBuffer::Blocks::size_type block_buffer_idx = 0; char* storage = balsa_buffer_.Reserve(line_size, &block_buffer_idx); size_t base_idx = storage - GetPtr(block_buffer_idx); char* cur_loc = storage; memcpy(cur_loc, key.data(), key.size()); cur_loc += key.size(); *cur_loc = ':'; ++cur_loc; *cur_loc = ' '; ++cur_loc; memcpy(cur_loc, value.data(), value.size()); *d = HeaderLineDescription( base_idx, base_idx + key.size(), base_idx + key.size() + 2, base_idx + key.size() + 2 + value.size(), block_buffer_idx); } void BalsaHeaders::AppendAndMakeDescription(absl::string_view key, absl::string_view value, HeaderLineDescription* d) { size_t old_value_size = d->last_char_idx - d->value_begin_idx; if (old_value_size == 0) { AddAndMakeDescription(key, value, d); return; } absl::string_view old_value(GetPtr(d->buffer_base_idx) + d->value_begin_idx, old_value_size); BalsaBuffer::Blocks::size_type block_buffer_idx = 0; size_t new_size = key.size() + 3 + old_value_size + value.size(); char* storage = balsa_buffer_.Reserve(new_size, &block_buffer_idx); size_t base_idx = storage - GetPtr(block_buffer_idx); absl::string_view first_value = old_value; absl::string_view second_value = value; char* cur_loc = storage; memcpy(cur_loc, key.data(), key.size()); cur_loc += key.size(); *cur_loc = ':'; ++cur_loc; *cur_loc = ' '; ++cur_loc; memcpy(cur_loc, first_value.data(), first_value.size()); cur_loc += first_value.size(); *cur_loc = ','; ++cur_loc; memcpy(cur_loc, second_value.data(), second_value.size()); *d = HeaderLineDescription(base_idx, base_idx + key.size(), base_idx + key.size() + 2, base_idx + new_size, block_buffer_idx); } void BalsaHeaders::MaybeClearSpecialHeaderValues(absl::string_view key) { if (absl::EqualsIgnoreCase(key, kContentLength)) { if (transfer_encoding_is_chunked_) { return; } content_length_status_ = BalsaHeadersEnums::NO_CONTENT_LENGTH; content_length_ = 0; return; } if (absl::EqualsIgnoreCase(key, kTransferEncoding)) { transfer_encoding_is_chunked_ = false; } } void BalsaHeaders::RemoveAllOfHeaderStartingAt(absl::string_view key, HeaderLines::iterator start) { MaybeClearSpecialHeaderValues(key); while (start != header_lines_.end()) { start->skip = true; ++start; start = GetHeaderLinesIterator(key, start); } } void BalsaHeaders::ReplaceOrAppendHeader(absl::string_view key, absl::string_view value) { const HeaderLines::iterator end = header_lines_.end(); const HeaderLines::iterator begin = header_lines_.begin(); HeaderLines::iterator i = GetHeaderLinesIterator(key, begin); if (i != end) { RemoveAllOfHeaderStartingAt(key, i); AddAndMakeDescription(key, value, &(*i)); return; } AppendHeader(key, value); } void BalsaHeaders::AppendHeader(absl::string_view key, absl::string_view value) { HeaderLineDescription hld; AddAndMakeDescription(key, value, &hld); header_lines_.push_back(hld); } void BalsaHeaders::AppendToHeader(absl::string_view key, absl::string_view value) { HeaderLines::iterator i = GetHeaderLinesIterator(key, header_lines_.begin()); if (i == header_lines_.end()) { AppendHeader(key, value); return; } HeaderLineDescription hld = *i; AppendAndMakeDescription(key, value, &hld); i->skip = true; header_lines_.push_back(hld); } void BalsaHeaders::AppendToHeaderWithCommaAndSpace(absl::string_view key, absl::string_view value) { HeaderLines::iterator i = GetHeaderLinesIteratorForLastMultivaluedHeader(key); if (i == header_lines_.end()) { AppendHeader(key, value); return; } std::string space_and_value = absl::StrCat(" ", value); HeaderLineDescription hld = *i; AppendAndMakeDescription(key, space_and_value, &hld); i->skip = true; header_lines_.push_back(hld); } absl::string_view BalsaHeaders::GetValueFromHeaderLineDescription( const HeaderLineDescription& line) const { QUICHE_DCHECK_GE(line.last_char_idx, line.value_begin_idx); return absl::string_view(GetPtr(line.buffer_base_idx) + line.value_begin_idx, line.last_char_idx - line.value_begin_idx); } absl::string_view BalsaHeaders::GetHeader(absl::string_view key) const { QUICHE_DCHECK(!header_properties::IsMultivaluedHeader(key)) << "Header '" << key << "' may consist of multiple lines. Do not " << "use BalsaHeaders::GetHeader() or you may be missing some of its " << "values."; const HeaderLines::const_iterator end = header_lines_.end(); HeaderLines::const_iterator i = GetConstHeaderLinesIterator(key); if (i == end) { return absl::string_view(); } return GetValueFromHeaderLineDescription(*i); } BalsaHeaders::const_header_lines_iterator BalsaHeaders::GetHeaderPosition( absl::string_view key) const { const HeaderLines::const_iterator end = header_lines_.end(); HeaderLines::const_iterator i = GetConstHeaderLinesIterator(key); if (i == end) { return lines().end(); } return const_header_lines_iterator(this, (i - header_lines_.begin())); } BalsaHeaders::const_header_lines_key_iterator BalsaHeaders::GetIteratorForKey( absl::string_view key) const { HeaderLines::const_iterator i = GetConstHeaderLinesIterator(key); if (i == header_lines_.end()) { return header_lines_key_end(); } return const_header_lines_key_iterator(this, (i - header_lines_.begin()), key); } BalsaHeaders::HeaderLines::const_iterator BalsaHeaders::GetConstHeaderLinesIterator(absl::string_view key) const { const HeaderLines::const_iterator end = header_lines_.end(); for (HeaderLines::const_iterator i = header_lines_.begin(); i != end; ++i) { const HeaderLineDescription& line = *i; if (line.skip) { continue; } const absl::string_view current_key( GetPtr(line.buffer_base_idx) + line.first_char_idx, line.key_end_idx - line.first_char_idx); if (absl::EqualsIgnoreCase(current_key, key)) { QUICHE_DCHECK_GE(line.last_char_idx, line.value_begin_idx); return i; } } return end; } BalsaHeaders::HeaderLines::iterator BalsaHeaders::GetHeaderLinesIterator( absl::string_view key, BalsaHeaders::HeaderLines::iterator start) { const HeaderLines::iterator end = header_lines_.end(); for (HeaderLines::iterator i = start; i != end; ++i) { const HeaderLineDescription& line = *i; if (line.skip) { continue; } const absl::string_view current_key( GetPtr(line.buffer_base_idx) + line.first_char_idx, line.key_end_idx - line.first_char_idx); if (absl::EqualsIgnoreCase(current_key, key)) { QUICHE_DCHECK_GE(line.last_char_idx, line.value_begin_idx); return i; } } return end; } BalsaHeaders::HeaderLines::iterator BalsaHeaders::GetHeaderLinesIteratorForLastMultivaluedHeader( absl::string_view key) { const HeaderLines::iterator end = header_lines_.end(); HeaderLines::iterator last_found_match; bool found_a_match = false; for (HeaderLines::iterator i = header_lines_.begin(); i != end; ++i) { const HeaderLineDescription& line = *i; if (line.skip) { continue; } const absl::string_view current_key( GetPtr(line.buffer_base_idx) + line.first_char_idx, line.key_end_idx - line.first_char_idx); if (absl::EqualsIgnoreCase(current_key, key)) { QUICHE_DCHECK_GE(line.last_char_idx, line.value_begin_idx); last_found_match = i; found_a_match = true; } } return (found_a_match ? last_found_match : end); } void BalsaHeaders::GetAllOfHeader(absl::string_view key, std::vector<absl::string_view>* out) const { for (const_header_lines_key_iterator it = GetIteratorForKey(key); it != lines().end(); ++it) { out->push_back(it->second); } } void BalsaHeaders::GetAllOfHeaderIncludeRemoved( absl::string_view key, std::vector<absl::string_view>* out) const { const HeaderLines::const_iterator begin = header_lines_.begin(); const HeaderLines::const_iterator end = header_lines_.end(); for (bool add_removed : {false, true}) { for (HeaderLines::const_iterator i = begin; i != end; ++i) { const HeaderLineDescription& line = *i; if ((!add_removed && line.skip) || (add_removed && !line.skip)) { continue; } const absl::string_view current_key( GetPtr(line.buffer_base_idx) + line.first_char_idx, line.key_end_idx - line.first_char_idx); if (absl::EqualsIgnoreCase(current_key, key)) { QUICHE_DCHECK_GE(line.last_char_idx, line.value_begin_idx); out->push_back(GetValueFromHeaderLineDescription(line)); } } } } namespace { bool SurroundedOnlyBySpacesAndCommas(absl::string_view::difference_type idx, absl::string_view::difference_type end_idx, absl::string_view line) { for (idx = idx - 1; idx >= 0; --idx) { if (line[idx] == ',') { break; } if (line[idx] != ' ') { return false; } } for (; end_idx < static_cast<int64_t>(line.size()); ++end_idx) { if (line[end_idx] == ',') { break; } if (line[end_idx] != ' ') { return false; } } return true; } } bool BalsaHeaders::HeaderHasValueHelper(absl::string_view key, absl::string_view value, bool case_sensitive) const { for (const_header_lines_key_iterator it = GetIteratorForKey(key); it != lines().end(); ++it) { absl::string_view line = it->second; absl::string_view::size_type idx = case_sensitive ? line.find(value, 0) : FindIgnoreCase(line, value); while (idx != absl::string_view::npos) { absl::string_view::difference_type end_idx = idx + value.size(); if (SurroundedOnlyBySpacesAndCommas(idx, end_idx, line)) { return true; } idx = line.find(value, idx + 1); } } return false; } bool BalsaHeaders::HasNonEmptyHeader(absl::string_view key) const { for (const_header_lines_key_iterator it = GetIteratorForKey(key); it != header_lines_key_end(); ++it) { if (!it->second.empty()) { return true; } } return false; } std::string BalsaHeaders::GetAllOfHeaderAsString(absl::string_view key) const { auto formatter = [](std::string* out, std::pair<absl::string_view, absl::string_view> header) { return absl::AlphaNumFormatter()(out, header.second); }; return absl::StrJoin(GetIteratorForKey(key), header_lines_key_end(), ",", formatter); } void BalsaHeaders::RemoveAllOfHeaderInList(const HeaderTokenList& keys) { if (keys.empty()) { return; } absl::flat_hash_set<std::string> lowercase_keys; lowercase_keys.reserve(keys.size()); for (const auto& key : keys) { MaybeClearSpecialHeaderValues(key); lowercase_keys.insert(absl::AsciiStrToLower(key)); } for (HeaderLineDescription& line : header_lines_) { if (line.skip) { continue; } const size_t key_len = line.key_end_idx - line.first_char_idx; absl::string_view key(GetPtr(line.buffer_base_idx) + line.first_char_idx, key_len); std::string lowercase_key = absl::AsciiStrToLower(key); if (lowercase_keys.count(lowercase_key) != 0) { line.skip = true; } } } void BalsaHeaders::RemoveAllOfHeader(absl::string_view key) { HeaderLines::iterator it = GetHeaderLinesIterator(key, header_lines_.begin()); RemoveAllOfHeaderStartingAt(key, it); } void BalsaHeaders::RemoveAllHeadersWithPrefix(absl::string_view prefix) { for (HeaderLines::size_type i = 0; i < header_lines_.size(); ++i) { if (header_lines_[i].skip) { continue; } HeaderLineDescription& line = header_lines_[i]; const size_t key_len = line.key_end_idx - line.first_char_idx; if (key_len < prefix.size()) { continue; } const absl::string_view current_key_prefix( GetPtr(line.buffer_base_idx) + line.first_char_idx, prefix.size()); if (absl::EqualsIgnoreCase(current_key_prefix, prefix)) { const absl::string_view current_key( GetPtr(line.buffer_base_idx) + line.first_char_idx, key_len); MaybeClearSpecialHeaderValues(current_key); line.skip = true; } } } bool BalsaHeaders::HasHeadersWithPrefix(absl::string_view prefix) const { for (HeaderLines::size_type i = 0; i < header_lines_.size(); ++i) { if (header_lines_[i].skip) { continue; } const HeaderLineDescription& line = header_lines_[i]; if (line.key_end_idx - line.first_char_idx < prefix.size()) { continue; } const absl::string_view current_key_prefix( GetPtr(line.buffer_base_idx) + line.first_char_idx, prefix.size()); if (absl::EqualsIgnoreCase(current_key_prefix, prefix)) { return true; } } return false; } void BalsaHeaders::GetAllOfHeaderWithPrefix( absl::string_view prefix, std::vector<std::pair<absl::string_view, absl::string_view>>* out) const { for (HeaderLines::size_type i = 0; i < header_lines_.size(); ++i) { if (header_lines_[i].skip) { continue; } const HeaderLineDescription& line = header_lines_[i]; absl::string_view key(GetPtr(line.buffer_base_idx) + line.first_char_idx, line.key_end_idx - line.first_char_idx); if (absl::StartsWithIgnoreCase(key, prefix)) { out->push_back(std::make_pair( key, absl::string_view(GetPtr(line.buffer_base_idx) + line.value_begin_idx, line.last_char_idx - line.value_begin_idx))); } } } void BalsaHeaders::GetAllHeadersWithLimit( std::vector<std::pair<absl::string_view, absl::string_view>>* out, int limit) const { for (HeaderLines::size_type i = 0; i < header_lines_.size(); ++i) { if (limit >= 0 && out->size() >= static_cast<size_t>(limit)) { return; } if (header_lines_[i].skip) { continue; } const HeaderLineDescription& line = header_lines_[i]; absl::string_view key(GetPtr(line.buffer_base_idx) + line.first_char_idx, line.key_end_idx - line.first_char_idx); out->push_back(std::make_pair( key, absl::string_view(GetPtr(line.buffer_base_idx) + line.value_begin_idx, line.last_char_idx - line.value_begin_idx))); } } size_t BalsaHeaders::RemoveValue(absl::string_view key, absl::string_view search_value) { absl::string_view needle = search_value; RemoveWhitespaceContext(&needle); QUICHE_BUG_IF(bug_22783_2, needle != search_value) << "Search value should not be surrounded by spaces."; if (needle.empty()) { return 0; } size_t removals = 0; for (HeaderLines::iterator it = GetHeaderLinesIterator(key, header_lines_.begin()); it != header_lines_.end(); it = GetHeaderLinesIterator(key, ++it)) { HeaderLineDescription* line = &(*it); if (line->ValuesLength() < needle.size()) { continue; } char* buf = GetPtr(line->buffer_base_idx); char* value_begin = buf + line->value_begin_idx; absl::string_view values(value_begin, line->ValuesLength()); RemoveWhitespaceContext(&values); if (values.size() == needle.size()) { if (values == needle) { line->skip = true; removals++; } continue; } char* insertion = value_begin; while (values.size() >= needle.size()) { ssize_t cur_leading_whitespace = RemoveLeadingWhitespace(&values); bool found = absl::StartsWith(values, needle); const size_t next_comma = values.find(',', (found ? needle.size() : 0)); const bool comma_found = next_comma != absl::string_view::npos; const size_t cur_size = (comma_found ? next_comma + 1 : values.size()); if (found && cur_size != needle.size()) { absl::string_view cur(values.data(), cur_size); if (comma_found) { cur.remove_suffix(1); } RemoveTrailingWhitespace(&cur); found = (cur.size() == needle.size()); } if (found) { removals++; if (!comma_found) { insertion--; } } else { if (insertion + cur_leading_whitespace != values.data()) { memmove(insertion, values.data(), cur_size); insertion += cur_size; } else { insertion += cur_leading_whitespace + cur_size; } } values.remove_prefix(cur_size); } if (!values.empty()) { if (insertion != values.data()) { memmove(insertion, values.data(), values.size()); } insertion += values.size(); } if (insertion <= value_begin) { line->skip = true; } else { line->last_char_idx = insertion - buf; } } return removals; } size_t BalsaHeaders::GetSizeForWriteBuffer() const { size_t write_buf_size = whitespace_4_idx_ - non_whitespace_1_idx_ + 2; const HeaderLines::size_type end = header_lines_.size(); for (HeaderLines::size_type i = 0; i < end; ++i) { const HeaderLineDescription& line = header_lines_[i]; if (!line.skip) { write_buf_size += line.key_end_idx - line.first_char_idx + 2; write_buf_size += line.last_char_idx - line.value_begin_idx + 2; } } return write_buf_size + 2; } void BalsaHeaders::DumpToString(std::string* str) const { DumpToPrefixedString(" ", str); } std::string BalsaHeaders::DebugString() const { std::string s; DumpToString(&s); return s; } bool BalsaHeaders::ForEachHeader( quiche::UnretainedCallback<bool(const absl::string_view key, const absl::string_view value)> fn) const { int s = header_lines_.size(); for (int i = 0; i < s; ++i) { const HeaderLineDescription& desc = header_lines_[i]; if (!desc.skip && desc.KeyLength() > 0) { const char* stream_begin = GetPtr(desc.buffer_base_idx); if (!fn(absl::string_view(stream_begin + desc.first_char_idx, desc.KeyLength()), absl::string_view(stream_begin + desc.value_begin_idx, desc.ValuesLength()))) { return false; } } } return true; } void BalsaHeaders::DumpToPrefixedString(const char* spaces, std::string* str) const { const absl::string_view firstline = first_line(); const int buffer_length = GetReadableBytesFromHeaderStream(); if (firstline.empty() && buffer_length == 0) { absl::StrAppend(str, "\n", spaces, "<empty header>\n"); return; } if (!FramerIsDoneWriting()) { absl::StrAppendFormat(str, "\n%s<incomplete header len: %d>\n%s%.*s\n", spaces, buffer_length, spaces, buffer_length, OriginalHeaderStreamBegin()); return; } str->reserve(str->size() + GetSizeForWriteBuffer()); absl::StrAppend(str, "\n", spaces, firstline, "\n"); for (const auto& line : lines()) { absl::StrAppend(str, spaces, line.first, ": ", line.second, "\n"); } } void BalsaHeaders::SetContentLength(size_t length) { if (content_length_status_ == BalsaHeadersEnums::VALID_CONTENT_LENGTH && content_length_ == length) { return; } if (content_length_status_ != BalsaHeadersEnums::NO_CONTENT_LENGTH) { RemoveAllOfHeader(kContentLength); } else if (transfer_encoding_is_chunked_) { RemoveAllOfHeader(kTransferEncoding); } content_length_status_ = BalsaHeadersEnums::VALID_CONTENT_LENGTH; content_length_ = length; AppendHeader(kContentLength, absl::StrCat(length)); } void BalsaHeaders::SetTransferEncodingToChunkedAndClearContentLength() { if (transfer_encoding_is_chunked_) { return; } if (content_length_status_ != BalsaHeadersEnums::NO_CONTENT_LENGTH) { ClearContentLength(); } ReplaceOrAppendHeader(kTransferEncoding, "chunked"); transfer_encoding_is_chunked_ = true; } void BalsaHeaders::SetNoTransferEncoding() { if (transfer_encoding_is_chunked_) { RemoveAllOfHeader(kTransferEncoding); } } void BalsaHeaders::ClearContentLength() { RemoveAllOfHeader(kContentLength); } bool BalsaHeaders::IsEmpty() const { return balsa_buffer_.GetTotalBytesUsed() == 0; } absl::string_view BalsaHeaders::Authority() const { return GetHeader(kHost); } void BalsaHeaders::ReplaceOrAppendAuthority(absl::string_view value) { ReplaceOrAppendHeader(kHost, value); } void BalsaHeaders::RemoveAuthority() { RemoveAllOfHeader(kHost); } void BalsaHeaders::ApplyToCookie( quiche::UnretainedCallback<void(absl::string_view cookie)> f) const { f(GetHeader(kCookie)); } void BalsaHeaders::SetResponseFirstline(absl::string_view version, size_t parsed_response_code, absl::string_view reason_phrase) { SetFirstlineFromStringPieces(version, absl::StrCat(parsed_response_code), reason_phrase); parsed_response_code_ = parsed_response_code; } void BalsaHeaders::SetFirstlineFromStringPieces(absl::string_view firstline_a, absl::string_view firstline_b, absl::string_view firstline_c) { size_t line_size = (firstline_a.size() + firstline_b.size() + firstline_c.size() + 2); char* storage = balsa_buffer_.Reserve(line_size, &firstline_buffer_base_idx_); char* cur_loc = storage; memcpy(cur_loc, firstline_a.data(), firstline_a.size()); cur_loc += firstline_a.size(); *cur_loc = ' '; ++cur_loc; memcpy(cur_loc, firstline_b.data(), firstline_b.size()); cur_loc += firstline_b.size(); *cur_loc = ' '; ++cur_loc; memcpy(cur_loc, firstline_c.data(), firstline_c.size()); whitespace_1_idx_ = storage - BeginningOfFirstLine(); non_whitespace_1_idx_ = whitespace_1_idx_; whitespace_2_idx_ = non_whitespace_1_idx_ + firstline_a.size(); non_whitespace_2_idx_ = whitespace_2_idx_ + 1; whitespace_3_idx_ = non_whitespace_2_idx_ + firstline_b.size(); non_whitespace_3_idx_ = whitespace_3_idx_ + 1; whitespace_4_idx_ = non_whitespace_3_idx_ + firstline_c.size(); } void BalsaHeaders::SetRequestMethod(absl::string_view method) { if (method.size() <= (whitespace_2_idx_ - non_whitespace_1_idx_)) { non_whitespace_1_idx_ = whitespace_2_idx_ - method.size(); if (!method.empty()) { char* stream_begin = BeginningOfFirstLine(); memcpy(stream_begin + non_whitespace_1_idx_, method.data(), method.size()); } } else { SetRequestFirstlineFromStringPieces(method, request_uri(), request_version()); } } void BalsaHeaders::SetResponseVersion(absl::string_view version) { SetRequestMethod(version); } void BalsaHeaders::SetRequestUri(absl::string_view uri) { SetRequestFirstlineFromStringPieces(request_method(), uri, request_version()); } void BalsaHeaders::SetResponseCode(absl::string_view code) { SetRequestUri(code); } void BalsaHeaders::SetParsedResponseCodeAndUpdateFirstline( size_t parsed_response_code) { parsed_response_code_ = parsed_response_code; SetResponseCode(absl::StrCat(parsed_response_code)); } void BalsaHeaders::SetRequestVersion(absl::string_view version) { bool fits_in_space_allowed = version.size() + 1 <= whitespace_4_idx_ - whitespace_3_idx_; if (!fits_in_space_allowed) { SetRequestFirstlineFromStringPieces(request_method(), request_uri(), version); return; } char* stream_begin = BeginningOfFirstLine(); *(stream_begin + whitespace_3_idx_) = ' '; non_whitespace_3_idx_ = whitespace_3_idx_ + 1; whitespace_4_idx_ = non_whitespace_3_idx_ + version.size(); memcpy(stream_begin + non_whitespace_3_idx_, version.data(), version.size()); } void BalsaHeaders::SetResponseReasonPhrase(absl::string_view reason) { SetRequestVersion(reason); } void BalsaHeaders::RemoveLastTokenFromHeaderValue(absl::string_view key) { BalsaHeaders::HeaderLines::iterator it = GetHeaderLinesIterator(key, header_lines_.begin()); if (it == header_lines_.end()) { QUICHE_DLOG(WARNING) << "Attempting to remove last token from a non-existent " << "header \"" << key << "\""; return; } BalsaHeaders::HeaderLines::iterator header_line; do { header_line = it; it = GetHeaderLinesIterator(key, it + 1); } while (it != header_lines_.end()); BalsaHeaders::HeaderTokenList tokens; absl::string_view value( GetPtr(header_line->buffer_base_idx) + header_line->value_begin_idx, header_line->last_char_idx - header_line->value_begin_idx); ParseTokenList(value, &tokens); if (tokens.empty()) { QUICHE_DLOG(WARNING) << "Attempting to remove a token from an empty header value " << "for header \"" << key << "\""; header_line->skip = true; } else if (tokens.size() == 1) { header_line->skip = true; } else { absl::string_view new_last_token = tokens[tokens.size() - 2]; const char* last_char_address = new_last_token.data() + new_last_token.size() - 1; const char* const stream_begin = GetPtr(header_line->buffer_base_idx); header_line->last_char_idx = last_char_address - stream_begin + 1; } } bool BalsaHeaders::ResponseCanHaveBody(int response_code) { if (response_code >= 100 && response_code < 200) { return false; } return (response_code != 204) && (response_code != 304); } }
#include "quiche/balsa/balsa_headers.h" #include <cstring> #include <limits> #include <memory> #include <sstream> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "quiche/balsa/balsa_enums.h" #include "quiche/balsa/balsa_frame.h" #include "quiche/balsa/simple_buffer.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using absl::make_unique; using testing::AnyOf; using testing::Combine; using testing::ElementsAre; using testing::Eq; using testing::StrEq; using testing::ValuesIn; namespace quiche { namespace test { class BalsaHeadersTestPeer { public: static void WriteFromFramer(BalsaHeaders* headers, const char* ptr, size_t size) { headers->WriteFromFramer(ptr, size); } }; namespace { class BalsaBufferTest : public QuicheTest { public: void CreateBuffer(size_t blocksize) { buffer_ = std::make_unique<BalsaBuffer>(blocksize); } void CreateBuffer() { buffer_ = std::make_unique<BalsaBuffer>(); } static std::unique_ptr<BalsaBuffer> CreateUnmanagedBuffer(size_t blocksize) { return std::make_unique<BalsaBuffer>(blocksize); } absl::string_view Write(absl::string_view sp, size_t* block_buffer_idx) { if (sp.empty()) { return sp; } char* storage = buffer_->Reserve(sp.size(), block_buffer_idx); memcpy(storage, sp.data(), sp.size()); return absl::string_view(storage, sp.size()); } protected: std::unique_ptr<BalsaBuffer> buffer_; }; using BufferBlock = BalsaBuffer::BufferBlock; BufferBlock MakeBufferBlock(const std::string& s) { BufferBlock block{make_unique<char[]>(s.size()), s.size() * 2, s.size()}; std::memcpy(block.buffer.get(), s.data(), s.size()); return block; } BalsaHeaders CreateHTTPHeaders(bool request, absl::string_view s) { BalsaHeaders headers; BalsaFrame framer; framer.set_is_request(request); framer.set_balsa_headers(&headers); QUICHE_CHECK_EQ(s.size(), framer.ProcessInput(s.data(), s.size())); QUICHE_CHECK(framer.MessageFullyRead()); return headers; } class BufferBlockTest : public QuicheTestWithParam<std::tuple<const char*, const char*>> {}; TEST_P(BufferBlockTest, CopyFrom) { const std::string s1 = std::get<0>(GetParam()); const std::string s2 = std::get<1>(GetParam()); BufferBlock block; block.CopyFrom(MakeBufferBlock(s1)); EXPECT_EQ(s1.size(), block.bytes_free); ASSERT_EQ(2 * s1.size(), block.buffer_size); EXPECT_EQ(0, memcmp(s1.data(), block.buffer.get(), s1.size())); block.CopyFrom(MakeBufferBlock(s2)); EXPECT_EQ(s2.size(), block.bytes_free); ASSERT_EQ(2 * s2.size(), block.buffer_size); EXPECT_EQ(0, memcmp(s2.data(), block.buffer.get(), s2.size())); } const char* block_strings[] = {"short string", "longer than the other string"}; INSTANTIATE_TEST_SUITE_P(VariousSizes, BufferBlockTest, Combine(ValuesIn(block_strings), ValuesIn(block_strings))); TEST_F(BalsaBufferTest, BlocksizeSet) { CreateBuffer(); EXPECT_EQ(BalsaBuffer::kDefaultBlocksize, buffer_->blocksize()); CreateBuffer(1024); EXPECT_EQ(1024u, buffer_->blocksize()); } TEST_F(BalsaBufferTest, GetMemorySize) { CreateBuffer(10); EXPECT_EQ(0u, buffer_->GetTotalBytesUsed()); EXPECT_EQ(0u, buffer_->GetTotalBufferBlockSize()); BalsaBuffer::Blocks::size_type index; buffer_->Reserve(1024, &index); EXPECT_EQ(10u + 1024u, buffer_->GetTotalBufferBlockSize()); EXPECT_EQ(1024u, buffer_->GetTotalBytesUsed()); } TEST_F(BalsaBufferTest, ManyWritesToContiguousBuffer) { CreateBuffer(0); std::string data = "0123456789"; for (int i = 0; i < 120 * 1000; ++i) { buffer_->WriteToContiguousBuffer(data); } } TEST_F(BalsaBufferTest, CopyFrom) { CreateBuffer(10); std::unique_ptr<BalsaBuffer> ptr = CreateUnmanagedBuffer(1024); ASSERT_EQ(1024u, ptr->blocksize()); EXPECT_EQ(0u, ptr->num_blocks()); std::string data1 = "foobarbaz01"; buffer_->WriteToContiguousBuffer(data1); buffer_->NoMoreWriteToContiguousBuffer(); std::string data2 = "12345"; Write(data2, nullptr); std::string data3 = "6789"; Write(data3, nullptr); std::string data4 = "123456789012345"; Write(data3, nullptr); ptr->CopyFrom(*buffer_); EXPECT_EQ(ptr->can_write_to_contiguous_buffer(), buffer_->can_write_to_contiguous_buffer()); ASSERT_EQ(ptr->num_blocks(), buffer_->num_blocks()); for (size_t i = 0; i < buffer_->num_blocks(); ++i) { ASSERT_EQ(ptr->bytes_used(i), buffer_->bytes_used(i)); ASSERT_EQ(ptr->buffer_size(i), buffer_->buffer_size(i)); EXPECT_EQ(0, memcmp(ptr->GetPtr(i), buffer_->GetPtr(i), ptr->bytes_used(i))); } } TEST_F(BalsaBufferTest, ClearWorks) { CreateBuffer(10); std::string data1 = "foobarbaz01"; buffer_->WriteToContiguousBuffer(data1); buffer_->NoMoreWriteToContiguousBuffer(); std::string data2 = "12345"; Write(data2, nullptr); std::string data3 = "6789"; Write(data3, nullptr); std::string data4 = "123456789012345"; Write(data3, nullptr); buffer_->Clear(); EXPECT_TRUE(buffer_->can_write_to_contiguous_buffer()); EXPECT_EQ(10u, buffer_->blocksize()); EXPECT_EQ(0u, buffer_->num_blocks()); } TEST_F(BalsaBufferTest, ClearWorksWhenLargerThanBlocksize) { CreateBuffer(10); std::string data1 = "foobarbaz01lkjasdlkjasdlkjasd"; buffer_->WriteToContiguousBuffer(data1); buffer_->NoMoreWriteToContiguousBuffer(); std::string data2 = "12345"; Write(data2, nullptr); std::string data3 = "6789"; Write(data3, nullptr); std::string data4 = "123456789012345"; Write(data3, nullptr); buffer_->Clear(); EXPECT_TRUE(buffer_->can_write_to_contiguous_buffer()); EXPECT_EQ(10u, buffer_->blocksize()); EXPECT_EQ(0u, buffer_->num_blocks()); } TEST_F(BalsaBufferTest, ContiguousWriteSmallerThanBlocksize) { CreateBuffer(1024); std::string data1 = "foo"; buffer_->WriteToContiguousBuffer(data1); std::string composite = data1; const char* buf_ptr = buffer_->GetPtr(0); ASSERT_LE(composite.size(), buffer_->buffer_size(0)); EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size())); std::string data2 = "barbaz"; buffer_->WriteToContiguousBuffer(data2); composite += data2; buf_ptr = buffer_->GetPtr(0); ASSERT_LE(composite.size(), buffer_->buffer_size(0)); EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size())); } TEST_F(BalsaBufferTest, SingleContiguousWriteLargerThanBlocksize) { CreateBuffer(10); std::string data1 = "abracadabrawords"; buffer_->WriteToContiguousBuffer(data1); std::string composite = data1; const char* buf_ptr = buffer_->GetPtr(0); ASSERT_LE(data1.size(), buffer_->buffer_size(0)); EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size())) << composite << "\n" << absl::string_view(buf_ptr, buffer_->bytes_used(0)); } TEST_F(BalsaBufferTest, ContiguousWriteLargerThanBlocksize) { CreateBuffer(10); std::string data1 = "123456789"; buffer_->WriteToContiguousBuffer(data1); std::string composite = data1; ASSERT_LE(10u, buffer_->buffer_size(0)); std::string data2 = "0123456789"; buffer_->WriteToContiguousBuffer(data2); composite += data2; const char* buf_ptr = buffer_->GetPtr(0); ASSERT_LE(composite.size(), buffer_->buffer_size(0)); EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size())) << "composite: " << composite << "\n" << " actual: " << absl::string_view(buf_ptr, buffer_->bytes_used(0)); } TEST_F(BalsaBufferTest, TwoContiguousWritesLargerThanBlocksize) { CreateBuffer(5); std::string data1 = "123456"; buffer_->WriteToContiguousBuffer(data1); std::string composite = data1; ASSERT_LE(composite.size(), buffer_->buffer_size(0)); std::string data2 = "7890123"; buffer_->WriteToContiguousBuffer(data2); composite += data2; const char* buf_ptr = buffer_->GetPtr(0); ASSERT_LE(composite.size(), buffer_->buffer_size(0)); EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size())) << "composite: " << composite << "\n" << " actual: " << absl::string_view(buf_ptr, buffer_->bytes_used(0)); } TEST_F(BalsaBufferTest, WriteSmallerThanBlocksize) { CreateBuffer(5); std::string data1 = "1234"; size_t block_idx = 0; absl::string_view write_result = Write(data1, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data1)); CreateBuffer(5); data1 = "1234"; block_idx = 0; write_result = Write(data1, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data1)); } TEST_F(BalsaBufferTest, TwoWritesSmallerThanBlocksizeThenAnotherWrite) { CreateBuffer(10); std::string data1 = "12345"; size_t block_idx = 0; absl::string_view write_result = Write(data1, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data1)); std::string data2 = "data2"; block_idx = 0; write_result = Write(data2, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data2)); std::string data3 = "data3"; block_idx = 0; write_result = Write(data3, &block_idx); ASSERT_EQ(2u, block_idx); EXPECT_THAT(write_result, StrEq(data3)); CreateBuffer(10); buffer_->NoMoreWriteToContiguousBuffer(); data1 = "12345"; block_idx = 0; write_result = Write(data1, &block_idx); ASSERT_EQ(0u, block_idx); EXPECT_THAT(write_result, StrEq(data1)); data2 = "data2"; block_idx = 0; write_result = Write(data2, &block_idx); ASSERT_EQ(0u, block_idx); EXPECT_THAT(write_result, StrEq(data2)); data3 = "data3"; block_idx = 0; write_result = Write(data3, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data3)); } TEST_F(BalsaBufferTest, WriteLargerThanBlocksize) { CreateBuffer(5); std::string data1 = "123456789"; size_t block_idx = 0; absl::string_view write_result = Write(data1, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data1)); CreateBuffer(5); buffer_->NoMoreWriteToContiguousBuffer(); data1 = "123456789"; block_idx = 0; write_result = Write(data1, &block_idx); ASSERT_EQ(1u, block_idx); EXPECT_THAT(write_result, StrEq(data1)); } TEST_F(BalsaBufferTest, ContiguousThenTwoSmallerThanBlocksize) { CreateBuffer(5); std::string data1 = "1234567890"; buffer_->WriteToContiguousBuffer(data1); size_t block_idx = 0; std::string data2 = "1234"; absl::string_view write_result = Write(data2, &block_idx); ASSERT_EQ(1u, block_idx); std::string data3 = "1234"; write_result = Write(data3, &block_idx); ASSERT_EQ(2u, block_idx); } TEST_F(BalsaBufferTest, AccessFirstBlockUninitialized) { CreateBuffer(5); EXPECT_EQ(0u, buffer_->GetReadableBytesOfFirstBlock()); EXPECT_QUICHE_BUG(buffer_->StartOfFirstBlock(), "First block not allocated yet!"); EXPECT_QUICHE_BUG(buffer_->EndOfFirstBlock(), "First block not allocated yet!"); } TEST_F(BalsaBufferTest, AccessFirstBlockInitialized) { CreateBuffer(5); std::string data1 = "1234567890"; buffer_->WriteToContiguousBuffer(data1); const char* start = buffer_->StartOfFirstBlock(); EXPECT_TRUE(start != nullptr); const char* end = buffer_->EndOfFirstBlock(); EXPECT_TRUE(end != nullptr); EXPECT_EQ(data1.length(), static_cast<size_t>(end - start)); EXPECT_EQ(data1.length(), buffer_->GetReadableBytesOfFirstBlock()); } TEST(BalsaHeaders, CanAssignBeginToIterator) { { BalsaHeaders header; BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); static_cast<void>(chli); } { const BalsaHeaders header; BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); static_cast<void>(chli); } } TEST(BalsaHeaders, CanAssignEndToIterator) { { BalsaHeaders header; BalsaHeaders::const_header_lines_iterator chli = header.lines().end(); static_cast<void>(chli); } { const BalsaHeaders header; BalsaHeaders::const_header_lines_iterator chli = header.lines().end(); static_cast<void>(chli); } } TEST(BalsaHeaders, ReplaceOrAppendHeaderTestAppending) { BalsaHeaders header; std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.ReplaceOrAppendHeader(key_1, value_1); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ASSERT_EQ(absl::string_view("key_1"), chli->first); ASSERT_EQ(absl::string_view("value_1"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, ReplaceOrAppendHeaderTestReplacing) { BalsaHeaders header; std::string key_1 = "key_1"; std::string value_1 = "value_1"; std::string key_2 = "key_2"; header.ReplaceOrAppendHeader(key_1, value_1); header.ReplaceOrAppendHeader(key_2, value_1); std::string value_2 = "value_2_string"; header.ReplaceOrAppendHeader(key_1, value_2); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ASSERT_EQ(key_1, chli->first); ASSERT_EQ(value_2, chli->second); ++chli; ASSERT_EQ(key_2, chli->first); ASSERT_EQ(value_1, chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, ReplaceOrAppendHeaderTestReplacingMultiple) { BalsaHeaders header; std::string key_1 = "key_1"; std::string key_2 = "key_2"; std::string value_1 = "val_1"; std::string value_2 = "val_2"; std::string value_3 = "value_3_is_longer_than_value_1_and_value_2_and_their_keys"; header.AppendHeader(key_1, value_1); header.AppendHeader(key_1, value_2); header.AppendHeader(key_2, value_1); header.ReplaceOrAppendHeader(key_1, value_3); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ASSERT_EQ(key_1, chli->first); ASSERT_EQ(value_3, chli->second); ++chli; ASSERT_EQ(key_2, chli->first); ASSERT_EQ(value_1, chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); header.ReplaceOrAppendHeader(key_1, value_1); chli = header.lines().begin(); ASSERT_EQ(key_1, chli->first); ASSERT_EQ(value_1, chli->second); ++chli; ASSERT_EQ(key_2, chli->first); ASSERT_EQ(value_1, chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, AppendHeaderAndIteratorTest1) { BalsaHeaders header; ASSERT_EQ(header.lines().begin(), header.lines().end()); { std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.AppendHeader(key_1, value_1); key_1 = "garbage"; value_1 = "garbage"; } ASSERT_NE(header.lines().begin(), header.lines().end()); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ASSERT_EQ(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_1"), chli->first); ASSERT_EQ(absl::string_view("value_1"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, AppendHeaderAndIteratorTest2) { BalsaHeaders header; ASSERT_EQ(header.lines().begin(), header.lines().end()); { std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.AppendHeader(key_1, value_1); key_1 = "garbage"; value_1 = "garbage"; } { std::string key_2 = "key_2"; std::string value_2 = "value_2"; header.AppendHeader(key_2, value_2); key_2 = "garbage"; value_2 = "garbage"; } ASSERT_NE(header.lines().begin(), header.lines().end()); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ASSERT_EQ(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_1"), chli->first); ASSERT_EQ(absl::string_view("value_1"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_2"), chli->first); ASSERT_EQ(absl::string_view("value_2"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, AppendHeaderAndIteratorTest3) { BalsaHeaders header; ASSERT_EQ(header.lines().begin(), header.lines().end()); { std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.AppendHeader(key_1, value_1); key_1 = "garbage"; value_1 = "garbage"; } { std::string key_2 = "key_2"; std::string value_2 = "value_2"; header.AppendHeader(key_2, value_2); key_2 = "garbage"; value_2 = "garbage"; } { std::string key_3 = "key_3"; std::string value_3 = "value_3"; header.AppendHeader(key_3, value_3); key_3 = "garbage"; value_3 = "garbage"; } ASSERT_NE(header.lines().begin(), header.lines().end()); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ASSERT_EQ(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_1"), chli->first); ASSERT_EQ(absl::string_view("value_1"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_2"), chli->first); ASSERT_EQ(absl::string_view("value_2"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_3"), chli->first); ASSERT_EQ(absl::string_view("value_3"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, AppendHeaderAndTestEraseWithIterator) { BalsaHeaders header; ASSERT_EQ(header.lines().begin(), header.lines().end()); { std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.AppendHeader(key_1, value_1); key_1 = "garbage"; value_1 = "garbage"; } { std::string key_2 = "key_2"; std::string value_2 = "value_2"; header.AppendHeader(key_2, value_2); key_2 = "garbage"; value_2 = "garbage"; } { std::string key_3 = "key_3"; std::string value_3 = "value_3"; header.AppendHeader(key_3, value_3); key_3 = "garbage"; value_3 = "garbage"; } BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ++chli; ASSERT_EQ(absl::string_view("key_2"), chli->first); header.erase(chli); chli = header.lines().begin(); ASSERT_NE(header.lines().begin(), header.lines().end()); ASSERT_EQ(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_1"), chli->first); ASSERT_EQ(absl::string_view("value_1"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_NE(header.lines().end(), chli); ASSERT_EQ(absl::string_view("key_3"), chli->first); ASSERT_EQ(absl::string_view("value_3"), chli->second); ++chli; ASSERT_NE(header.lines().begin(), chli); ASSERT_EQ(header.lines().end(), chli); } TEST(BalsaHeaders, TestSetFirstlineInAdditionalBuffer) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0")); } TEST(BalsaHeaders, TestSetFirstlineInOriginalBufferAndIsShorterThanOriginal) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET /foobar HTTP/1.0\r\n" "\r\n"); ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0")); headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0")); } TEST(BalsaHeaders, TestSetFirstlineInOriginalBufferAndIsLongerThanOriginal) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "some_key: some_value\r\n" "another_key: another_value\r\n" "\r\n"); ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0")); headers.erase(headers.lines().begin()); headers.SetRequestFirstlineFromStringPieces("GET", "/foobar", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0")); } TEST(BalsaHeaders, TestSetFirstlineInAdditionalDataAndIsShorterThanOriginal) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/foobar", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0")); headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0")); } TEST(BalsaHeaders, TestSetFirstlineInAdditionalDataAndIsLongerThanOriginal) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0")); headers.SetRequestFirstlineFromStringPieces("GET", "/foobar", "HTTP/1.0"); ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0")); } TEST(BalsaHeaders, TestDeletingSubstring) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key2", "value2"); headers.AppendHeader("key", "value"); headers.AppendHeader("unrelated", "value"); headers.RemoveAllOfHeader("key"); EXPECT_TRUE(headers.HasHeader("key1")); EXPECT_TRUE(headers.HasHeader("key2")); EXPECT_TRUE(headers.HasHeader("unrelated")); EXPECT_FALSE(headers.HasHeader("key")); EXPECT_TRUE(headers.HasHeadersWithPrefix("key")); EXPECT_TRUE(headers.HasHeadersWithPrefix("KeY")); EXPECT_TRUE(headers.HasHeadersWithPrefix("UNREL")); EXPECT_FALSE(headers.HasHeadersWithPrefix("key3")); EXPECT_FALSE(headers.GetHeader("key1").empty()); EXPECT_FALSE(headers.GetHeader("KEY1").empty()); EXPECT_FALSE(headers.GetHeader("key2").empty()); EXPECT_FALSE(headers.GetHeader("unrelated").empty()); EXPECT_TRUE(headers.GetHeader("key").empty()); headers.AppendHeader("key", ""); EXPECT_TRUE(headers.HasHeader("key")); EXPECT_TRUE(headers.HasHeadersWithPrefix("key")); EXPECT_TRUE(headers.GetHeader("key").empty()); headers.RemoveAllHeadersWithPrefix("key"); EXPECT_FALSE(headers.HasHeader("key1")); EXPECT_FALSE(headers.HasHeader("key2")); EXPECT_TRUE(headers.HasHeader("unrelated")); EXPECT_FALSE(headers.HasHeader("key")); EXPECT_FALSE(headers.HasHeadersWithPrefix("key")); EXPECT_FALSE(headers.HasHeadersWithPrefix("key1")); EXPECT_FALSE(headers.HasHeadersWithPrefix("key2")); EXPECT_FALSE(headers.HasHeadersWithPrefix("kEy")); EXPECT_TRUE(headers.HasHeadersWithPrefix("unrelated")); EXPECT_TRUE(headers.GetHeader("key1").empty()); EXPECT_TRUE(headers.GetHeader("key2").empty()); EXPECT_FALSE(headers.GetHeader("unrelated").empty()); EXPECT_TRUE(headers.GetHeader("key").empty()); } TEST(BalsaHeaders, TestRemovingValues) { { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("hi", "hello"); headers.AppendHeader("key1", "val1"); headers.AppendHeader("key1", "value2"); headers.AppendHeader("key1", "value3"); headers.AppendHeader("key2", "value4"); headers.AppendHeader("unrelated", "value"); EXPECT_EQ(0u, headers.RemoveValue("key1", "")); EXPECT_EQ(1u, headers.RemoveValue("key1", "value2")); std::string key1_vals = headers.GetAllOfHeaderAsString("key1"); EXPECT_THAT(key1_vals, StrEq("val1,value3")); EXPECT_TRUE(headers.HeaderHasValue("key1", "val1")); EXPECT_TRUE(headers.HeaderHasValue("key1", "value3")); EXPECT_EQ("value4", headers.GetHeader("key2")); EXPECT_EQ("hello", headers.GetHeader("hi")); EXPECT_EQ("value", headers.GetHeader("unrelated")); EXPECT_FALSE(headers.HeaderHasValue("key1", "value2")); EXPECT_EQ(1u, headers.RemoveValue("key1", "value3")); key1_vals = headers.GetAllOfHeaderAsString("key1"); EXPECT_THAT(key1_vals, StrEq("val1")); EXPECT_TRUE(headers.HeaderHasValue("key1", "val1")); EXPECT_EQ("value4", headers.GetHeader("key2")); EXPECT_EQ("hello", headers.GetHeader("hi")); EXPECT_EQ("value", headers.GetHeader("unrelated")); EXPECT_FALSE(headers.HeaderHasValue("key1", "value3")); EXPECT_FALSE(headers.HeaderHasValue("key1", "value2")); } { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key1", "value2, value3,value2"); headers.AppendHeader("key1", "value4 ,value2,value5,val6"); headers.AppendHeader("key1", "value2, value2 , value2"); headers.AppendHeader("key1", " value2 , value2 "); headers.AppendHeader("key1", " value2 a"); headers.AppendHeader("key1", ""); headers.AppendHeader("key1", ", ,,"); headers.AppendHeader("unrelated", "value"); EXPECT_EQ(8u, headers.RemoveValue("key1", "value2")); std::string key1_vals = headers.GetAllOfHeaderAsString("key1"); EXPECT_THAT(key1_vals, StrEq("value1,value3,value4 ,value5,val6,value2 a,,, ,,")); EXPECT_EQ("value", headers.GetHeader("unrelated")); EXPECT_TRUE(headers.HeaderHasValue("key1", "value1")); EXPECT_TRUE(headers.HeaderHasValue("key1", "value3")); EXPECT_TRUE(headers.HeaderHasValue("key1", "value4")); EXPECT_TRUE(headers.HeaderHasValue("key1", "value5")); EXPECT_TRUE(headers.HeaderHasValue("key1", "val6")); EXPECT_FALSE(headers.HeaderHasValue("key1", "value2")); } { const absl::string_view key("key"); const absl::string_view value1("foo\0bar", 7); const absl::string_view value2("value2"); const std::string value = absl::StrCat(value1, ",", value2); { BalsaHeaders headers; headers.AppendHeader(key, value); EXPECT_TRUE(headers.HeaderHasValue(key, value1)); EXPECT_TRUE(headers.HeaderHasValue(key, value2)); EXPECT_EQ(value, headers.GetAllOfHeaderAsString(key)); EXPECT_EQ(1u, headers.RemoveValue(key, value2)); EXPECT_TRUE(headers.HeaderHasValue(key, value1)); EXPECT_FALSE(headers.HeaderHasValue(key, value2)); EXPECT_EQ(value1, headers.GetAllOfHeaderAsString(key)); } { BalsaHeaders headers; headers.AppendHeader(key, value1); headers.AppendHeader(key, value2); EXPECT_TRUE(headers.HeaderHasValue(key, value1)); EXPECT_TRUE(headers.HeaderHasValue(key, value2)); EXPECT_EQ(value, headers.GetAllOfHeaderAsString(key)); EXPECT_EQ(1u, headers.RemoveValue(key, value2)); EXPECT_TRUE(headers.HeaderHasValue(key, value1)); EXPECT_FALSE(headers.HeaderHasValue(key, value2)); EXPECT_EQ(value1, headers.GetAllOfHeaderAsString(key)); } } } TEST(BalsaHeaders, ZeroAppendToHeaderWithCommaAndSpace) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "\r\n"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "1.1.1.1"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "2.2.2.2"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "3.3.3.3"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "4.4.4.4"); EXPECT_THAT(headers.GetAllOfHeader("X-Forwarded-For"), ElementsAre("1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4")); } TEST(BalsaHeaders, SingleAppendToHeaderWithCommaAndSpace) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "X-Forwarded-For: 1.1.1.1\r\n" "\r\n"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "2.2.2.2"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "3.3.3.3"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "4.4.4.4"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "5.5.5.5"); EXPECT_THAT(headers.GetAllOfHeader("X-Forwarded-For"), ElementsAre("1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 5.5.5.5")); } TEST(BalsaHeaders, MultipleAppendToHeaderWithCommaAndSpace) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "X-Forwarded-For: 1.1.1.1\r\n" "X-Forwarded-For: 2.2.2.2\r\n" "\r\n"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "3.3.3.3"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "4.4.4.4"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "5.5.5.5"); headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "6.6.6.6"); EXPECT_THAT( headers.GetAllOfHeader("X-Forwarded-For"), ElementsAre("1.1.1.1", "2.2.2.2, 3.3.3.3, 4.4.4.4, 5.5.5.5, 6.6.6.6")); } TEST(BalsaHeaders, HeaderHasValues) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key", "val1,val2val2,val2,val3"); headers.AppendHeader("key", "val4val5val6"); headers.AppendHeader("key", "val11 val12"); headers.AppendHeader("key", "v val13"); headers.AppendHeader("key", "val7"); headers.AppendHeader("key", ""); headers.AppendHeader("key", "val8 , val9 , val10"); headers.AppendHeader("key", " val14 "); headers.AppendHeader("key2", "val15"); headers.AppendHeader("key", "Val16"); headers.AppendHeader("key", "foo, Val17, bar"); EXPECT_TRUE(headers.HeaderHasValue("key", "val1")); EXPECT_TRUE(headers.HeaderHasValue("key", "val2")); EXPECT_TRUE(headers.HeaderHasValue("key", "val3")); EXPECT_TRUE(headers.HeaderHasValue("key", "val7")); EXPECT_TRUE(headers.HeaderHasValue("key", "val8")); EXPECT_TRUE(headers.HeaderHasValue("key", "val9")); EXPECT_TRUE(headers.HeaderHasValue("key", "val10")); EXPECT_TRUE(headers.HeaderHasValue("key", "val14")); EXPECT_FALSE(headers.HeaderHasValue("key", "val4")); EXPECT_FALSE(headers.HeaderHasValue("key", "val5")); EXPECT_FALSE(headers.HeaderHasValue("key", "val6")); EXPECT_FALSE(headers.HeaderHasValue("key", "val11")); EXPECT_FALSE(headers.HeaderHasValue("key", "val12")); EXPECT_FALSE(headers.HeaderHasValue("key", "val13")); EXPECT_FALSE(headers.HeaderHasValue("key", "val15")); EXPECT_FALSE(headers.HeaderHasValue("key", "val16")); EXPECT_FALSE(headers.HeaderHasValue("key", "val17")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val1")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val2")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val3")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val7")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val8")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val9")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val10")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val14")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val4")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val5")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val6")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val11")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val12")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val13")); EXPECT_FALSE(headers.HeaderHasValueIgnoreCase("key", "val15")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val16")); EXPECT_TRUE(headers.HeaderHasValueIgnoreCase("key", "val17")); } TEST(BalsaHeaders, TestNotDeletingBeyondString) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.RemoveAllHeadersWithPrefix("key1: value1"); EXPECT_NE(headers.lines().begin(), headers.lines().end()); } TEST(BalsaHeaders, TestIteratingOverErasedHeaders) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key2", "value2"); headers.AppendHeader("key3", "value3"); headers.AppendHeader("key4", "value4"); headers.AppendHeader("key5", "value5"); headers.AppendHeader("key6", "value6"); headers.RemoveAllOfHeader("key6"); headers.RemoveAllOfHeader("key5"); headers.RemoveAllOfHeader("key4"); BalsaHeaders::const_header_lines_iterator chli = headers.lines().begin(); EXPECT_NE(headers.lines().end(), chli); EXPECT_EQ(headers.lines().begin(), chli); EXPECT_THAT(chli->first, StrEq("key1")); EXPECT_THAT(chli->second, StrEq("value1")); ++chli; EXPECT_NE(headers.lines().end(), chli); EXPECT_NE(headers.lines().begin(), chli); EXPECT_THAT(chli->first, StrEq("key2")); EXPECT_THAT(chli->second, StrEq("value2")); ++chli; EXPECT_NE(headers.lines().end(), chli); EXPECT_NE(headers.lines().begin(), chli); EXPECT_THAT(chli->first, StrEq("key3")); EXPECT_THAT(chli->second, StrEq("value3")); ++chli; EXPECT_EQ(headers.lines().end(), chli); EXPECT_NE(headers.lines().begin(), chli); headers.RemoveAllOfHeader("key1"); headers.RemoveAllOfHeader("key2"); chli = headers.lines().begin(); EXPECT_THAT(chli->first, StrEq("key3")); EXPECT_THAT(chli->second, StrEq("value3")); EXPECT_NE(headers.lines().end(), chli); EXPECT_EQ(headers.lines().begin(), chli); ++chli; EXPECT_EQ(headers.lines().end(), chli); EXPECT_NE(headers.lines().begin(), chli); } TEST(BalsaHeaders, CanCompareIterators) { BalsaHeaders header; ASSERT_EQ(header.lines().begin(), header.lines().end()); { std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.AppendHeader(key_1, value_1); key_1 = "garbage"; value_1 = "garbage"; } { std::string key_2 = "key_2"; std::string value_2 = "value_2"; header.AppendHeader(key_2, value_2); key_2 = "garbage"; value_2 = "garbage"; } BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); BalsaHeaders::const_header_lines_iterator chlj = header.lines().begin(); EXPECT_EQ(chli, chlj); ++chlj; EXPECT_NE(chli, chlj); EXPECT_LT(chli, chlj); EXPECT_LE(chli, chlj); EXPECT_LE(chli, chli); EXPECT_GT(chlj, chli); EXPECT_GE(chlj, chli); EXPECT_GE(chlj, chlj); } TEST(BalsaHeaders, AppendHeaderAndTestThatYouCanEraseEverything) { BalsaHeaders header; ASSERT_EQ(header.lines().begin(), header.lines().end()); { std::string key_1 = "key_1"; std::string value_1 = "value_1"; header.AppendHeader(key_1, value_1); key_1 = "garbage"; value_1 = "garbage"; } { std::string key_2 = "key_2"; std::string value_2 = "value_2"; header.AppendHeader(key_2, value_2); key_2 = "garbage"; value_2 = "garbage"; } { std::string key_3 = "key_3"; std::string value_3 = "value_3"; header.AppendHeader(key_3, value_3); key_3 = "garbage"; value_3 = "garbage"; } EXPECT_NE(header.lines().begin(), header.lines().end()); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); while (chli != header.lines().end()) { header.erase(chli); chli = header.lines().begin(); } ASSERT_EQ(header.lines().begin(), header.lines().end()); } TEST(BalsaHeaders, GetHeaderPositionWorksAsExpectedWithNoHeaderLines) { BalsaHeaders header; BalsaHeaders::const_header_lines_iterator i = header.GetHeaderPosition("foo"); EXPECT_EQ(i, header.lines().end()); } TEST(BalsaHeaders, GetHeaderPositionWorksAsExpectedWithBalsaFrameProcessInput) { BalsaHeaders headers = CreateHTTPHeaders( true, "GET / HTTP/1.0\r\n" "key1: value_1\r\n" "key1: value_foo\r\n" "key2: value_2\r\n" "key3: value_3\r\n" "a: value_a\r\n" "b: value_b\r\n" "\r\n"); BalsaHeaders::const_header_lines_iterator header_position_b = headers.GetHeaderPosition("b"); ASSERT_NE(header_position_b, headers.lines().end()); absl::string_view header_key_b_value = header_position_b->second; ASSERT_FALSE(header_key_b_value.empty()); EXPECT_EQ(std::string("value_b"), header_key_b_value); BalsaHeaders::const_header_lines_iterator header_position_1 = headers.GetHeaderPosition("key1"); ASSERT_NE(header_position_1, headers.lines().end()); absl::string_view header_key_1_value = header_position_1->second; ASSERT_FALSE(header_key_1_value.empty()); EXPECT_EQ(std::string("value_1"), header_key_1_value); BalsaHeaders::const_header_lines_iterator header_position_3 = headers.GetHeaderPosition("key3"); ASSERT_NE(header_position_3, headers.lines().end()); absl::string_view header_key_3_value = header_position_3->second; ASSERT_FALSE(header_key_3_value.empty()); EXPECT_EQ(std::string("value_3"), header_key_3_value); BalsaHeaders::const_header_lines_iterator header_position_2 = headers.GetHeaderPosition("key2"); ASSERT_NE(header_position_2, headers.lines().end()); absl::string_view header_key_2_value = header_position_2->second; ASSERT_FALSE(header_key_2_value.empty()); EXPECT_EQ(std::string("value_2"), header_key_2_value); BalsaHeaders::const_header_lines_iterator header_position_a = headers.GetHeaderPosition("a"); ASSERT_NE(header_position_a, headers.lines().end()); absl::string_view header_key_a_value = header_position_a->second; ASSERT_FALSE(header_key_a_value.empty()); EXPECT_EQ(std::string("value_a"), header_key_a_value); } TEST(BalsaHeaders, GetHeaderWorksAsExpectedWithNoHeaderLines) { BalsaHeaders header; absl::string_view value = header.GetHeader("foo"); EXPECT_TRUE(value.empty()); value = header.GetHeader(""); EXPECT_TRUE(value.empty()); } TEST(BalsaHeaders, HasHeaderWorksAsExpectedWithNoHeaderLines) { BalsaHeaders header; EXPECT_FALSE(header.HasHeader("foo")); EXPECT_FALSE(header.HasHeader("")); EXPECT_FALSE(header.HasHeadersWithPrefix("foo")); EXPECT_FALSE(header.HasHeadersWithPrefix("")); } TEST(BalsaHeaders, HasHeaderWorksAsExpectedWithBalsaFrameProcessInput) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "key1: value_1\r\n" "key1: value_foo\r\n" "key2:\r\n" "\r\n"); EXPECT_FALSE(headers.HasHeader("foo")); EXPECT_TRUE(headers.HasHeader("key1")); EXPECT_TRUE(headers.HasHeader("key2")); EXPECT_FALSE(headers.HasHeadersWithPrefix("foo")); EXPECT_TRUE(headers.HasHeadersWithPrefix("key")); EXPECT_TRUE(headers.HasHeadersWithPrefix("KEY")); } TEST(BalsaHeaders, GetHeaderWorksAsExpectedWithBalsaFrameProcessInput) { BalsaHeaders headers = CreateHTTPHeaders( true, "GET / HTTP/1.0\r\n" "key1: value_1\r\n" "key1: value_foo\r\n" "key2: value_2\r\n" "key3: value_3\r\n" "key4:\r\n" "a: value_a\r\n" "b: value_b\r\n" "\r\n"); absl::string_view header_key_b_value = headers.GetHeader("b"); ASSERT_FALSE(header_key_b_value.empty()); EXPECT_EQ(std::string("value_b"), header_key_b_value); absl::string_view header_key_1_value = headers.GetHeader("key1"); ASSERT_FALSE(header_key_1_value.empty()); EXPECT_EQ(std::string("value_1"), header_key_1_value); absl::string_view header_key_3_value = headers.GetHeader("key3"); ASSERT_FALSE(header_key_3_value.empty()); EXPECT_EQ(std::string("value_3"), header_key_3_value); absl::string_view header_key_2_value = headers.GetHeader("key2"); ASSERT_FALSE(header_key_2_value.empty()); EXPECT_EQ(std::string("value_2"), header_key_2_value); absl::string_view header_key_a_value = headers.GetHeader("a"); ASSERT_FALSE(header_key_a_value.empty()); EXPECT_EQ(std::string("value_a"), header_key_a_value); EXPECT_TRUE(headers.GetHeader("key4").empty()); } TEST(BalsaHeaders, GetHeaderWorksAsExpectedWithAppendHeader) { BalsaHeaders header; header.AppendHeader("key1", "value_1"); header.AppendHeader("key1", "value_2"); header.AppendHeader("key2", "value_2"); header.AppendHeader("key3", "value_3"); header.AppendHeader("a", "value_a"); header.AppendHeader("b", "value_b"); absl::string_view header_key_b_value = header.GetHeader("b"); absl::string_view header_key_1_value = header.GetHeader("key1"); absl::string_view header_key_3_value = header.GetHeader("key3"); absl::string_view header_key_2_value = header.GetHeader("key2"); absl::string_view header_key_a_value = header.GetHeader("a"); ASSERT_FALSE(header_key_1_value.empty()); ASSERT_FALSE(header_key_2_value.empty()); ASSERT_FALSE(header_key_3_value.empty()); ASSERT_FALSE(header_key_a_value.empty()); ASSERT_FALSE(header_key_b_value.empty()); EXPECT_TRUE(header.HasHeader("key1")); EXPECT_TRUE(header.HasHeader("key2")); EXPECT_TRUE(header.HasHeader("key3")); EXPECT_TRUE(header.HasHeader("a")); EXPECT_TRUE(header.HasHeader("b")); EXPECT_TRUE(header.HasHeadersWithPrefix("key1")); EXPECT_TRUE(header.HasHeadersWithPrefix("key2")); EXPECT_TRUE(header.HasHeadersWithPrefix("key3")); EXPECT_TRUE(header.HasHeadersWithPrefix("a")); EXPECT_TRUE(header.HasHeadersWithPrefix("b")); EXPECT_EQ(std::string("value_1"), header_key_1_value); EXPECT_EQ(std::string("value_2"), header_key_2_value); EXPECT_EQ(std::string("value_3"), header_key_3_value); EXPECT_EQ(std::string("value_a"), header_key_a_value); EXPECT_EQ(std::string("value_b"), header_key_b_value); } TEST(BalsaHeaders, HasHeaderWorksAsExpectedWithAppendHeader) { BalsaHeaders header; ASSERT_FALSE(header.HasHeader("key1")); EXPECT_FALSE(header.HasHeadersWithPrefix("K")); EXPECT_FALSE(header.HasHeadersWithPrefix("ke")); EXPECT_FALSE(header.HasHeadersWithPrefix("key")); EXPECT_FALSE(header.HasHeadersWithPrefix("key1")); EXPECT_FALSE(header.HasHeadersWithPrefix("key2")); header.AppendHeader("key1", "value_1"); EXPECT_TRUE(header.HasHeader("key1")); EXPECT_TRUE(header.HasHeadersWithPrefix("K")); EXPECT_TRUE(header.HasHeadersWithPrefix("ke")); EXPECT_TRUE(header.HasHeadersWithPrefix("key")); EXPECT_TRUE(header.HasHeadersWithPrefix("key1")); EXPECT_FALSE(header.HasHeadersWithPrefix("key2")); header.AppendHeader("key1", "value_2"); EXPECT_TRUE(header.HasHeader("key1")); EXPECT_FALSE(header.HasHeader("key2")); EXPECT_TRUE(header.HasHeadersWithPrefix("k")); EXPECT_TRUE(header.HasHeadersWithPrefix("ke")); EXPECT_TRUE(header.HasHeadersWithPrefix("key")); EXPECT_TRUE(header.HasHeadersWithPrefix("key1")); EXPECT_FALSE(header.HasHeadersWithPrefix("key2")); } TEST(BalsaHeaders, GetHeaderWorksAsExpectedWithHeadersErased) { BalsaHeaders header; header.AppendHeader("key1", "value_1"); header.AppendHeader("key1", "value_2"); header.AppendHeader("key2", "value_2"); header.AppendHeader("key3", "value_3"); header.AppendHeader("a", "value_a"); header.AppendHeader("b", "value_b"); header.erase(header.GetHeaderPosition("key2")); absl::string_view header_key_b_value = header.GetHeader("b"); absl::string_view header_key_1_value = header.GetHeader("key1"); absl::string_view header_key_3_value = header.GetHeader("key3"); absl::string_view header_key_2_value = header.GetHeader("key2"); absl::string_view header_key_a_value = header.GetHeader("a"); ASSERT_FALSE(header_key_1_value.empty()); ASSERT_TRUE(header_key_2_value.empty()); ASSERT_FALSE(header_key_3_value.empty()); ASSERT_FALSE(header_key_a_value.empty()); ASSERT_FALSE(header_key_b_value.empty()); EXPECT_EQ(std::string("value_1"), header_key_1_value); EXPECT_EQ(std::string("value_3"), header_key_3_value); EXPECT_EQ(std::string("value_a"), header_key_a_value); EXPECT_EQ(std::string("value_b"), header_key_b_value); header.erase(header.GetHeaderPosition("key1")); header_key_1_value = header.GetHeader("key1"); ASSERT_FALSE(header_key_1_value.empty()); EXPECT_EQ(std::string("value_2"), header_key_1_value); header.erase(header.GetHeaderPosition("key1")); ASSERT_TRUE(header.GetHeader("key1").empty()); } TEST(BalsaHeaders, HasHeaderWorksAsExpectedWithHeadersErased) { BalsaHeaders header; header.AppendHeader("key1", "value_1"); header.AppendHeader("key2", "value_2a"); header.AppendHeader("key2", "value_2b"); ASSERT_TRUE(header.HasHeader("key1")); ASSERT_TRUE(header.HasHeadersWithPrefix("key1")); ASSERT_TRUE(header.HasHeadersWithPrefix("key2")); ASSERT_TRUE(header.HasHeadersWithPrefix("kEY")); header.erase(header.GetHeaderPosition("key1")); EXPECT_FALSE(header.HasHeader("key1")); EXPECT_FALSE(header.HasHeadersWithPrefix("key1")); EXPECT_TRUE(header.HasHeadersWithPrefix("key2")); EXPECT_TRUE(header.HasHeadersWithPrefix("kEY")); ASSERT_TRUE(header.HasHeader("key2")); header.erase(header.GetHeaderPosition("key2")); ASSERT_TRUE(header.HasHeader("key2")); EXPECT_FALSE(header.HasHeadersWithPrefix("key1")); EXPECT_TRUE(header.HasHeadersWithPrefix("key2")); EXPECT_TRUE(header.HasHeadersWithPrefix("kEY")); header.erase(header.GetHeaderPosition("key2")); EXPECT_FALSE(header.HasHeader("key2")); EXPECT_FALSE(header.HasHeadersWithPrefix("key1")); EXPECT_FALSE(header.HasHeadersWithPrefix("key2")); EXPECT_FALSE(header.HasHeadersWithPrefix("kEY")); } TEST(BalsaHeaders, HasNonEmptyHeaderWorksAsExpectedWithNoHeaderLines) { BalsaHeaders header; EXPECT_FALSE(header.HasNonEmptyHeader("foo")); EXPECT_FALSE(header.HasNonEmptyHeader("")); } TEST(BalsaHeaders, HasNonEmptyHeaderWorksAsExpectedWithAppendHeader) { BalsaHeaders header; EXPECT_FALSE(header.HasNonEmptyHeader("key1")); header.AppendHeader("key1", ""); EXPECT_FALSE(header.HasNonEmptyHeader("key1")); header.AppendHeader("key1", "value_2"); EXPECT_TRUE(header.HasNonEmptyHeader("key1")); EXPECT_FALSE(header.HasNonEmptyHeader("key2")); } TEST(BalsaHeaders, HasNonEmptyHeaderWorksAsExpectedWithHeadersErased) { BalsaHeaders header; header.AppendHeader("key1", "value_1"); header.AppendHeader("key2", "value_2a"); header.AppendHeader("key2", ""); EXPECT_TRUE(header.HasNonEmptyHeader("key1")); header.erase(header.GetHeaderPosition("key1")); EXPECT_FALSE(header.HasNonEmptyHeader("key1")); EXPECT_TRUE(header.HasNonEmptyHeader("key2")); header.erase(header.GetHeaderPosition("key2")); EXPECT_FALSE(header.HasNonEmptyHeader("key2")); header.erase(header.GetHeaderPosition("key2")); EXPECT_FALSE(header.HasNonEmptyHeader("key2")); } TEST(BalsaHeaders, HasNonEmptyHeaderWorksAsExpectedWithBalsaFrameProcessInput) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "key1: value_1\r\n" "key2:\r\n" "key3:\r\n" "key3: value_3\r\n" "key4:\r\n" "key4:\r\n" "key5: value_5\r\n" "key5:\r\n" "\r\n"); EXPECT_FALSE(headers.HasNonEmptyHeader("foo")); EXPECT_TRUE(headers.HasNonEmptyHeader("key1")); EXPECT_FALSE(headers.HasNonEmptyHeader("key2")); EXPECT_TRUE(headers.HasNonEmptyHeader("key3")); EXPECT_FALSE(headers.HasNonEmptyHeader("key4")); EXPECT_TRUE(headers.HasNonEmptyHeader("key5")); headers.erase(headers.GetHeaderPosition("key5")); EXPECT_FALSE(headers.HasNonEmptyHeader("key5")); } TEST(BalsaHeaders, GetAllOfHeader) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("Key", "value_2,value_3"); header.AppendHeader("key", ""); header.AppendHeader("KEY", "value_4"); std::vector<absl::string_view> result; header.GetAllOfHeader("key", &result); ASSERT_EQ(4u, result.size()); EXPECT_EQ("value_1", result[0]); EXPECT_EQ("value_2,value_3", result[1]); EXPECT_EQ("", result[2]); EXPECT_EQ("value_4", result[3]); EXPECT_EQ(header.GetAllOfHeader("key"), result); } TEST(BalsaHeaders, GetAllOfHeaderDoesWhatItSays) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); header.AppendHeader("key", ""); header.AppendHeader("key", "value_1"); ASSERT_NE(header.lines().begin(), header.lines().end()); std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); ASSERT_EQ(4u, out.size()); EXPECT_EQ("value_1", out[0]); EXPECT_EQ("value_2", out[1]); EXPECT_EQ("", out[2]); EXPECT_EQ("value_1", out[3]); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderWithPrefix) { BalsaHeaders header; header.AppendHeader("foo-Foo", "value_1"); header.AppendHeader("Foo-bar", "value_2,value_3"); header.AppendHeader("foo-Foo", ""); header.AppendHeader("bar", "value_not"); header.AppendHeader("fOO-fOO", "value_4"); std::vector<std::pair<absl::string_view, absl::string_view>> result; header.GetAllOfHeaderWithPrefix("abc", &result); ASSERT_EQ(0u, result.size()); header.GetAllOfHeaderWithPrefix("foo", &result); ASSERT_EQ(4u, result.size()); EXPECT_EQ("foo-Foo", result[0].first); EXPECT_EQ("value_1", result[0].second); EXPECT_EQ("Foo-bar", result[1].first); EXPECT_EQ("value_2,value_3", result[1].second); EXPECT_EQ("", result[2].second); EXPECT_EQ("value_4", result[3].second); std::vector<std::pair<absl::string_view, absl::string_view>> result2; header.GetAllOfHeaderWithPrefix("FoO", &result2); ASSERT_EQ(4u, result2.size()); } TEST(BalsaHeaders, GetAllHeadersWithLimit) { BalsaHeaders header; header.AppendHeader("foo-Foo", "value_1"); header.AppendHeader("Foo-bar", "value_2,value_3"); header.AppendHeader("foo-Foo", ""); header.AppendHeader("bar", "value_4"); header.AppendHeader("fOO-fOO", "value_5"); std::vector<std::pair<absl::string_view, absl::string_view>> result; header.GetAllHeadersWithLimit(&result, 4); ASSERT_EQ(4u, result.size()); EXPECT_EQ("foo-Foo", result[0].first); EXPECT_EQ("value_1", result[0].second); EXPECT_EQ("Foo-bar", result[1].first); EXPECT_EQ("value_2,value_3", result[1].second); EXPECT_EQ("", result[2].second); EXPECT_EQ("value_4", result[3].second); std::vector<std::pair<absl::string_view, absl::string_view>> result2; header.GetAllHeadersWithLimit(&result2, -1); ASSERT_EQ(5u, result2.size()); } TEST(BalsaHeaders, RangeFor) { BalsaHeaders header; header.AppendHeader("key1", "value_1a"); header.AppendHeader("key1", "value_1b"); header.AppendHeader("key2", ""); header.AppendHeader("key3", "value_3"); std::vector<std::pair<absl::string_view, absl::string_view>> out; for (const auto& line : header.lines()) { out.push_back(line); } const std::vector<std::pair<absl::string_view, absl::string_view>> expected = {{"key1", "value_1a"}, {"key1", "value_1b"}, {"key2", ""}, {"key3", "value_3"}}; EXPECT_EQ(expected, out); } TEST(BalsaHeaders, GetAllOfHeaderWithNonExistentKey) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); std::vector<absl::string_view> out; header.GetAllOfHeader("key_non_existent", &out); ASSERT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("key_non_existent"), out); } TEST(BalsaHeaders, GetAllOfHeaderEmptyValVariation1) { BalsaHeaders header; header.AppendHeader("key", ""); header.AppendHeader("key", ""); header.AppendHeader("key", "v1"); std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); ASSERT_EQ(3u, out.size()); EXPECT_EQ("", out[0]); EXPECT_EQ("", out[1]); EXPECT_EQ("v1", out[2]); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderEmptyValVariation2) { BalsaHeaders header; header.AppendHeader("key", ""); header.AppendHeader("key", "v1"); header.AppendHeader("key", ""); std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); ASSERT_EQ(3u, out.size()); EXPECT_EQ("", out[0]); EXPECT_EQ("v1", out[1]); EXPECT_EQ("", out[2]); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderEmptyValVariation3) { BalsaHeaders header; header.AppendHeader("key", ""); header.AppendHeader("key", "v1"); std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); ASSERT_EQ(2u, out.size()); EXPECT_EQ("", out[0]); EXPECT_EQ("v1", out[1]); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderEmptyValVariation4) { BalsaHeaders header; header.AppendHeader("key", "v1"); header.AppendHeader("key", ""); std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); ASSERT_EQ(2u, out.size()); EXPECT_EQ("v1", out[0]); EXPECT_EQ("", out[1]); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderWithAppendHeaders) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); std::vector<absl::string_view> out; header.GetAllOfHeader("key_new", &out); ASSERT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("key_new"), out); header.AppendHeader("key_new", "value_3"); header.GetAllOfHeader("key_new", &out); ASSERT_EQ(1u, out.size()); EXPECT_EQ("value_3", out[0]); EXPECT_EQ(header.GetAllOfHeader("key_new"), out); header.GetAllOfHeader("key", &out); ASSERT_EQ(3u, out.size()); EXPECT_EQ("value_1", out[1]); EXPECT_EQ("value_2", out[2]); EXPECT_THAT(header.GetAllOfHeader("key"), ElementsAre("value_1", "value_2")); } TEST(BalsaHeaders, GetAllOfHeaderWithRemoveHeaders) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); header.AppendHeader("a", "va"); header.RemoveAllOfHeader("key"); std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); ASSERT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("key"), out); header.GetAllOfHeader("a", &out); ASSERT_EQ(1u, out.size()); EXPECT_EQ(header.GetAllOfHeader("a"), out); out.clear(); header.RemoveAllOfHeader("a"); header.GetAllOfHeader("a", &out); ASSERT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("a"), out); } TEST(BalsaHeaders, GetAllOfHeaderWithRemoveNonExistentHeaders) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("Accept-Encoding", "deflate,compress"); EXPECT_EQ(0u, headers.RemoveValue("Accept-Encoding", "gzip(gfe)")); std::string accept_encoding_vals = headers.GetAllOfHeaderAsString("Accept-Encoding"); EXPECT_EQ("deflate,compress", accept_encoding_vals); } TEST(BalsaHeaders, GetAllOfHeaderWithEraseHeaders) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); header.AppendHeader("a", "va"); std::vector<absl::string_view> out; header.erase(header.GetHeaderPosition("key")); header.GetAllOfHeader("key", &out); ASSERT_EQ(1u, out.size()); EXPECT_EQ("value_2", out[0]); EXPECT_EQ(header.GetAllOfHeader("key"), out); out.clear(); header.erase(header.GetHeaderPosition("key")); header.GetAllOfHeader("key", &out); ASSERT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("key"), out); out.clear(); header.GetAllOfHeader("a", &out); ASSERT_EQ(1u, out.size()); EXPECT_EQ(header.GetAllOfHeader("a"), out); out.clear(); header.erase(header.GetHeaderPosition("a")); header.GetAllOfHeader("a", &out); ASSERT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderWithNoHeaderLines) { BalsaHeaders header; std::vector<absl::string_view> out; header.GetAllOfHeader("key", &out); EXPECT_EQ(0u, out.size()); EXPECT_EQ(header.GetAllOfHeader("key"), out); } TEST(BalsaHeaders, GetAllOfHeaderDoesWhatItSaysForVariousKeys) { BalsaHeaders header; header.AppendHeader("key1", "value_11"); header.AppendHeader("key2", "value_21"); header.AppendHeader("key1", "value_12"); header.AppendHeader("key2", "value_22"); std::vector<absl::string_view> out; header.GetAllOfHeader("key1", &out); EXPECT_EQ("value_11", out[0]); EXPECT_EQ("value_12", out[1]); EXPECT_EQ(header.GetAllOfHeader("key1"), out); header.GetAllOfHeader("key2", &out); EXPECT_EQ("value_21", out[2]); EXPECT_EQ("value_22", out[3]); EXPECT_THAT(header.GetAllOfHeader("key2"), ElementsAre("value_21", "value_22")); } TEST(BalsaHeaders, GetAllOfHeaderWithBalsaFrameProcessInput) { BalsaHeaders header = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "key1: value_1\r\n" "key1: value_foo\r\n" "key2: value_2\r\n" "a: value_a\r\n" "key2: \r\n" "b: value_b\r\n" "\r\n"); std::vector<absl::string_view> out; int index = 0; header.GetAllOfHeader("key1", &out); EXPECT_EQ("value_1", out[index++]); EXPECT_EQ("value_foo", out[index++]); EXPECT_EQ(header.GetAllOfHeader("key1"), out); header.GetAllOfHeader("key2", &out); EXPECT_EQ("value_2", out[index++]); EXPECT_EQ("", out[index++]); EXPECT_THAT(header.GetAllOfHeader("key2"), ElementsAre("value_2", "")); header.GetAllOfHeader("a", &out); EXPECT_EQ("value_a", out[index++]); EXPECT_THAT(header.GetAllOfHeader("a"), ElementsAre("value_a")); header.GetAllOfHeader("b", &out); EXPECT_EQ("value_b", out[index++]); EXPECT_THAT(header.GetAllOfHeader("b"), ElementsAre("value_b")); } TEST(BalsaHeaders, GetAllOfHeaderIncludeRemovedDoesWhatItSays) { BalsaHeaders header; header.AppendHeader("key1", "value_11"); header.AppendHeader("key2", "value_21"); header.AppendHeader("key1", "value_12"); header.AppendHeader("key2", "value_22"); header.AppendHeader("key1", ""); std::vector<absl::string_view> out; header.GetAllOfHeaderIncludeRemoved("key1", &out); ASSERT_EQ(3u, out.size()); EXPECT_EQ("value_11", out[0]); EXPECT_EQ("value_12", out[1]); EXPECT_EQ("", out[2]); header.GetAllOfHeaderIncludeRemoved("key2", &out); ASSERT_EQ(5u, out.size()); EXPECT_EQ("value_21", out[3]); EXPECT_EQ("value_22", out[4]); header.erase(header.GetHeaderPosition("key1")); out.clear(); header.GetAllOfHeaderIncludeRemoved("key1", &out); ASSERT_EQ(3u, out.size()); EXPECT_EQ("value_12", out[0]); EXPECT_EQ("", out[1]); EXPECT_EQ("value_11", out[2]); header.GetAllOfHeaderIncludeRemoved("key2", &out); ASSERT_EQ(5u, out.size()); EXPECT_EQ("value_21", out[3]); EXPECT_EQ("value_22", out[4]); header.RemoveAllOfHeader("key1"); out.clear(); header.GetAllOfHeaderIncludeRemoved("key1", &out); ASSERT_EQ(3u, out.size()); EXPECT_EQ("value_11", out[0]); EXPECT_EQ("value_12", out[1]); EXPECT_EQ("", out[2]); header.GetAllOfHeaderIncludeRemoved("key2", &out); ASSERT_EQ(5u, out.size()); EXPECT_EQ("value_21", out[3]); EXPECT_EQ("value_22", out[4]); header.Clear(); out.clear(); header.GetAllOfHeaderIncludeRemoved("key1", &out); ASSERT_EQ(0u, out.size()); header.GetAllOfHeaderIncludeRemoved("key2", &out); ASSERT_EQ(0u, out.size()); } TEST(BalsaHeaders, GetAllOfHeaderIncludeRemovedWithNonExistentKey) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); std::vector<absl::string_view> out; header.GetAllOfHeaderIncludeRemoved("key_non_existent", &out); ASSERT_EQ(0u, out.size()); } TEST(BalsaHeaders, GetIteratorForKeyDoesWhatItSays) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("Key", "value_2"); header.AppendHeader("key", ""); header.AppendHeader("KEY", "value_1"); BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("key"); EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key", key_it->first); EXPECT_EQ("value_1", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("Key", key_it->first); EXPECT_EQ("value_2", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key", key_it->first); EXPECT_EQ("", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("KEY", key_it->first); EXPECT_EQ("value_1", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); } TEST(BalsaHeaders, GetIteratorForKeyWithNonExistentKey) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("key_non_existent"); EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); const auto lines = header.lines("key_non_existent"); EXPECT_EQ(lines.begin(), header.lines().end()); EXPECT_EQ(lines.end(), header.header_lines_key_end()); } TEST(BalsaHeaders, GetIteratorForKeyWithAppendHeaders) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("key_new"); EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); header.AppendHeader("key_new", "value_3"); key_it = header.GetIteratorForKey("key_new"); const auto lines1 = header.lines("key_new"); EXPECT_EQ(lines1.begin(), key_it); EXPECT_EQ(lines1.end(), header.header_lines_key_end()); EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key_new", key_it->first); EXPECT_EQ("value_3", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); key_it = header.GetIteratorForKey("key"); const auto lines2 = header.lines("key"); EXPECT_EQ(lines2.begin(), key_it); EXPECT_EQ(lines2.end(), header.header_lines_key_end()); EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key", key_it->first); EXPECT_EQ("value_1", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key", key_it->first); EXPECT_EQ("value_2", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); } TEST(BalsaHeaders, GetIteratorForKeyWithRemoveHeaders) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); header.AppendHeader("a", "va"); header.RemoveAllOfHeader("a"); BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("key"); EXPECT_NE(header.lines().end(), key_it); const auto lines1 = header.lines("key"); EXPECT_EQ(lines1.begin(), key_it); EXPECT_EQ(lines1.end(), header.header_lines_key_end()); EXPECT_EQ("value_1", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key", key_it->first); EXPECT_EQ("value_2", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); for (BalsaHeaders::const_header_lines_key_iterator it = header.GetIteratorForKey("key"); it != header.lines().end(); ++it) { EXPECT_EQ("key", it->first); } } TEST(BalsaHeaders, GetIteratorForKeyWithEraseHeaders) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); header.AppendHeader("a", "va"); header.erase(header.GetHeaderPosition("key")); BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("key"); EXPECT_NE(header.lines().end(), key_it); const auto lines1 = header.lines("key"); EXPECT_EQ(lines1.begin(), key_it); EXPECT_EQ(lines1.end(), header.header_lines_key_end()); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key", key_it->first); EXPECT_EQ("value_2", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); header.erase(header.GetHeaderPosition("key")); key_it = header.GetIteratorForKey("key"); const auto lines2 = header.lines("key"); EXPECT_EQ(lines2.begin(), key_it); EXPECT_EQ(lines2.end(), header.header_lines_key_end()); EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); key_it = header.GetIteratorForKey("a"); const auto lines3 = header.lines("a"); EXPECT_EQ(lines3.begin(), key_it); EXPECT_EQ(lines3.end(), header.header_lines_key_end()); EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("a", key_it->first); EXPECT_EQ("va", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); header.erase(header.GetHeaderPosition("a")); key_it = header.GetIteratorForKey("a"); const auto lines4 = header.lines("a"); EXPECT_EQ(lines4.begin(), key_it); EXPECT_EQ(lines4.end(), header.header_lines_key_end()); EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); } TEST(BalsaHeaders, GetIteratorForKeyWithNoHeaderLines) { BalsaHeaders header; BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("key"); const auto lines = header.lines("key"); EXPECT_EQ(lines.begin(), key_it); EXPECT_EQ(lines.end(), header.header_lines_key_end()); EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); } TEST(BalsaHeaders, GetIteratorForKeyWithBalsaFrameProcessInput) { BalsaHeaders header = CreateHTTPHeaders(true, "GET / HTTP/1.0\r\n" "key1: value_1\r\n" "Key1: value_foo\r\n" "key2: value_2\r\n" "a: value_a\r\n" "key2: \r\n" "b: value_b\r\n" "\r\n"); BalsaHeaders::const_header_lines_key_iterator key_it = header.GetIteratorForKey("Key1"); const auto lines1 = header.lines("Key1"); EXPECT_EQ(lines1.begin(), key_it); EXPECT_EQ(lines1.end(), header.header_lines_key_end()); EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key1", key_it->first); EXPECT_EQ("value_1", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("Key1", key_it->first); EXPECT_EQ("value_foo", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); key_it = header.GetIteratorForKey("key2"); EXPECT_NE(header.lines().end(), key_it); const auto lines2 = header.lines("key2"); EXPECT_EQ(lines2.begin(), key_it); EXPECT_EQ(lines2.end(), header.header_lines_key_end()); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key2", key_it->first); EXPECT_EQ("value_2", key_it->second); ++key_it; EXPECT_NE(header.lines().end(), key_it); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("key2", key_it->first); EXPECT_EQ("", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); key_it = header.GetIteratorForKey("a"); EXPECT_NE(header.lines().end(), key_it); const auto lines3 = header.lines("a"); EXPECT_EQ(lines3.begin(), key_it); EXPECT_EQ(lines3.end(), header.header_lines_key_end()); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("a", key_it->first); EXPECT_EQ("value_a", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); key_it = header.GetIteratorForKey("b"); EXPECT_NE(header.lines().end(), key_it); const auto lines4 = header.lines("b"); EXPECT_EQ(lines4.begin(), key_it); EXPECT_EQ(lines4.end(), header.header_lines_key_end()); EXPECT_NE(header.header_lines_key_end(), key_it); EXPECT_EQ("b", key_it->first); EXPECT_EQ("value_b", key_it->second); ++key_it; EXPECT_EQ(header.lines().end(), key_it); EXPECT_EQ(header.header_lines_key_end(), key_it); } TEST(BalsaHeaders, GetAllOfHeaderAsStringDoesWhatItSays) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("Key", "value_2"); header.AppendHeader("key", ""); header.AppendHeader("KEY", "value_1"); std::string result = header.GetAllOfHeaderAsString("key"); EXPECT_EQ("value_1,value_2,,value_1", result); } TEST(BalsaHeaders, RemoveAllOfHeaderDoesWhatItSays) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); ASSERT_NE(header.lines().begin(), header.lines().end()); header.RemoveAllOfHeader("key"); ASSERT_EQ(header.lines().begin(), header.lines().end()); } TEST(BalsaHeaders, RemoveAllOfHeaderDoesWhatItSaysEvenWhenThingsHaveBeenErased) { BalsaHeaders header; header.AppendHeader("key1", "value_1"); header.AppendHeader("key1", "value_2"); header.AppendHeader("key2", "value_3"); header.AppendHeader("key1", "value_4"); header.AppendHeader("key2", "value_5"); header.AppendHeader("key1", "value_6"); ASSERT_NE(header.lines().begin(), header.lines().end()); BalsaHeaders::const_header_lines_iterator chli = header.lines().begin(); ++chli; ++chli; ++chli; header.erase(chli); chli = header.lines().begin(); ++chli; header.erase(chli); header.RemoveAllOfHeader("key1"); for (const auto& line : header.lines()) { EXPECT_NE(std::string("key1"), line.first); } } TEST(BalsaHeaders, RemoveAllOfHeaderDoesNothingWhenNoKeyOfThatNameExists) { BalsaHeaders header; header.AppendHeader("key", "value_1"); header.AppendHeader("key", "value_2"); ASSERT_NE(header.lines().begin(), header.lines().end()); header.RemoveAllOfHeader("foo"); int num_found = 0; for (const auto& line : header.lines()) { ++num_found; EXPECT_EQ(absl::string_view("key"), line.first); } EXPECT_EQ(2, num_found); EXPECT_NE(header.lines().begin(), header.lines().end()); } TEST(BalsaHeaders, WriteHeaderEndingToBuffer) { BalsaHeaders header; SimpleBuffer simple_buffer; header.WriteHeaderEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq("\r\n")); } TEST(BalsaHeaders, WriteToBufferDoesntCrashWithUninitializedHeader) { BalsaHeaders header; SimpleBuffer simple_buffer; header.WriteHeaderAndEndingToBuffer(&simple_buffer); } TEST(BalsaHeaders, WriteToBufferWorksWithBalsaHeadersParsedByFramer) { std::string input = "GET / HTTP/1.0\r\n" "key_with_value: value\r\n" "key_with_continuation_value: \r\n" " with continuation\r\n" "key_with_two_continuation_value: \r\n" " continuation 1\r\n" " continuation 2\r\n" "a: foo \r\n" "b-s:\n" " bar\t\n" "foo: \r\n" "bazzzzzzzleriffic!: snaps\n" "\n"; std::string expected = "GET / HTTP/1.0\r\n" "key_with_value: value\r\n" "key_with_continuation_value: with continuation\r\n" "key_with_two_continuation_value: continuation 1\r\n" " continuation 2\r\n" "a: foo\r\n" "b-s: bar\r\n" "foo: \r\n" "bazzzzzzzleriffic!: snaps\r\n" "\r\n"; BalsaHeaders headers = CreateHTTPHeaders(true, input); SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, WriteToBufferWorksWithBalsaHeadersParsedByFramerTabContinuations) { std::string input = "GET / HTTP/1.0\r\n" "key_with_value: value\r\n" "key_with_continuation_value: \r\n" "\twith continuation\r\n" "key_with_two_continuation_value: \r\n" "\tcontinuation 1\r\n" "\tcontinuation 2\r\n" "a: foo \r\n" "b-s:\n" "\tbar\t\n" "foo: \r\n" "bazzzzzzzleriffic!: snaps\n" "\n"; std::string expected = "GET / HTTP/1.0\r\n" "key_with_value: value\r\n" "key_with_continuation_value: with continuation\r\n" "key_with_two_continuation_value: continuation 1\r\n" "\tcontinuation 2\r\n" "a: foo\r\n" "b-s: bar\r\n" "foo: \r\n" "bazzzzzzzleriffic!: snaps\r\n" "\r\n"; BalsaHeaders headers = CreateHTTPHeaders(true, input); SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, WriteToBufferWorksWhenFirstlineSetThroughHeaders) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); std::string expected = "GET / HTTP/1.0\r\n" "\r\n"; SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, WriteToBufferWorksWhenSetThroughHeaders) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key 2", "value\n 2"); headers.AppendHeader("key\n 3", "value3"); std::string expected = "GET / HTTP/1.0\r\n" "key1: value1\r\n" "key 2: value\n" " 2\r\n" "key\n" " 3: value3\r\n" "\r\n"; SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, WriteToBufferWorkWhensOnlyLinesSetThroughHeaders) { BalsaHeaders headers; headers.AppendHeader("key1", "value1"); headers.AppendHeader("key 2", "value\n 2"); headers.AppendHeader("key\n 3", "value3"); std::string expected = "\r\n" "key1: value1\r\n" "key 2: value\n" " 2\r\n" "key\n" " 3: value3\r\n" "\r\n"; SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, WriteToBufferWorksWhenSetThroughHeadersWithElementsErased) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key 2", "value\n 2"); headers.AppendHeader("key\n 3", "value3"); headers.RemoveAllOfHeader("key1"); headers.RemoveAllOfHeader("key\n 3"); std::string expected = "GET / HTTP/1.0\r\n" "key 2: value\n" " 2\r\n" "\r\n"; SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, WriteToBufferWithManuallyAppendedHeaderLine) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key 2", "value\n 2"); std::string expected = "GET / HTTP/1.0\r\n" "key1: value1\r\n" "key 2: value\n" " 2\r\n" "key 3: value 3\r\n" "\r\n"; SimpleBuffer simple_buffer; size_t expected_write_buffer_size = headers.GetSizeForWriteBuffer(); headers.WriteToBuffer(&simple_buffer); headers.WriteHeaderLineToBuffer(&simple_buffer, "key 3", "value 3", BalsaHeaders::CaseOption::kNoModification); headers.WriteHeaderEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected)); EXPECT_EQ(expected_write_buffer_size + 16, static_cast<size_t>(simple_buffer.ReadableBytes())); } TEST(BalsaHeaders, DumpToStringEmptyHeaders) { BalsaHeaders headers; std::string headers_str; headers.DumpToString(&headers_str); EXPECT_EQ("\n <empty header>\n", headers_str); } TEST(BalsaHeaders, DumpToStringParsedHeaders) { std::string input = "GET / HTTP/1.0\r\n" "Header1: value\r\n" "Header2: value\r\n" "\r\n"; std::string output = "\n" " GET / HTTP/1.0\n" " Header1: value\n" " Header2: value\n"; BalsaHeaders headers = CreateHTTPHeaders(true, input); std::string headers_str; headers.DumpToString(&headers_str); EXPECT_EQ(output, headers_str); EXPECT_TRUE(headers.FramerIsDoneWriting()); } TEST(BalsaHeaders, DumpToStringPartialHeaders) { BalsaHeaders headers; BalsaFrame balsa_frame; balsa_frame.set_is_request(true); balsa_frame.set_balsa_headers(&headers); std::string input = "GET / HTTP/1.0\r\n" "Header1: value\r\n" "Header2: value\r\n"; std::string output = absl::StrFormat("\n <incomplete header len: %d>\n ", static_cast<int>(input.size())); output += input; output += '\n'; ASSERT_EQ(input.size(), balsa_frame.ProcessInput(input.data(), input.size())); ASSERT_FALSE(balsa_frame.MessageFullyRead()); std::string headers_str; headers.DumpToString(&headers_str); EXPECT_EQ(output, headers_str); EXPECT_FALSE(headers.FramerIsDoneWriting()); } TEST(BalsaHeaders, DumpToStringParsingNonHeadersData) { BalsaHeaders headers; BalsaFrame balsa_frame; balsa_frame.set_is_request(true); balsa_frame.set_balsa_headers(&headers); std::string input = "This is not a header. " "Just some random data to simulate mismatch."; std::string output = absl::StrFormat("\n <incomplete header len: %d>\n ", static_cast<int>(input.size())); output += input; output += '\n'; ASSERT_EQ(input.size(), balsa_frame.ProcessInput(input.data(), input.size())); ASSERT_FALSE(balsa_frame.MessageFullyRead()); std::string headers_str; headers.DumpToString(&headers_str); EXPECT_EQ(output, headers_str); } TEST(BalsaHeaders, Clear) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("key1", "value1"); headers.AppendHeader("key 2", "value\n 2"); headers.AppendHeader("key\n 3", "value3"); headers.RemoveAllOfHeader("key1"); headers.RemoveAllOfHeader("key\n 3"); headers.Clear(); EXPECT_TRUE(headers.first_line().empty()); EXPECT_EQ(headers.lines().begin(), headers.lines().end()); EXPECT_TRUE(headers.IsEmpty()); } TEST(BalsaHeaders, TestSetFromStringPiecesWithInitialFirstlineInHeaderStreamAndNewToo) { BalsaHeaders headers = CreateHTTPHeaders(false, "HTTP/1.1 200 reason phrase\r\n" "content-length: 0\r\n" "\r\n"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.1")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); headers.SetResponseFirstline("HTTP/1.0", 404, "a reason"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.0")); EXPECT_THAT(headers.response_code(), StrEq("404")); EXPECT_THAT(headers.parsed_response_code(), Eq(404)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("a reason")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.0 404 a reason")); } TEST(BalsaHeaders, TestSetFromStringPiecesWithInitialFirstlineInHeaderStreamButNotNew) { BalsaHeaders headers = CreateHTTPHeaders(false, "HTTP/1.1 200 reason phrase\r\n" "content-length: 0\r\n" "\r\n"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.1")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); headers.SetResponseFirstline("HTTP/1.000", 404000, "supercalifragilisticexpealidocious"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.000")); EXPECT_THAT(headers.response_code(), StrEq("404000")); EXPECT_THAT(headers.parsed_response_code(), Eq(404000)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("supercalifragilisticexpealidocious")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.000 404000 supercalifragilisticexpealidocious")); } TEST(BalsaHeaders, TestSetFromStringPiecesWithFirstFirstlineInHeaderStreamButNotNew2) { SCOPED_TRACE( "This test tests the codepath where the new firstline is" " too large to fit within the space used by the original" " firstline, but large enuogh to space in the free space" " available in both firstline plus the space made available" " with deleted header lines (specifically, the first one"); BalsaHeaders headers = CreateHTTPHeaders( false, "HTTP/1.1 200 reason phrase\r\n" "a: 0987123409871234078130948710938471093827401983740198327401982374\r\n" "content-length: 0\r\n" "\r\n"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.1")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); headers.erase(headers.lines().begin()); headers.SetResponseFirstline("HTTP/1.000", 404000, "supercalifragilisticexpealidocious"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.000")); EXPECT_THAT(headers.response_code(), StrEq("404000")); EXPECT_THAT(headers.parsed_response_code(), Eq(404000)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("supercalifragilisticexpealidocious")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.000 404000 supercalifragilisticexpealidocious")); } TEST(BalsaHeaders, TestSetFirstlineFromStringPiecesWithNoInitialFirstline) { BalsaHeaders headers; headers.SetResponseFirstline("HTTP/1.1", 200, "don't need a reason"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.1")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.parsed_response_code(), Eq(200)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("don't need a reason")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.1 200 don't need a reason")); } TEST(BalsaHeaders, TestSettingFirstlineElementsWithOtherElementsMissing) { { BalsaHeaders headers; headers.SetRequestMethod("GET"); headers.SetRequestUri("/"); EXPECT_THAT(headers.first_line(), StrEq("GET / ")); } { BalsaHeaders headers; headers.SetRequestMethod("GET"); headers.SetRequestVersion("HTTP/1.1"); EXPECT_THAT(headers.first_line(), StrEq("GET HTTP/1.1")); } { BalsaHeaders headers; headers.SetRequestUri("/"); headers.SetRequestVersion("HTTP/1.1"); EXPECT_THAT(headers.first_line(), StrEq(" / HTTP/1.1")); } } TEST(BalsaHeaders, TestSettingMissingFirstlineElementsAfterBalsaHeadersParsed) { { BalsaHeaders headers = CreateHTTPHeaders(true, "GET /foo\r\n"); ASSERT_THAT(headers.first_line(), StrEq("GET /foo")); headers.SetRequestVersion("HTTP/1.1"); EXPECT_THAT(headers.first_line(), StrEq("GET /foo HTTP/1.1")); } { BalsaHeaders headers = CreateHTTPHeaders(true, "GET\r\n"); ASSERT_THAT(headers.first_line(), StrEq("GET")); headers.SetRequestUri("/foo"); EXPECT_THAT(headers.first_line(), StrEq("GET /foo ")); } } TEST(BalsaHeaders, SetFirstlineFromStringPiecesFirstInAdditionalDataAndNewLarger) { BalsaHeaders headers; headers.SetResponseFirstline("HTTP/1.1", 200, "don't need a reason"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.1")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.parsed_response_code(), Eq(200)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("don't need a reason")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.1 200 don't need a reason")); headers.SetResponseFirstline("HTTP/1.10", 2000, "REALLY don't need a reason"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.10")); EXPECT_THAT(headers.response_code(), StrEq("2000")); EXPECT_THAT(headers.parsed_response_code(), Eq(2000)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("REALLY don't need a reason")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.10 2000 REALLY don't need a reason")); } TEST(BalsaHeaders, TestSetFirstlineFromStringPiecesWithPreviousInAdditionalDataNewSmaller) { BalsaHeaders headers; headers.SetResponseFirstline("HTTP/1.10", 2000, "REALLY don't need a reason"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.10")); EXPECT_THAT(headers.response_code(), StrEq("2000")); EXPECT_THAT(headers.parsed_response_code(), Eq(2000)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("REALLY don't need a reason")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.10 2000 REALLY don't need a reason")); headers.SetResponseFirstline("HTTP/1.0", 200, "a reason"); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.0")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.parsed_response_code(), Eq(200)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("a reason")); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.0 200 a reason")); } TEST(BalsaHeaders, CopyFrom) { BalsaHeaders headers1, headers2; absl::string_view method("GET"); absl::string_view uri("/foo"); absl::string_view version("HTTP/1.0"); headers1.SetRequestFirstlineFromStringPieces(method, uri, version); headers1.AppendHeader("key1", "value1"); headers1.AppendHeader("key 2", "value\n 2"); headers1.AppendHeader("key\n 3", "value3"); headers2.CopyFrom(headers1); EXPECT_THAT(headers1.first_line(), StrEq("GET /foo HTTP/1.0")); BalsaHeaders::const_header_lines_iterator chli = headers1.lines().begin(); EXPECT_THAT(chli->first, StrEq("key1")); EXPECT_THAT(chli->second, StrEq("value1")); ++chli; EXPECT_THAT(chli->first, StrEq("key 2")); EXPECT_THAT(chli->second, StrEq("value\n 2")); ++chli; EXPECT_THAT(chli->first, StrEq("key\n 3")); EXPECT_THAT(chli->second, StrEq("value3")); ++chli; EXPECT_EQ(headers1.lines().end(), chli); EXPECT_THAT(headers1.request_method(), StrEq((std::string(headers2.request_method())))); EXPECT_THAT(headers1.request_uri(), StrEq((std::string(headers2.request_uri())))); EXPECT_THAT(headers1.request_version(), StrEq((std::string(headers2.request_version())))); EXPECT_THAT(headers2.first_line(), StrEq("GET /foo HTTP/1.0")); chli = headers2.lines().begin(); EXPECT_THAT(chli->first, StrEq("key1")); EXPECT_THAT(chli->second, StrEq("value1")); ++chli; EXPECT_THAT(chli->first, StrEq("key 2")); EXPECT_THAT(chli->second, StrEq("value\n 2")); ++chli; EXPECT_THAT(chli->first, StrEq("key\n 3")); EXPECT_THAT(chli->second, StrEq("value3")); ++chli; EXPECT_EQ(headers2.lines().end(), chli); version = absl::string_view("HTTP/1.1"); int code = 200; absl::string_view reason_phrase("reason phrase asdf"); headers1.RemoveAllOfHeader("key1"); headers1.AppendHeader("key4", "value4"); headers1.SetResponseFirstline(version, code, reason_phrase); headers2.CopyFrom(headers1); EXPECT_THAT(headers1.request_method(), StrEq((std::string(headers2.request_method())))); EXPECT_THAT(headers1.request_uri(), StrEq((std::string(headers2.request_uri())))); EXPECT_THAT(headers1.request_version(), StrEq((std::string(headers2.request_version())))); EXPECT_THAT(headers2.first_line(), StrEq("HTTP/1.1 200 reason phrase asdf")); chli = headers2.lines().begin(); EXPECT_THAT(chli->first, StrEq("key 2")); EXPECT_THAT(chli->second, StrEq("value\n 2")); ++chli; EXPECT_THAT(chli->first, StrEq("key\n 3")); EXPECT_THAT(chli->second, StrEq("value3")); ++chli; EXPECT_THAT(chli->first, StrEq("key4")); EXPECT_THAT(chli->second, StrEq("value4")); ++chli; EXPECT_EQ(headers2.lines().end(), chli); } TEST(BalsaHeaders, Move) { BalsaHeaders headers1, headers3; absl::string_view method("GET"); absl::string_view uri("/foo"); absl::string_view version("HTTP/1.0"); headers1.SetRequestFirstlineFromStringPieces(method, uri, version); headers1.AppendHeader("key1", "value1"); headers1.AppendHeader("key 2", "value\n 2"); headers1.AppendHeader("key\n 3", "value3"); BalsaHeaders headers2 = std::move(headers1); EXPECT_EQ("GET /foo HTTP/1.0", headers2.first_line()); BalsaHeaders::const_header_lines_iterator chli = headers2.lines().begin(); EXPECT_EQ("key1", chli->first); EXPECT_EQ("value1", chli->second); ++chli; EXPECT_EQ("key 2", chli->first); EXPECT_EQ("value\n 2", chli->second); ++chli; EXPECT_EQ("key\n 3", chli->first); EXPECT_EQ("value3", chli->second); ++chli; EXPECT_EQ(headers2.lines().end(), chli); EXPECT_EQ("GET", headers2.request_method()); EXPECT_EQ("/foo", headers2.request_uri()); EXPECT_EQ("HTTP/1.0", headers2.request_version()); headers3 = std::move(headers2); version = absl::string_view("HTTP/1.1"); int code = 200; absl::string_view reason_phrase("reason phrase asdf"); headers3.RemoveAllOfHeader("key1"); headers3.AppendHeader("key4", "value4"); headers3.SetResponseFirstline(version, code, reason_phrase); BalsaHeaders headers4 = std::move(headers3); EXPECT_EQ("200", headers4.response_code()); EXPECT_EQ("reason phrase asdf", headers4.response_reason_phrase()); EXPECT_EQ("HTTP/1.1", headers4.response_version()); EXPECT_EQ("HTTP/1.1 200 reason phrase asdf", headers4.first_line()); chli = headers4.lines().begin(); EXPECT_EQ("key 2", chli->first); EXPECT_EQ("value\n 2", chli->second); ++chli; EXPECT_EQ("key\n 3", chli->first); EXPECT_EQ("value3", chli->second); ++chli; EXPECT_EQ("key4", chli->first); EXPECT_EQ("value4", chli->second); ++chli; EXPECT_EQ(headers4.lines().end(), chli); } TEST(BalsaHeaders, IteratorWorksWithOStreamAsExpected) { { std::stringstream actual; BalsaHeaders::const_header_lines_iterator chli; actual << chli; EXPECT_THAT(actual.str(), AnyOf(StrEq("[0, 0]"), StrEq("[(nil), 0]"), StrEq("[0x0, 0]"))); } { BalsaHeaders headers; std::stringstream actual; BalsaHeaders::const_header_lines_iterator chli = headers.lines().begin(); actual << chli; std::stringstream expected; expected << "[" << &headers << ", 0]"; EXPECT_THAT(expected.str(), StrEq(actual.str())); } } TEST(BalsaHeaders, TestSetResponseReasonPhraseWithNoInitialFirstline) { BalsaHeaders balsa_headers; balsa_headers.SetResponseReasonPhrase("don't need a reason"); EXPECT_THAT(balsa_headers.first_line(), StrEq(" don't need a reason")); EXPECT_TRUE(balsa_headers.response_version().empty()); EXPECT_TRUE(balsa_headers.response_code().empty()); EXPECT_THAT(balsa_headers.response_reason_phrase(), StrEq("don't need a reason")); } TEST(BalsaHeaders, TestSetResponseReasonPhrase) { const char* response_reason_phrases[] = { "qwerty asdfgh", "qwerty", "qwerty asdfghjkl", }; size_t arraysize_squared = (ABSL_ARRAYSIZE(response_reason_phrases) * ABSL_ARRAYSIZE(response_reason_phrases)); for (size_t iteration = 0; iteration < arraysize_squared; ++iteration) { SCOPED_TRACE("Original firstline: \"HTTP/1.0 200 reason phrase\""); BalsaHeaders headers = CreateHTTPHeaders(true, "HTTP/1.0 200 reason phrase\r\n" "content-length: 0\r\n" "\r\n"); ASSERT_THAT(headers.first_line(), StrEq("HTTP/1.0 200 reason phrase")); { int first = iteration / ABSL_ARRAYSIZE(response_reason_phrases); const char* response_reason_phrase_first = response_reason_phrases[first]; std::string expected_new_firstline = absl::StrFormat("HTTP/1.0 200 %s", response_reason_phrase_first); SCOPED_TRACE(absl::StrFormat("Then set response_reason_phrase(\"%s\")", response_reason_phrase_first)); headers.SetResponseReasonPhrase(response_reason_phrase_first); EXPECT_THAT(headers.first_line(), StrEq(absl::StrFormat("HTTP/1.0 200 %s", response_reason_phrase_first))); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.0")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq(response_reason_phrase_first)); } { int second = iteration % ABSL_ARRAYSIZE(response_reason_phrases); const char* response_reason_phrase_second = response_reason_phrases[second]; std::string expected_new_firstline = absl::StrFormat("HTTP/1.0 200 %s", response_reason_phrase_second); SCOPED_TRACE(absl::StrFormat("Then set response_reason_phrase(\"%s\")", response_reason_phrase_second)); headers.SetResponseReasonPhrase(response_reason_phrase_second); EXPECT_THAT(headers.first_line(), StrEq(absl::StrFormat("HTTP/1.0 200 %s", response_reason_phrase_second))); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.0")); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq(response_reason_phrase_second)); } } } TEST(BalsaHeaders, TestSetResponseVersionWithNoInitialFirstline) { BalsaHeaders balsa_headers; balsa_headers.SetResponseVersion("HTTP/1.1"); EXPECT_THAT(balsa_headers.first_line(), StrEq("HTTP/1.1 ")); EXPECT_THAT(balsa_headers.response_version(), StrEq("HTTP/1.1")); EXPECT_TRUE(balsa_headers.response_code().empty()); EXPECT_TRUE(balsa_headers.response_reason_phrase().empty()); } TEST(BalsaHeaders, TestSetResponseVersion) { const char* response_versions[] = { "ABCD/123", "ABCD", "ABCD/123456", }; size_t arraysize_squared = (ABSL_ARRAYSIZE(response_versions) * ABSL_ARRAYSIZE(response_versions)); for (size_t iteration = 0; iteration < arraysize_squared; ++iteration) { SCOPED_TRACE("Original firstline: \"HTTP/1.0 200 reason phrase\""); BalsaHeaders headers = CreateHTTPHeaders(false, "HTTP/1.0 200 reason phrase\r\n" "content-length: 0\r\n" "\r\n"); ASSERT_THAT(headers.first_line(), StrEq("HTTP/1.0 200 reason phrase")); { int first = iteration / ABSL_ARRAYSIZE(response_versions); const char* response_version_first = response_versions[first]; std::string expected_new_firstline = absl::StrFormat("%s 200 reason phrase", response_version_first); SCOPED_TRACE(absl::StrFormat("Then set response_version(\"%s\")", response_version_first)); headers.SetResponseVersion(response_version_first); EXPECT_THAT(headers.first_line(), StrEq(expected_new_firstline)); EXPECT_THAT(headers.response_version(), StrEq(response_version_first)); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); } { int second = iteration % ABSL_ARRAYSIZE(response_versions); const char* response_version_second = response_versions[second]; std::string expected_new_firstline = absl::StrFormat("%s 200 reason phrase", response_version_second); SCOPED_TRACE(absl::StrFormat("Then set response_version(\"%s\")", response_version_second)); headers.SetResponseVersion(response_version_second); EXPECT_THAT(headers.first_line(), StrEq(expected_new_firstline)); EXPECT_THAT(headers.response_version(), StrEq(response_version_second)); EXPECT_THAT(headers.response_code(), StrEq("200")); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); } } } TEST(BalsaHeaders, TestSetResponseReasonAndVersionWithNoInitialFirstline) { BalsaHeaders headers; headers.SetResponseVersion("HTTP/1.1"); headers.SetResponseReasonPhrase("don't need a reason"); EXPECT_THAT(headers.first_line(), StrEq("HTTP/1.1 don't need a reason")); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.1")); EXPECT_TRUE(headers.response_code().empty()); EXPECT_THAT(headers.response_reason_phrase(), StrEq("don't need a reason")); } TEST(BalsaHeaders, TestSetResponseCodeWithNoInitialFirstline) { BalsaHeaders balsa_headers; balsa_headers.SetParsedResponseCodeAndUpdateFirstline(2002); EXPECT_THAT(balsa_headers.first_line(), StrEq(" 2002 ")); EXPECT_TRUE(balsa_headers.response_version().empty()); EXPECT_THAT(balsa_headers.response_code(), StrEq("2002")); EXPECT_TRUE(balsa_headers.response_reason_phrase().empty()); EXPECT_THAT(balsa_headers.parsed_response_code(), Eq(2002)); } TEST(BalsaHeaders, TestSetParsedResponseCode) { BalsaHeaders balsa_headers; balsa_headers.set_parsed_response_code(std::numeric_limits<int>::max()); EXPECT_THAT(balsa_headers.parsed_response_code(), Eq(std::numeric_limits<int>::max())); } TEST(BalsaHeaders, TestSetResponseCode) { const char* response_codes[] = { "200" "23", "200200", }; size_t arraysize_squared = (ABSL_ARRAYSIZE(response_codes) * ABSL_ARRAYSIZE(response_codes)); for (size_t iteration = 0; iteration < arraysize_squared; ++iteration) { SCOPED_TRACE("Original firstline: \"HTTP/1.0 200 reason phrase\""); BalsaHeaders headers = CreateHTTPHeaders(false, "HTTP/1.0 200 reason phrase\r\n" "content-length: 0\r\n" "\r\n"); ASSERT_THAT(headers.first_line(), StrEq("HTTP/1.0 200 reason phrase")); { int first = iteration / ABSL_ARRAYSIZE(response_codes); const char* response_code_first = response_codes[first]; std::string expected_new_firstline = absl::StrFormat("HTTP/1.0 %s reason phrase", response_code_first); SCOPED_TRACE(absl::StrFormat("Then set response_code(\"%s\")", response_code_first)); headers.SetResponseCode(response_code_first); EXPECT_THAT(headers.first_line(), StrEq(expected_new_firstline)); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.0")); EXPECT_THAT(headers.response_code(), StrEq(response_code_first)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); } { int second = iteration % ABSL_ARRAYSIZE(response_codes); const char* response_code_second = response_codes[second]; std::string expected_new_secondline = absl::StrFormat("HTTP/1.0 %s reason phrase", response_code_second); SCOPED_TRACE(absl::StrFormat("Then set response_code(\"%s\")", response_code_second)); headers.SetResponseCode(response_code_second); EXPECT_THAT(headers.first_line(), StrEq(expected_new_secondline)); EXPECT_THAT(headers.response_version(), StrEq("HTTP/1.0")); EXPECT_THAT(headers.response_code(), StrEq(response_code_second)); EXPECT_THAT(headers.response_reason_phrase(), StrEq("reason phrase")); } } } TEST(BalsaHeaders, TestAppendToHeader) { BalsaHeaders headers; headers.AppendHeader("foo", "foo_value"); headers.AppendHeader("bar", "bar_value"); headers.AppendToHeader("foo", "foo_value2"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value,foo_value2")); EXPECT_THAT(headers.GetHeader("bar"), StrEq("bar_value")); } TEST(BalsaHeaders, TestInitialAppend) { BalsaHeaders headers; headers.AppendToHeader("foo", "foo_value"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value")); headers.AppendToHeader("foo", "foo_value2"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value,foo_value2")); } TEST(BalsaHeaders, TestAppendAndRemove) { BalsaHeaders headers; headers.AppendToHeader("foo", "foo_value"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value")); headers.AppendToHeader("foo", "foo_value2"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value,foo_value2")); headers.RemoveAllOfHeader("foo"); headers.AppendToHeader("foo", "foo_value3"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value3")); headers.AppendToHeader("foo", "foo_value4"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value3,foo_value4")); } TEST(BalsaHeaders, TestAppendToHeaderWithCommaAndSpace) { BalsaHeaders headers; headers.AppendHeader("foo", "foo_value"); headers.AppendHeader("bar", "bar_value"); headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value2"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value, foo_value2")); EXPECT_THAT(headers.GetHeader("bar"), StrEq("bar_value")); } TEST(BalsaHeaders, TestInitialAppendWithCommaAndSpace) { BalsaHeaders headers; headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value")); headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value2"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value, foo_value2")); } TEST(BalsaHeaders, TestAppendWithCommaAndSpaceAndRemove) { BalsaHeaders headers; headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value")); headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value2"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value, foo_value2")); headers.RemoveAllOfHeader("foo"); headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value3"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value3")); headers.AppendToHeaderWithCommaAndSpace("foo", "foo_value4"); EXPECT_THAT(headers.GetHeader("foo"), StrEq("foo_value3, foo_value4")); } TEST(BalsaHeaders, SetContentLength) { BalsaHeaders headers; headers.SetContentLength(10); EXPECT_THAT(headers.GetHeader("Content-length"), StrEq("10")); EXPECT_EQ(BalsaHeadersEnums::VALID_CONTENT_LENGTH, headers.content_length_status()); EXPECT_TRUE(headers.content_length_valid()); headers.SetContentLength(0); EXPECT_THAT(headers.GetHeader("Content-length"), StrEq("0")); EXPECT_EQ(BalsaHeadersEnums::VALID_CONTENT_LENGTH, headers.content_length_status()); EXPECT_TRUE(headers.content_length_valid()); BalsaHeaders::const_header_lines_iterator iter = headers.GetHeaderPosition("Content-length"); EXPECT_EQ(headers.lines().begin(), iter); EXPECT_EQ(headers.lines().end(), ++iter); headers.SetContentLength(0); EXPECT_THAT(headers.GetHeader("Content-length"), StrEq("0")); EXPECT_EQ(BalsaHeadersEnums::VALID_CONTENT_LENGTH, headers.content_length_status()); EXPECT_TRUE(headers.content_length_valid()); iter = headers.GetHeaderPosition("Content-length"); EXPECT_EQ(headers.lines().begin(), iter); EXPECT_EQ(headers.lines().end(), ++iter); } TEST(BalsaHeaders, ToggleChunkedEncoding) { BalsaHeaders headers; headers.SetTransferEncodingToChunkedAndClearContentLength(); EXPECT_EQ("chunked", headers.GetAllOfHeaderAsString("Transfer-Encoding")); EXPECT_TRUE(headers.HasHeadersWithPrefix("Transfer-Encoding")); EXPECT_TRUE(headers.HasHeadersWithPrefix("transfer-encoding")); EXPECT_TRUE(headers.HasHeadersWithPrefix("transfer")); EXPECT_TRUE(headers.transfer_encoding_is_chunked()); headers.SetTransferEncodingToChunkedAndClearContentLength(); EXPECT_EQ("chunked", headers.GetAllOfHeaderAsString("Transfer-Encoding")); EXPECT_TRUE(headers.HasHeadersWithPrefix("Transfer-Encoding")); EXPECT_TRUE(headers.HasHeadersWithPrefix("transfer-encoding")); EXPECT_TRUE(headers.HasHeadersWithPrefix("transfer")); EXPECT_TRUE(headers.transfer_encoding_is_chunked()); BalsaHeaders::const_header_lines_iterator iter = headers.GetHeaderPosition("Transfer-Encoding"); EXPECT_EQ(headers.lines().begin(), iter); EXPECT_EQ(headers.lines().end(), ++iter); headers.SetNoTransferEncoding(); EXPECT_FALSE(headers.HasHeader("Transfer-Encoding")); EXPECT_FALSE(headers.HasHeadersWithPrefix("Transfer-Encoding")); EXPECT_FALSE(headers.HasHeadersWithPrefix("transfer-encoding")); EXPECT_FALSE(headers.HasHeadersWithPrefix("transfer")); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); EXPECT_EQ(headers.lines().end(), headers.lines().begin()); headers.SetNoTransferEncoding(); EXPECT_FALSE(headers.HasHeader("Transfer-Encoding")); EXPECT_FALSE(headers.HasHeadersWithPrefix("Transfer-Encoding")); EXPECT_FALSE(headers.HasHeadersWithPrefix("transfer-encoding")); EXPECT_FALSE(headers.HasHeadersWithPrefix("transfer")); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); EXPECT_EQ(headers.lines().end(), headers.lines().begin()); } TEST(BalsaHeaders, SetNoTransferEncodingByRemoveHeader) { BalsaHeaders headers; headers.SetTransferEncodingToChunkedAndClearContentLength(); headers.RemoveAllOfHeader("Transfer-Encoding"); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); headers.SetTransferEncodingToChunkedAndClearContentLength(); std::vector<absl::string_view> headers_to_remove; headers_to_remove.emplace_back("Transfer-Encoding"); headers.RemoveAllOfHeaderInList(headers_to_remove); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); headers.SetTransferEncodingToChunkedAndClearContentLength(); headers.RemoveAllHeadersWithPrefix("Transfer"); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); } TEST(BalsaHeaders, ClearContentLength) { BalsaHeaders headers; headers.SetContentLength(10); headers.ClearContentLength(); EXPECT_FALSE(headers.HasHeader("Content-length")); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_FALSE(headers.content_length_valid()); headers.ClearContentLength(); EXPECT_FALSE(headers.HasHeader("Content-length")); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_FALSE(headers.content_length_valid()); headers.SetTransferEncodingToChunkedAndClearContentLength(); headers.ClearContentLength(); EXPECT_EQ("chunked", headers.GetAllOfHeaderAsString("Transfer-Encoding")); EXPECT_TRUE(headers.transfer_encoding_is_chunked()); BalsaHeaders::const_header_lines_iterator iter = headers.GetHeaderPosition("Transfer-Encoding"); EXPECT_EQ(headers.lines().begin(), iter); EXPECT_EQ(headers.lines().end(), ++iter); headers.SetNoTransferEncoding(); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_FALSE(headers.content_length_valid()); } TEST(BalsaHeaders, ClearContentLengthByRemoveHeader) { BalsaHeaders headers; headers.SetContentLength(10); headers.RemoveAllOfHeader("Content-Length"); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_EQ(0u, headers.content_length()); EXPECT_FALSE(headers.content_length_valid()); headers.SetContentLength(11); std::vector<absl::string_view> headers_to_remove; headers_to_remove.emplace_back("Content-Length"); headers.RemoveAllOfHeaderInList(headers_to_remove); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_EQ(0u, headers.content_length()); EXPECT_FALSE(headers.content_length_valid()); headers.SetContentLength(12); headers.RemoveAllHeadersWithPrefix("Content"); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_EQ(0u, headers.content_length()); EXPECT_FALSE(headers.content_length_valid()); } TEST(BalsaHeaders, IdentityCodingToChunked) { std::string message = "HTTP/1.1 200 OK\r\n" "Transfer-Encoding: identity\r\n\r\n"; BalsaHeaders headers; BalsaFrame balsa_frame; balsa_frame.set_is_request(false); balsa_frame.set_balsa_headers(&headers); EXPECT_EQ(message.size(), balsa_frame.ProcessInput(message.data(), message.size())); EXPECT_TRUE(headers.is_framed_by_connection_close()); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); EXPECT_THAT(headers.GetAllOfHeader("Transfer-Encoding"), ElementsAre("identity")); headers.SetTransferEncodingToChunkedAndClearContentLength(); EXPECT_FALSE(headers.is_framed_by_connection_close()); EXPECT_TRUE(headers.transfer_encoding_is_chunked()); EXPECT_THAT(headers.GetAllOfHeader("Transfer-Encoding"), ElementsAre("chunked")); } TEST(BalsaHeaders, SwitchContentLengthToChunk) { BalsaHeaders headers; headers.SetContentLength(10); EXPECT_THAT(headers.GetHeader("Content-length"), StrEq("10")); EXPECT_EQ(BalsaHeadersEnums::VALID_CONTENT_LENGTH, headers.content_length_status()); EXPECT_TRUE(headers.content_length_valid()); headers.SetTransferEncodingToChunkedAndClearContentLength(); EXPECT_EQ("chunked", headers.GetAllOfHeaderAsString("Transfer-Encoding")); EXPECT_TRUE(headers.transfer_encoding_is_chunked()); EXPECT_FALSE(headers.HasHeader("Content-length")); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_FALSE(headers.content_length_valid()); } TEST(BalsaHeaders, SwitchChunkedToContentLength) { BalsaHeaders headers; headers.SetTransferEncodingToChunkedAndClearContentLength(); EXPECT_EQ("chunked", headers.GetAllOfHeaderAsString("Transfer-Encoding")); EXPECT_TRUE(headers.transfer_encoding_is_chunked()); EXPECT_FALSE(headers.HasHeader("Content-length")); EXPECT_EQ(BalsaHeadersEnums::NO_CONTENT_LENGTH, headers.content_length_status()); EXPECT_FALSE(headers.content_length_valid()); headers.SetContentLength(10); EXPECT_THAT(headers.GetHeader("Content-length"), StrEq("10")); EXPECT_EQ(BalsaHeadersEnums::VALID_CONTENT_LENGTH, headers.content_length_status()); EXPECT_TRUE(headers.content_length_valid()); EXPECT_FALSE(headers.HasHeader("Transfer-Encoding")); EXPECT_FALSE(headers.transfer_encoding_is_chunked()); } TEST(BalsaHeaders, OneHundredResponseMessagesNoFramedByClose) { BalsaHeaders headers; headers.SetResponseFirstline("HTTP/1.1", 100, "Continue"); EXPECT_FALSE(headers.is_framed_by_connection_close()); } TEST(BalsaHeaders, TwoOhFourResponseMessagesNoFramedByClose) { BalsaHeaders headers; headers.SetResponseFirstline("HTTP/1.1", 204, "Continue"); EXPECT_FALSE(headers.is_framed_by_connection_close()); } TEST(BalsaHeaders, ThreeOhFourResponseMessagesNoFramedByClose) { BalsaHeaders headers; headers.SetResponseFirstline("HTTP/1.1", 304, "Continue"); EXPECT_FALSE(headers.is_framed_by_connection_close()); } TEST(BalsaHeaders, InvalidCharInHeaderValue) { std::string message = "GET http: "Host: \x01\x01www.265.com\r\n" "\r\n"; BalsaHeaders headers = CreateHTTPHeaders(true, message); EXPECT_EQ("www.265.com", headers.GetHeader("Host")); SimpleBuffer buffer; headers.WriteHeaderAndEndingToBuffer(&buffer); message.replace(message.find_first_of(0x1), 2, ""); EXPECT_EQ(message, buffer.GetReadableRegion()); } TEST(BalsaHeaders, CarriageReturnAtStartOfLine) { std::string message = "GET /foo HTTP/1.1\r\n" "Host: www.265.com\r\n" "Foo: bar\r\n" "\rX-User-Ip: 1.2.3.4\r\n" "\r\n"; BalsaHeaders headers; BalsaFrame balsa_frame; balsa_frame.set_is_request(true); balsa_frame.set_balsa_headers(&headers); EXPECT_EQ(message.size(), balsa_frame.ProcessInput(message.data(), message.size())); EXPECT_EQ(BalsaFrameEnums::INVALID_HEADER_FORMAT, balsa_frame.ErrorCode()); EXPECT_TRUE(balsa_frame.Error()); } TEST(BalsaHeaders, CheckEmpty) { BalsaHeaders headers; EXPECT_TRUE(headers.IsEmpty()); } TEST(BalsaHeaders, CheckNonEmpty) { BalsaHeaders headers; BalsaHeadersTestPeer::WriteFromFramer(&headers, "a b c", 5); EXPECT_FALSE(headers.IsEmpty()); } TEST(BalsaHeaders, ForEachHeader) { BalsaHeaders headers; headers.AppendHeader(":host", "SomeHost"); headers.AppendHeader("key", "val1,val2val2,val2,val3"); headers.AppendHeader("key", "val4val5val6"); headers.AppendHeader("key", "val11 val12"); headers.AppendHeader("key", "v val13"); headers.AppendHeader("key", "val7"); headers.AppendHeader("key", ""); headers.AppendHeader("key", "val8 , val9 ,, val10"); headers.AppendHeader("key", " val14 "); headers.AppendHeader("key2", "val15"); headers.AppendHeader("key", "Val16"); headers.AppendHeader("key", "foo, Val17, bar"); headers.AppendHeader("date", "2 Jan 1970"); headers.AppendHeader("AcceptEncoding", "MyFavoriteEncoding"); { std::string result; EXPECT_TRUE(headers.ForEachHeader( [&result](const absl::string_view key, absl::string_view value) { result.append("<") .append(key.data(), key.size()) .append("> = <") .append(value.data(), value.size()) .append(">\n"); return true; })); EXPECT_EQ(result, "<:host> = <SomeHost>\n" "<key> = <val1,val2val2,val2,val3>\n" "<key> = <val4val5val6>\n" "<key> = <val11 val12>\n" "<key> = <v val13>\n" "<key> = <val7>\n" "<key> = <>\n" "<key> = <val8 , val9 ,, val10>\n" "<key> = < val14 >\n" "<key2> = <val15>\n" "<key> = <Val16>\n" "<key> = <foo, Val17, bar>\n" "<date> = <2 Jan 1970>\n" "<AcceptEncoding> = <MyFavoriteEncoding>\n"); } { std::string result; EXPECT_FALSE(headers.ForEachHeader( [&result](const absl::string_view key, absl::string_view value) { result.append("<") .append(key.data(), key.size()) .append("> = <") .append(value.data(), value.size()) .append(">\n"); return !value.empty(); })); EXPECT_EQ(result, "<:host> = <SomeHost>\n" "<key> = <val1,val2val2,val2,val3>\n" "<key> = <val4val5val6>\n" "<key> = <val11 val12>\n" "<key> = <v val13>\n" "<key> = <val7>\n" "<key> = <>\n"); } } TEST(BalsaHeaders, WriteToBufferWithLowerCasedHeaderKey) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("Key1", "value1"); headers.AppendHeader("Key2", "value2"); std::string expected_lower_case = "GET / HTTP/1.0\r\n" "key1: value1\r\n" "key2: value2\r\n"; std::string expected_lower_case_with_end = "GET / HTTP/1.0\r\n" "key1: value1\r\n" "key2: value2\r\n\r\n"; std::string expected_upper_case = "GET / HTTP/1.0\r\n" "Key1: value1\r\n" "Key2: value2\r\n"; std::string expected_upper_case_with_end = "GET / HTTP/1.0\r\n" "Key1: value1\r\n" "Key2: value2\r\n\r\n"; SimpleBuffer simple_buffer; headers.WriteToBuffer(&simple_buffer, BalsaHeaders::CaseOption::kLowercase, BalsaHeaders::CoalesceOption::kNoCoalesce); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected_lower_case)); simple_buffer.Clear(); headers.WriteToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected_upper_case)); simple_buffer.Clear(); headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected_upper_case_with_end)); simple_buffer.Clear(); headers.WriteHeaderAndEndingToBuffer( &simple_buffer, BalsaHeaders::CaseOption::kLowercase, BalsaHeaders::CoalesceOption::kNoCoalesce); EXPECT_THAT(simple_buffer.GetReadableRegion(), StrEq(expected_lower_case_with_end)); } TEST(BalsaHeaders, WriteToBufferWithProperCasedHeaderKey) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("Te", "value1"); headers.AppendHeader("my-Test-header", "value2"); std::string expected_proper_case = "GET / HTTP/1.0\r\n" "TE: value1\r\n" "My-Test-Header: value2\r\n"; std::string expected_proper_case_with_end = "GET / HTTP/1.0\r\n" "TE: value1\r\n" "My-Test-Header: value2\r\n\r\n"; std::string expected_unmodified = "GET / HTTP/1.0\r\n" "Te: value1\r\n" "my-Test-header: value2\r\n"; std::string expected_unmodified_with_end = "GET / HTTP/1.0\r\n" "Te: value1\r\n" "my-Test-header: value2\r\n\r\n"; SimpleBuffer simple_buffer; headers.WriteToBuffer(&simple_buffer, BalsaHeaders::CaseOption::kPropercase, BalsaHeaders::CoalesceOption::kNoCoalesce); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_proper_case); simple_buffer.Clear(); headers.WriteToBuffer(&simple_buffer, BalsaHeaders::CaseOption::kNoModification, BalsaHeaders::CoalesceOption::kNoCoalesce); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_unmodified); simple_buffer.Clear(); headers.WriteHeaderAndEndingToBuffer( &simple_buffer, BalsaHeaders::CaseOption::kNoModification, BalsaHeaders::CoalesceOption::kNoCoalesce); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_unmodified_with_end); simple_buffer.Clear(); headers.WriteHeaderAndEndingToBuffer( &simple_buffer, BalsaHeaders::CaseOption::kPropercase, BalsaHeaders::CoalesceOption::kNoCoalesce); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_proper_case_with_end); } TEST(BalsaHeadersTest, ToPropercaseTest) { EXPECT_EQ(BalsaHeaders::ToPropercase(""), ""); EXPECT_EQ(BalsaHeaders::ToPropercase("Foo"), "Foo"); EXPECT_EQ(BalsaHeaders::ToPropercase("foO"), "Foo"); EXPECT_EQ(BalsaHeaders::ToPropercase("my-test-header"), "My-Test-Header"); EXPECT_EQ(BalsaHeaders::ToPropercase("my--test-header"), "My--Test-Header"); } TEST(BalsaHeaders, WriteToBufferCoalescingMultivaluedHeaders) { BalsaHeaders::MultivaluedHeadersSet multivalued_headers; multivalued_headers.insert("KeY1"); multivalued_headers.insert("another_KEY"); BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("Key1", "value1"); headers.AppendHeader("Key2", "value2"); headers.AppendHeader("Key1", "value11"); headers.AppendHeader("Key2", "value21"); headers.AppendHeader("Key1", "multiples, values, already"); std::string expected_non_coalesced = "GET / HTTP/1.0\r\n" "Key1: value1\r\n" "Key2: value2\r\n" "Key1: value11\r\n" "Key2: value21\r\n" "Key1: multiples, values, already\r\n"; std::string expected_coalesced = "Key1: value1,value11,multiples, values, already\r\n" "Key2: value2\r\n" "Key2: value21\r\n"; SimpleBuffer simple_buffer; headers.WriteToBuffer(&simple_buffer); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_non_coalesced); simple_buffer.Clear(); headers.WriteToBufferCoalescingMultivaluedHeaders( &simple_buffer, multivalued_headers, BalsaHeaders::CaseOption::kNoModification); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_coalesced); } TEST(BalsaHeaders, WriteToBufferCoalescingMultivaluedHeadersMultiLine) { BalsaHeaders::MultivaluedHeadersSet multivalued_headers; multivalued_headers.insert("Key 2"); multivalued_headers.insert("key\n 3"); BalsaHeaders headers; headers.AppendHeader("key1", "value1"); headers.AppendHeader("key 2", "value\n 2"); headers.AppendHeader("key\n 3", "value3"); headers.AppendHeader("key 2", "value 21"); headers.AppendHeader("key 3", "value 33"); std::string expected_non_coalesced = "\r\n" "key1: value1\r\n" "key 2: value\n" " 2\r\n" "key\n" " 3: value3\r\n" "key 2: value 21\r\n" "key 3: value 33\r\n"; SimpleBuffer simple_buffer; headers.WriteToBuffer(&simple_buffer); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_non_coalesced); std::string expected_coalesced = "key1: value1\r\n" "key 2: value\n" " 2,value 21\r\n" "key\n" " 3: value3\r\n" "key 3: value 33\r\n"; simple_buffer.Clear(); headers.WriteToBufferCoalescingMultivaluedHeaders( &simple_buffer, multivalued_headers, BalsaHeaders::CaseOption::kNoModification); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_coalesced); } TEST(BalsaHeaders, WriteToBufferCoalescingEnvoyHeaders) { BalsaHeaders headers; headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0"); headers.AppendHeader("User-Agent", "UserAgent1"); headers.AppendHeader("Key2", "value2"); headers.AppendHeader("USER-AGENT", "UA2"); headers.AppendHeader("Set-Cookie", "Cookie1=aaa"); headers.AppendHeader("user-agent", "agent3"); headers.AppendHeader("Set-Cookie", "Cookie2=bbb"); std::string expected_non_coalesced = "GET / HTTP/1.0\r\n" "User-Agent: UserAgent1\r\n" "Key2: value2\r\n" "USER-AGENT: UA2\r\n" "Set-Cookie: Cookie1=aaa\r\n" "user-agent: agent3\r\n" "Set-Cookie: Cookie2=bbb\r\n" "\r\n"; std::string expected_coalesced = "GET / HTTP/1.0\r\n" "User-Agent: UserAgent1,UA2,agent3\r\n" "Key2: value2\r\n" "Set-Cookie: Cookie1=aaa\r\n" "Set-Cookie: Cookie2=bbb\r\n" "\r\n"; SimpleBuffer simple_buffer; headers.WriteHeaderAndEndingToBuffer(&simple_buffer); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_non_coalesced); simple_buffer.Clear(); headers.WriteHeaderAndEndingToBuffer( &simple_buffer, BalsaHeaders::CaseOption::kNoModification, BalsaHeaders::CoalesceOption::kCoalesce); EXPECT_EQ(simple_buffer.GetReadableRegion(), expected_coalesced); } TEST(BalsaHeadersTest, RemoveLastTokenFromOneLineHeader) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET /foo HTTP/1.1\r\n" "Content-Length: 0\r\n" "Content-Encoding: gzip, 3des, tar, prc\r\n\r\n"); BalsaHeaders::const_header_lines_key_iterator it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip, 3des, tar, prc", it->second); EXPECT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip, 3des, tar", it->second); EXPECT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip, 3des", it->second); EXPECT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip", it->second); EXPECT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); EXPECT_FALSE(headers.HasHeader("Content-Encoding")); } TEST(BalsaHeadersTest, RemoveLastTokenFromMultiLineHeader) { BalsaHeaders headers = CreateHTTPHeaders(true, "GET /foo HTTP/1.1\r\n" "Content-Length: 0\r\n" "Content-Encoding: gzip, 3des\r\n" "Content-Encoding: tar, prc\r\n\r\n"); BalsaHeaders::const_header_lines_key_iterator it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip, 3des", it->second); ASSERT_EQ("tar, prc", (++it)->second); ASSERT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip, 3des", it->second); ASSERT_EQ("tar", (++it)->second); ASSERT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip, 3des", it->second); ASSERT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); it = headers.GetIteratorForKey("Content-Encoding"); ASSERT_EQ("gzip", it->second); ASSERT_EQ(headers.header_lines_key_end(), ++it); headers.RemoveLastTokenFromHeaderValue("Content-Encoding"); EXPECT_FALSE(headers.HasHeader("Content-Encoding")); } TEST(BalsaHeadersTest, ResponseCanHaveBody) { EXPECT_FALSE(BalsaHeaders::ResponseCanHaveBody(100)); EXPECT_FALSE(BalsaHeaders::ResponseCanHaveBody(101)); EXPECT_FALSE(BalsaHeaders::ResponseCanHaveBody(102)); EXPECT_FALSE(BalsaHeaders::ResponseCanHaveBody(204)); EXPECT_FALSE(BalsaHeaders::ResponseCanHaveBody(304)); EXPECT_TRUE(BalsaHeaders::ResponseCanHaveBody(200)); EXPECT_TRUE(BalsaHeaders::ResponseCanHaveBody(302)); EXPECT_TRUE(BalsaHeaders::ResponseCanHaveBody(404)); EXPECT_TRUE(BalsaHeaders::ResponseCanHaveBody(502)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/balsa_headers.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/balsa_headers_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f23edeb0-accf-4935-9f5b-21406e911acd
cpp
google/quiche
balsa_headers_sequence
quiche/balsa/balsa_headers_sequence.cc
quiche/balsa/balsa_headers_sequence_test.cc
#include "quiche/balsa/balsa_headers_sequence.h" #include <memory> #include <utility> #include "quiche/balsa/balsa_headers.h" namespace quiche { void BalsaHeadersSequence::Append(std::unique_ptr<BalsaHeaders> headers) { sequence_.push_back(std::move(headers)); } bool BalsaHeadersSequence::HasNext() const { return next_ < sequence_.size(); } BalsaHeaders* BalsaHeadersSequence::PeekNext() { if (!HasNext()) { return nullptr; } return sequence_[next_].get(); } BalsaHeaders* BalsaHeadersSequence::Next() { if (!HasNext()) { return nullptr; } return sequence_[next_++].get(); } void BalsaHeadersSequence::Clear() { sequence_.clear(); next_ = 0; } }
#include "quiche/balsa/balsa_headers_sequence.h" #include <memory> #include <utility> #include "quiche/balsa/balsa_headers.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { TEST(BalsaHeadersSequenceTest, Initial) { BalsaHeadersSequence sequence; EXPECT_FALSE(sequence.HasNext()); EXPECT_EQ(sequence.Next(), nullptr); EXPECT_TRUE(sequence.IsEmpty()); } TEST(BalsaHeadersSequenceTest, Basic) { BalsaHeadersSequence sequence; auto headers_one = std::make_unique<BalsaHeaders>(); headers_one->AppendHeader("one", "fish"); sequence.Append(std::move(headers_one)); EXPECT_TRUE(sequence.HasNext()); EXPECT_FALSE(sequence.IsEmpty()); auto headers_two = std::make_unique<BalsaHeaders>(); headers_two->AppendHeader("two", "fish"); sequence.Append(std::move(headers_two)); EXPECT_TRUE(sequence.HasNext()); EXPECT_FALSE(sequence.IsEmpty()); const BalsaHeaders* headers = sequence.Next(); ASSERT_NE(headers, nullptr); EXPECT_TRUE(headers->HasHeader("one")); EXPECT_TRUE(sequence.HasNext()); EXPECT_FALSE(sequence.IsEmpty()); headers = sequence.Next(); ASSERT_NE(headers, nullptr); EXPECT_TRUE(headers->HasHeader("two")); EXPECT_FALSE(sequence.HasNext()); EXPECT_FALSE(sequence.IsEmpty()); EXPECT_EQ(sequence.Next(), nullptr); } TEST(BalsaHeadersSequenceTest, Clear) { BalsaHeadersSequence sequence; auto headers_one = std::make_unique<BalsaHeaders>(); headers_one->AppendHeader("one", "fish"); sequence.Append(std::move(headers_one)); EXPECT_TRUE(sequence.HasNext()); EXPECT_FALSE(sequence.IsEmpty()); auto headers_two = std::make_unique<BalsaHeaders>(); headers_two->AppendHeader("two", "fish"); sequence.Append(std::move(headers_two)); EXPECT_TRUE(sequence.HasNext()); EXPECT_FALSE(sequence.IsEmpty()); sequence.Clear(); EXPECT_FALSE(sequence.HasNext()); EXPECT_EQ(sequence.Next(), nullptr); EXPECT_TRUE(sequence.IsEmpty()); } TEST(BalsaHeadersSequenceTest, PeekNext) { BalsaHeadersSequence sequence; EXPECT_EQ(sequence.PeekNext(), nullptr); auto headers_one = std::make_unique<BalsaHeaders>(); headers_one->AppendHeader("one", "fish"); sequence.Append(std::move(headers_one)); EXPECT_TRUE(sequence.HasNext()); const BalsaHeaders* headers = sequence.PeekNext(); ASSERT_NE(headers, nullptr); EXPECT_TRUE(headers->HasHeader("one")); EXPECT_TRUE(sequence.HasNext()); EXPECT_EQ(sequence.PeekNext(), headers); auto headers_two = std::make_unique<BalsaHeaders>(); headers_two->AppendHeader("two", "fish"); sequence.Append(std::move(headers_two)); EXPECT_TRUE(sequence.HasNext()); EXPECT_EQ(sequence.PeekNext(), headers); headers = sequence.Next(); ASSERT_NE(headers, nullptr); EXPECT_TRUE(headers->HasHeader("one")); EXPECT_TRUE(sequence.HasNext()); headers = sequence.PeekNext(); ASSERT_NE(headers, nullptr); EXPECT_TRUE(headers->HasHeader("two")); EXPECT_TRUE(sequence.HasNext()); headers = sequence.Next(); ASSERT_NE(headers, nullptr); EXPECT_TRUE(headers->HasHeader("two")); EXPECT_FALSE(sequence.HasNext()); EXPECT_EQ(sequence.PeekNext(), nullptr); } TEST(BalsaHeadersSequenceTest, CanRetainValidReference) { BalsaHeadersSequence sequence; auto headers = std::make_unique<BalsaHeaders>(); headers->AppendHeader("one", "fish"); BalsaHeaders* headers_ptr = headers.get(); sequence.Append(std::move(headers)); ASSERT_TRUE(sequence.HasNext()); EXPECT_EQ(sequence.Next(), headers_ptr); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/balsa_headers_sequence.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/balsa_headers_sequence_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
56b7e2fd-62df-4e17-b887-14c15ca390a9
cpp
google/quiche
simple_buffer
quiche/balsa/simple_buffer.cc
quiche/balsa/simple_buffer_test.cc
#include "quiche/balsa/simple_buffer.h" #include <algorithm> #include <cstring> #include <memory> #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { constexpr int kMinimumSimpleBufferSize = 10; SimpleBuffer::SimpleBuffer(int size) { Reserve(size); } int SimpleBuffer::Write(const char* bytes, int size) { if (size <= 0) { QUICHE_BUG_IF(simple_buffer_write_negative_size, size < 0) << "size must not be negative: " << size; return 0; } Reserve(size); memcpy(storage_ + write_idx_, bytes, size); AdvanceWritablePtr(size); return size; } int SimpleBuffer::Read(char* bytes, int size) { if (size < 0) { QUICHE_BUG(simple_buffer_read_negative_size) << "size must not be negative: " << size; return 0; } char* read_ptr = nullptr; int read_size = 0; GetReadablePtr(&read_ptr, &read_size); read_size = std::min(read_size, size); if (read_size == 0) { return 0; } memcpy(bytes, read_ptr, read_size); AdvanceReadablePtr(read_size); return read_size; } void SimpleBuffer::Reserve(int size) { if (size < 0) { QUICHE_BUG(simple_buffer_reserve_negative_size) << "size must not be negative: " << size; return; } if (size == 0 || storage_size_ - write_idx_ >= size) { return; } char* read_ptr = nullptr; int read_size = 0; GetReadablePtr(&read_ptr, &read_size); if (read_ptr == nullptr) { QUICHE_DCHECK_EQ(0, read_size); size = std::max(size, kMinimumSimpleBufferSize); storage_ = new char[size]; storage_size_ = size; return; } if (read_size + size <= storage_size_) { memmove(storage_, read_ptr, read_size); read_idx_ = 0; write_idx_ = read_size; return; } storage_size_ = std::max(2 * storage_size_, size + read_size); char* new_storage = new char[storage_size_]; memcpy(new_storage, read_ptr, read_size); delete[] storage_; read_idx_ = 0; write_idx_ = read_size; storage_ = new_storage; } void SimpleBuffer::AdvanceReadablePtr(int amount_to_advance) { if (amount_to_advance < 0) { QUICHE_BUG(simple_buffer_advance_read_negative_arg) << "amount_to_advance must not be negative: " << amount_to_advance; return; } read_idx_ += amount_to_advance; if (read_idx_ > write_idx_) { QUICHE_BUG(simple_buffer_read_ptr_too_far) << "error: readable pointer advanced beyond writable one"; read_idx_ = write_idx_; } if (read_idx_ == write_idx_) { Clear(); } } void SimpleBuffer::AdvanceWritablePtr(int amount_to_advance) { if (amount_to_advance < 0) { QUICHE_BUG(simple_buffer_advance_write_negative_arg) << "amount_to_advance must not be negative: " << amount_to_advance; return; } write_idx_ += amount_to_advance; if (write_idx_ > storage_size_) { QUICHE_BUG(simple_buffer_write_ptr_too_far) << "error: writable pointer advanced beyond end of storage"; write_idx_ = storage_size_; } } SimpleBuffer::ReleasedBuffer SimpleBuffer::Release() { if (write_idx_ == 0) { return ReleasedBuffer{nullptr, 0}; } ReleasedBuffer buffer{std::unique_ptr<char[]>(storage_), static_cast<size_t>(write_idx_)}; Clear(); storage_ = nullptr; storage_size_ = 0; return buffer; } }
#include "quiche/balsa/simple_buffer.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { constexpr int kMinimumSimpleBufferSize = 10; const char ibuf[] = { "123456789!@#$%^&*()abcdefghijklmnopqrstu" "123456789!@#$%^&*()abcdefghijklmnopqrstu" "123456789!@#$%^&*()abcdefghijklmnopqrstu" "123456789!@#$%^&*()abcdefghijklmnopqrstu" "123456789!@#$%^&*()abcdefghijklmnopqrstu"}; } class SimpleBufferTest : public QuicheTest { public: static char* storage(SimpleBuffer& buffer) { return buffer.storage_; } static int write_idx(SimpleBuffer& buffer) { return buffer.write_idx_; } static int read_idx(SimpleBuffer& buffer) { return buffer.read_idx_; } static int storage_size(SimpleBuffer& buffer) { return buffer.storage_size_; } }; namespace { TEST_F(SimpleBufferTest, CreationWithSize) { SimpleBuffer buffer1(5); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer1)); SimpleBuffer buffer2(25); EXPECT_EQ(25, storage_size(buffer2)); } TEST_F(SimpleBufferTest, CreationWithZeroSize) { SimpleBuffer buffer(0); EXPECT_EQ(0, storage_size(buffer)); EXPECT_EQ(4, buffer.Write(ibuf, 4)); EXPECT_EQ(4, write_idx(buffer)); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); EXPECT_EQ(4, buffer.ReadableBytes()); } TEST_F(SimpleBufferTest, ReadZeroBytes) { SimpleBuffer buffer; EXPECT_EQ(0, buffer.Read(nullptr, 0)); } TEST_F(SimpleBufferTest, WriteZeroFromNullptr) { SimpleBuffer buffer; EXPECT_EQ(0, buffer.Write(nullptr, 0)); } TEST(SimpleBufferExpectBug, ReserveNegativeSize) { SimpleBuffer buffer; EXPECT_QUICHE_BUG(buffer.Reserve(-1), "size must not be negative"); } TEST(SimpleBufferExpectBug, ReadNegativeSize) { SimpleBuffer buffer; EXPECT_QUICHE_BUG(buffer.Read(nullptr, -1), "size must not be negative"); } TEST(SimpleBufferExpectBug, WriteNegativeSize) { SimpleBuffer buffer; EXPECT_QUICHE_BUG(buffer.Write(nullptr, -1), "size must not be negative"); } TEST_F(SimpleBufferTest, Basics) { SimpleBuffer buffer; EXPECT_TRUE(buffer.Empty()); EXPECT_EQ("", buffer.GetReadableRegion()); EXPECT_EQ(0, storage_size(buffer)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); char* readable_ptr = nullptr; int readable_size = 0; buffer.GetReadablePtr(&readable_ptr, &readable_size); char* writeable_ptr = nullptr; int writable_size = 0; buffer.GetWritablePtr(&writeable_ptr, &writable_size); EXPECT_EQ(storage(buffer), readable_ptr); EXPECT_EQ(0, readable_size); EXPECT_EQ(storage(buffer), writeable_ptr); EXPECT_EQ(0, writable_size); EXPECT_EQ(0, buffer.ReadableBytes()); const SimpleBuffer buffer2; EXPECT_EQ(0, buffer2.ReadableBytes()); } TEST_F(SimpleBufferTest, BasicWR) { SimpleBuffer buffer; EXPECT_EQ(4, buffer.Write(ibuf, 4)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(4, write_idx(buffer)); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); EXPECT_EQ(4, buffer.ReadableBytes()); EXPECT_EQ("1234", buffer.GetReadableRegion()); int bytes_written = 4; EXPECT_TRUE(!buffer.Empty()); char* readable_ptr = nullptr; int readable_size = 0; buffer.GetReadablePtr(&readable_ptr, &readable_size); char* writeable_ptr = nullptr; int writable_size = 0; buffer.GetWritablePtr(&writeable_ptr, &writable_size); EXPECT_EQ(storage(buffer), readable_ptr); EXPECT_EQ(4, readable_size); EXPECT_EQ(storage(buffer) + 4, writeable_ptr); EXPECT_EQ(6, writable_size); char obuf[ABSL_ARRAYSIZE(ibuf)]; int bytes_read = 0; EXPECT_EQ(4, buffer.Read(obuf + bytes_read, 40)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); EXPECT_EQ(0, buffer.ReadableBytes()); EXPECT_EQ("", buffer.GetReadableRegion()); bytes_read += 4; EXPECT_TRUE(buffer.Empty()); buffer.GetReadablePtr(&readable_ptr, &readable_size); buffer.GetWritablePtr(&writeable_ptr, &writable_size); EXPECT_EQ(storage(buffer), readable_ptr); EXPECT_EQ(0, readable_size); EXPECT_EQ(storage(buffer), writeable_ptr); EXPECT_EQ(kMinimumSimpleBufferSize, writable_size); EXPECT_EQ(bytes_written, bytes_read); for (int i = 0; i < bytes_read; ++i) { EXPECT_EQ(obuf[i], ibuf[i]); } EXPECT_EQ(10, buffer.Write(ibuf + bytes_written, 10)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(10, write_idx(buffer)); EXPECT_EQ(10, storage_size(buffer)); EXPECT_EQ(10, buffer.ReadableBytes()); bytes_written += 10; EXPECT_TRUE(!buffer.Empty()); EXPECT_EQ(6, buffer.Read(obuf + bytes_read, 6)); EXPECT_EQ(6, read_idx(buffer)); EXPECT_EQ(10, write_idx(buffer)); EXPECT_EQ(10, storage_size(buffer)); EXPECT_EQ(4, buffer.ReadableBytes()); bytes_read += 6; EXPECT_TRUE(!buffer.Empty()); EXPECT_EQ(4, buffer.Read(obuf + bytes_read, 7)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); EXPECT_EQ(10, storage_size(buffer)); EXPECT_EQ(0, buffer.ReadableBytes()); bytes_read += 4; EXPECT_TRUE(buffer.Empty()); EXPECT_EQ(bytes_written, bytes_read); for (int i = 0; i < bytes_read; ++i) { EXPECT_EQ(obuf[i], ibuf[i]); } } TEST_F(SimpleBufferTest, Reserve) { SimpleBuffer buffer; EXPECT_EQ(0, storage_size(buffer)); buffer.WriteString("foo"); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); buffer.Reserve(kMinimumSimpleBufferSize + 1); EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer)); buffer.Clear(); buffer.AdvanceWritablePtr(kMinimumSimpleBufferSize); buffer.AdvanceReadablePtr(kMinimumSimpleBufferSize - 2); EXPECT_EQ(kMinimumSimpleBufferSize, write_idx(buffer)); EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer)); buffer.Reserve(kMinimumSimpleBufferSize + 1); EXPECT_EQ(2, write_idx(buffer)); EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer)); } TEST_F(SimpleBufferTest, Extend) { SimpleBuffer buffer; EXPECT_EQ(7, buffer.Write(ibuf, 7)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(7, write_idx(buffer)); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); EXPECT_EQ(7, buffer.ReadableBytes()); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(7, write_idx(buffer)); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); EXPECT_EQ(7, buffer.ReadableBytes()); int bytes_written = 7; EXPECT_EQ(4, buffer.Write(ibuf + bytes_written, 4)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(11, write_idx(buffer)); EXPECT_EQ(20, storage_size(buffer)); EXPECT_EQ(11, buffer.ReadableBytes()); bytes_written += 4; char obuf[ABSL_ARRAYSIZE(ibuf)]; EXPECT_EQ(11, buffer.Read(obuf, 11)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); EXPECT_EQ(20, storage_size(buffer)); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); EXPECT_EQ(0, buffer.ReadableBytes()); const int bytes_read = 11; EXPECT_EQ(bytes_written, bytes_read); for (int i = 0; i < bytes_read; ++i) { EXPECT_EQ(obuf[i], ibuf[i]); } } TEST_F(SimpleBufferTest, Clear) { SimpleBuffer buffer; buffer.Clear(); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); EXPECT_EQ(0, storage_size(buffer)); EXPECT_EQ(0, buffer.ReadableBytes()); buffer.WriteString("foo"); buffer.Clear(); EXPECT_EQ(0, read_idx(buffer)); EXPECT_EQ(0, write_idx(buffer)); EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer)); EXPECT_EQ(0, buffer.ReadableBytes()); } TEST_F(SimpleBufferTest, LongWrite) { SimpleBuffer buffer; std::string s1 = "HTTP/1.1 500 Service Unavailable"; buffer.Write(s1.data(), s1.size()); buffer.Write("\r\n", 2); std::string key = "Connection"; std::string value = "close"; buffer.Write(key.data(), key.size()); buffer.Write(": ", 2); buffer.Write(value.data(), value.size()); buffer.Write("\r\n", 2); buffer.Write("\r\n", 2); std::string message = "<html><head>\n" "<meta http-equiv=\"content-type\"" " content=\"text/html;charset=us-ascii\">\n" "<style><!--\n" "body {font-family: arial,sans-serif}\n" "div.nav {margin-top: 1ex}\n" "div.nav A {font-size: 10pt; font-family: arial,sans-serif}\n" "span.nav {font-size: 10pt; font-family: arial,sans-serif;" " font-weight: bold}\n" "div.nav A,span.big {font-size: 12pt; color: #0000cc}\n" "div.nav A {font-size: 10pt; color: black}\n" "A.l:link {color: #6f6f6f}\n" "A.u:link {color: green}\n" " "</head>\n" "<body text=#000000 bgcolor=#ffffff>\n" "<table border=0 cellpadding=2 cellspacing=0 width=100%>" "<tr><td rowspan=3 width=1% nowrap>\n" "<b>" "<font face=times color=#0039b6 size=10>G</font>" "<font face=times color=#c41200 size=10>o</font>" "<font face=times color=#f3c518 size=10>o</font>" "<font face=times color=#0039b6 size=10>g</font>" "<font face=times color=#30a72f size=10>l</font>" "<font face=times color=#c41200 size=10>e</font>" "&nbsp;&nbsp;</b>\n" "<td>&nbsp;</td></tr>\n" "<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff>" " <b>Error</b></td></tr>\n" "<tr><td>&nbsp;</td></tr></table>\n" "<blockquote>\n" "<H1> Internal Server Error</H1>\n" " This server was unable to complete the request\n" "<p></blockquote>\n" "<table width=100% cellpadding=0 cellspacing=0>" "<tr><td bgcolor=#3366cc><img alt=\"\" width=1 height=4></td></tr>" "</table>" "</body></html>\n"; buffer.Write(message.data(), message.size()); const std::string correct_result = "HTTP/1.1 500 Service Unavailable\r\n" "Connection: close\r\n" "\r\n" "<html><head>\n" "<meta http-equiv=\"content-type\"" " content=\"text/html;charset=us-ascii\">\n" "<style><!--\n" "body {font-family: arial,sans-serif}\n" "div.nav {margin-top: 1ex}\n" "div.nav A {font-size: 10pt; font-family: arial,sans-serif}\n" "span.nav {font-size: 10pt; font-family: arial,sans-serif;" " font-weight: bold}\n" "div.nav A,span.big {font-size: 12pt; color: #0000cc}\n" "div.nav A {font-size: 10pt; color: black}\n" "A.l:link {color: #6f6f6f}\n" "A.u:link {color: green}\n" " "</head>\n" "<body text=#000000 bgcolor=#ffffff>\n" "<table border=0 cellpadding=2 cellspacing=0 width=100%>" "<tr><td rowspan=3 width=1% nowrap>\n" "<b>" "<font face=times color=#0039b6 size=10>G</font>" "<font face=times color=#c41200 size=10>o</font>" "<font face=times color=#f3c518 size=10>o</font>" "<font face=times color=#0039b6 size=10>g</font>" "<font face=times color=#30a72f size=10>l</font>" "<font face=times color=#c41200 size=10>e</font>" "&nbsp;&nbsp;</b>\n" "<td>&nbsp;</td></tr>\n" "<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff>" " <b>Error</b></td></tr>\n" "<tr><td>&nbsp;</td></tr></table>\n" "<blockquote>\n" "<H1> Internal Server Error</H1>\n" " This server was unable to complete the request\n" "<p></blockquote>\n" "<table width=100% cellpadding=0 cellspacing=0>" "<tr><td bgcolor=#3366cc><img alt=\"\" width=1 height=4></td></tr>" "</table>" "</body></html>\n"; EXPECT_EQ(correct_result, buffer.GetReadableRegion()); } TEST_F(SimpleBufferTest, ReleaseAsSlice) { SimpleBuffer buffer; buffer.WriteString("abc"); SimpleBuffer::ReleasedBuffer released = buffer.Release(); EXPECT_EQ("abc", absl::string_view(released.buffer.get(), released.size)); char* readable_ptr = nullptr; int readable_size = 0; buffer.GetReadablePtr(&readable_ptr, &readable_size); EXPECT_EQ(nullptr, readable_ptr); EXPECT_EQ(0, readable_size); buffer.WriteString("def"); released = buffer.Release(); buffer.GetReadablePtr(&readable_ptr, &readable_size); EXPECT_EQ(nullptr, readable_ptr); EXPECT_EQ(0, readable_size); EXPECT_EQ("def", absl::string_view(released.buffer.get(), released.size)); } TEST_F(SimpleBufferTest, EmptyBufferReleaseAsSlice) { SimpleBuffer buffer; char* readable_ptr = nullptr; int readable_size = 0; SimpleBuffer::ReleasedBuffer released = buffer.Release(); buffer.GetReadablePtr(&readable_ptr, &readable_size); EXPECT_EQ(nullptr, readable_ptr); EXPECT_EQ(0, readable_size); EXPECT_TRUE(released.buffer == nullptr); EXPECT_EQ(released.size, 0u); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/simple_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/balsa/simple_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1aab19fb-dac4-4d6e-935a-6fba6c4f96d3
cpp
google/quiche
http2_constants
quiche/http2/http2_constants.cc
quiche/http2/http2_constants_test.cc
#include "quiche/http2/http2_constants.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::string Http2FrameTypeToString(Http2FrameType v) { switch (v) { case Http2FrameType::DATA: return "DATA"; case Http2FrameType::HEADERS: return "HEADERS"; case Http2FrameType::PRIORITY: return "PRIORITY"; case Http2FrameType::RST_STREAM: return "RST_STREAM"; case Http2FrameType::SETTINGS: return "SETTINGS"; case Http2FrameType::PUSH_PROMISE: return "PUSH_PROMISE"; case Http2FrameType::PING: return "PING"; case Http2FrameType::GOAWAY: return "GOAWAY"; case Http2FrameType::WINDOW_UPDATE: return "WINDOW_UPDATE"; case Http2FrameType::CONTINUATION: return "CONTINUATION"; case Http2FrameType::ALTSVC: return "ALTSVC"; case Http2FrameType::PRIORITY_UPDATE: return "PRIORITY_UPDATE"; } return absl::StrCat("UnknownFrameType(", static_cast<int>(v), ")"); } std::string Http2FrameTypeToString(uint8_t v) { return Http2FrameTypeToString(static_cast<Http2FrameType>(v)); } std::string Http2FrameFlagsToString(Http2FrameType type, uint8_t flags) { std::string s; auto append_and_clear = [&s, &flags](absl::string_view v, uint8_t bit) { if (!s.empty()) { s.push_back('|'); } absl::StrAppend(&s, v); flags ^= bit; }; if (flags & 0x01) { if (type == Http2FrameType::DATA || type == Http2FrameType::HEADERS) { append_and_clear("END_STREAM", Http2FrameFlag::END_STREAM); } else if (type == Http2FrameType::SETTINGS || type == Http2FrameType::PING) { append_and_clear("ACK", Http2FrameFlag::ACK); } } if (flags & 0x04) { if (type == Http2FrameType::HEADERS || type == Http2FrameType::PUSH_PROMISE || type == Http2FrameType::CONTINUATION) { append_and_clear("END_HEADERS", Http2FrameFlag::END_HEADERS); } } if (flags & 0x08) { if (type == Http2FrameType::DATA || type == Http2FrameType::HEADERS || type == Http2FrameType::PUSH_PROMISE) { append_and_clear("PADDED", Http2FrameFlag::PADDED); } } if (flags & 0x20) { if (type == Http2FrameType::HEADERS) { append_and_clear("PRIORITY", Http2FrameFlag::PRIORITY); } } if (flags != 0) { append_and_clear(absl::StrFormat("0x%02x", flags), flags); } QUICHE_DCHECK_EQ(0, flags); return s; } std::string Http2FrameFlagsToString(uint8_t type, uint8_t flags) { return Http2FrameFlagsToString(static_cast<Http2FrameType>(type), flags); } std::string Http2ErrorCodeToString(uint32_t v) { switch (v) { case 0x0: return "NO_ERROR"; case 0x1: return "PROTOCOL_ERROR"; case 0x2: return "INTERNAL_ERROR"; case 0x3: return "FLOW_CONTROL_ERROR"; case 0x4: return "SETTINGS_TIMEOUT"; case 0x5: return "STREAM_CLOSED"; case 0x6: return "FRAME_SIZE_ERROR"; case 0x7: return "REFUSED_STREAM"; case 0x8: return "CANCEL"; case 0x9: return "COMPRESSION_ERROR"; case 0xa: return "CONNECT_ERROR"; case 0xb: return "ENHANCE_YOUR_CALM"; case 0xc: return "INADEQUATE_SECURITY"; case 0xd: return "HTTP_1_1_REQUIRED"; } return absl::StrCat("UnknownErrorCode(0x", absl::Hex(v), ")"); } std::string Http2ErrorCodeToString(Http2ErrorCode v) { return Http2ErrorCodeToString(static_cast<uint32_t>(v)); } std::string Http2SettingsParameterToString(uint32_t v) { switch (v) { case 0x1: return "HEADER_TABLE_SIZE"; case 0x2: return "ENABLE_PUSH"; case 0x3: return "MAX_CONCURRENT_STREAMS"; case 0x4: return "INITIAL_WINDOW_SIZE"; case 0x5: return "MAX_FRAME_SIZE"; case 0x6: return "MAX_HEADER_LIST_SIZE"; } return absl::StrCat("UnknownSettingsParameter(0x", absl::Hex(v), ")"); } std::string Http2SettingsParameterToString(Http2SettingsParameter v) { return Http2SettingsParameterToString(static_cast<uint32_t>(v)); } constexpr char const* kHttp2InvalidHeaderNames[] = { "connection", "host", "keep-alive", "proxy-connection", "transfer-encoding", "", }; const InvalidHeaderSet& GetInvalidHttp2HeaderSet() { static const auto* invalid_header_set = new InvalidHeaderSet(std::begin(http2::kHttp2InvalidHeaderNames), std::end(http2::kHttp2InvalidHeaderNames)); return *invalid_header_set; } }
#include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { class Http2ConstantsTest : public quiche::test::QuicheTest {}; TEST(Http2ConstantsTest, Http2FrameType) { EXPECT_EQ(Http2FrameType::DATA, static_cast<Http2FrameType>(0)); EXPECT_EQ(Http2FrameType::HEADERS, static_cast<Http2FrameType>(1)); EXPECT_EQ(Http2FrameType::PRIORITY, static_cast<Http2FrameType>(2)); EXPECT_EQ(Http2FrameType::RST_STREAM, static_cast<Http2FrameType>(3)); EXPECT_EQ(Http2FrameType::SETTINGS, static_cast<Http2FrameType>(4)); EXPECT_EQ(Http2FrameType::PUSH_PROMISE, static_cast<Http2FrameType>(5)); EXPECT_EQ(Http2FrameType::PING, static_cast<Http2FrameType>(6)); EXPECT_EQ(Http2FrameType::GOAWAY, static_cast<Http2FrameType>(7)); EXPECT_EQ(Http2FrameType::WINDOW_UPDATE, static_cast<Http2FrameType>(8)); EXPECT_EQ(Http2FrameType::CONTINUATION, static_cast<Http2FrameType>(9)); EXPECT_EQ(Http2FrameType::ALTSVC, static_cast<Http2FrameType>(10)); } TEST(Http2ConstantsTest, Http2FrameTypeToString) { EXPECT_EQ("DATA", Http2FrameTypeToString(Http2FrameType::DATA)); EXPECT_EQ("HEADERS", Http2FrameTypeToString(Http2FrameType::HEADERS)); EXPECT_EQ("PRIORITY", Http2FrameTypeToString(Http2FrameType::PRIORITY)); EXPECT_EQ("RST_STREAM", Http2FrameTypeToString(Http2FrameType::RST_STREAM)); EXPECT_EQ("SETTINGS", Http2FrameTypeToString(Http2FrameType::SETTINGS)); EXPECT_EQ("PUSH_PROMISE", Http2FrameTypeToString(Http2FrameType::PUSH_PROMISE)); EXPECT_EQ("PING", Http2FrameTypeToString(Http2FrameType::PING)); EXPECT_EQ("GOAWAY", Http2FrameTypeToString(Http2FrameType::GOAWAY)); EXPECT_EQ("WINDOW_UPDATE", Http2FrameTypeToString(Http2FrameType::WINDOW_UPDATE)); EXPECT_EQ("CONTINUATION", Http2FrameTypeToString(Http2FrameType::CONTINUATION)); EXPECT_EQ("ALTSVC", Http2FrameTypeToString(Http2FrameType::ALTSVC)); EXPECT_EQ("DATA", Http2FrameTypeToString(0)); EXPECT_EQ("HEADERS", Http2FrameTypeToString(1)); EXPECT_EQ("PRIORITY", Http2FrameTypeToString(2)); EXPECT_EQ("RST_STREAM", Http2FrameTypeToString(3)); EXPECT_EQ("SETTINGS", Http2FrameTypeToString(4)); EXPECT_EQ("PUSH_PROMISE", Http2FrameTypeToString(5)); EXPECT_EQ("PING", Http2FrameTypeToString(6)); EXPECT_EQ("GOAWAY", Http2FrameTypeToString(7)); EXPECT_EQ("WINDOW_UPDATE", Http2FrameTypeToString(8)); EXPECT_EQ("CONTINUATION", Http2FrameTypeToString(9)); EXPECT_EQ("ALTSVC", Http2FrameTypeToString(10)); EXPECT_EQ("UnknownFrameType(99)", Http2FrameTypeToString(99)); } TEST(Http2ConstantsTest, Http2FrameFlag) { EXPECT_EQ(Http2FrameFlag::END_STREAM, static_cast<Http2FrameFlag>(0x01)); EXPECT_EQ(Http2FrameFlag::ACK, static_cast<Http2FrameFlag>(0x01)); EXPECT_EQ(Http2FrameFlag::END_HEADERS, static_cast<Http2FrameFlag>(0x04)); EXPECT_EQ(Http2FrameFlag::PADDED, static_cast<Http2FrameFlag>(0x08)); EXPECT_EQ(Http2FrameFlag::PRIORITY, static_cast<Http2FrameFlag>(0x20)); EXPECT_EQ(Http2FrameFlag::END_STREAM, 0x01); EXPECT_EQ(Http2FrameFlag::ACK, 0x01); EXPECT_EQ(Http2FrameFlag::END_HEADERS, 0x04); EXPECT_EQ(Http2FrameFlag::PADDED, 0x08); EXPECT_EQ(Http2FrameFlag::PRIORITY, 0x20); } TEST(Http2ConstantsTest, Http2FrameFlagsToString) { EXPECT_EQ("END_STREAM", Http2FrameFlagsToString(Http2FrameType::DATA, Http2FrameFlag::END_STREAM)); EXPECT_EQ("END_STREAM", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0x01)); EXPECT_EQ("ACK", Http2FrameFlagsToString(Http2FrameType::SETTINGS, Http2FrameFlag::ACK)); EXPECT_EQ("ACK", Http2FrameFlagsToString(Http2FrameType::PING, 0x01)); EXPECT_EQ("0x02", Http2FrameFlagsToString(0xff, 0x02)); EXPECT_EQ("END_HEADERS", Http2FrameFlagsToString(Http2FrameType::HEADERS, Http2FrameFlag::END_HEADERS)); EXPECT_EQ("END_HEADERS", Http2FrameFlagsToString(Http2FrameType::PUSH_PROMISE, 0x04)); EXPECT_EQ("END_HEADERS", Http2FrameFlagsToString(0x09, 0x04)); EXPECT_EQ("0x04", Http2FrameFlagsToString(0xff, 0x04)); EXPECT_EQ("PADDED", Http2FrameFlagsToString(Http2FrameType::DATA, Http2FrameFlag::PADDED)); EXPECT_EQ("PADDED", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0x08)); EXPECT_EQ("PADDED", Http2FrameFlagsToString(0x05, 0x08)); EXPECT_EQ("0x08", Http2FrameFlagsToString(0xff, Http2FrameFlag::PADDED)); EXPECT_EQ("0x10", Http2FrameFlagsToString(Http2FrameType::SETTINGS, 0x10)); EXPECT_EQ("PRIORITY", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0x20)); EXPECT_EQ("0x20", Http2FrameFlagsToString(Http2FrameType::PUSH_PROMISE, 0x20)); EXPECT_EQ("0x40", Http2FrameFlagsToString(0xff, 0x40)); EXPECT_EQ("0x80", Http2FrameFlagsToString(0xff, 0x80)); EXPECT_EQ("END_STREAM|PADDED|0xf6", Http2FrameFlagsToString(Http2FrameType::DATA, 0xff)); EXPECT_EQ("END_STREAM|END_HEADERS|PADDED|PRIORITY|0xd2", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::PRIORITY, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::RST_STREAM, 0xff)); EXPECT_EQ("ACK|0xfe", Http2FrameFlagsToString(Http2FrameType::SETTINGS, 0xff)); EXPECT_EQ("END_HEADERS|PADDED|0xf3", Http2FrameFlagsToString(Http2FrameType::PUSH_PROMISE, 0xff)); EXPECT_EQ("ACK|0xfe", Http2FrameFlagsToString(Http2FrameType::PING, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::GOAWAY, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::WINDOW_UPDATE, 0xff)); EXPECT_EQ("END_HEADERS|0xfb", Http2FrameFlagsToString(Http2FrameType::CONTINUATION, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::ALTSVC, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(0xff, 0xff)); } TEST(Http2ConstantsTest, Http2ErrorCode) { EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, static_cast<Http2ErrorCode>(0x0)); EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, static_cast<Http2ErrorCode>(0x1)); EXPECT_EQ(Http2ErrorCode::INTERNAL_ERROR, static_cast<Http2ErrorCode>(0x2)); EXPECT_EQ(Http2ErrorCode::FLOW_CONTROL_ERROR, static_cast<Http2ErrorCode>(0x3)); EXPECT_EQ(Http2ErrorCode::SETTINGS_TIMEOUT, static_cast<Http2ErrorCode>(0x4)); EXPECT_EQ(Http2ErrorCode::STREAM_CLOSED, static_cast<Http2ErrorCode>(0x5)); EXPECT_EQ(Http2ErrorCode::FRAME_SIZE_ERROR, static_cast<Http2ErrorCode>(0x6)); EXPECT_EQ(Http2ErrorCode::REFUSED_STREAM, static_cast<Http2ErrorCode>(0x7)); EXPECT_EQ(Http2ErrorCode::CANCEL, static_cast<Http2ErrorCode>(0x8)); EXPECT_EQ(Http2ErrorCode::COMPRESSION_ERROR, static_cast<Http2ErrorCode>(0x9)); EXPECT_EQ(Http2ErrorCode::CONNECT_ERROR, static_cast<Http2ErrorCode>(0xa)); EXPECT_EQ(Http2ErrorCode::ENHANCE_YOUR_CALM, static_cast<Http2ErrorCode>(0xb)); EXPECT_EQ(Http2ErrorCode::INADEQUATE_SECURITY, static_cast<Http2ErrorCode>(0xc)); EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, static_cast<Http2ErrorCode>(0xd)); } TEST(Http2ConstantsTest, Http2ErrorCodeToString) { EXPECT_EQ("NO_ERROR", Http2ErrorCodeToString(Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_EQ("NO_ERROR", Http2ErrorCodeToString(0x0)); EXPECT_EQ("PROTOCOL_ERROR", Http2ErrorCodeToString(Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_EQ("PROTOCOL_ERROR", Http2ErrorCodeToString(0x1)); EXPECT_EQ("INTERNAL_ERROR", Http2ErrorCodeToString(Http2ErrorCode::INTERNAL_ERROR)); EXPECT_EQ("INTERNAL_ERROR", Http2ErrorCodeToString(0x2)); EXPECT_EQ("FLOW_CONTROL_ERROR", Http2ErrorCodeToString(Http2ErrorCode::FLOW_CONTROL_ERROR)); EXPECT_EQ("FLOW_CONTROL_ERROR", Http2ErrorCodeToString(0x3)); EXPECT_EQ("SETTINGS_TIMEOUT", Http2ErrorCodeToString(Http2ErrorCode::SETTINGS_TIMEOUT)); EXPECT_EQ("SETTINGS_TIMEOUT", Http2ErrorCodeToString(0x4)); EXPECT_EQ("STREAM_CLOSED", Http2ErrorCodeToString(Http2ErrorCode::STREAM_CLOSED)); EXPECT_EQ("STREAM_CLOSED", Http2ErrorCodeToString(0x5)); EXPECT_EQ("FRAME_SIZE_ERROR", Http2ErrorCodeToString(Http2ErrorCode::FRAME_SIZE_ERROR)); EXPECT_EQ("FRAME_SIZE_ERROR", Http2ErrorCodeToString(0x6)); EXPECT_EQ("REFUSED_STREAM", Http2ErrorCodeToString(Http2ErrorCode::REFUSED_STREAM)); EXPECT_EQ("REFUSED_STREAM", Http2ErrorCodeToString(0x7)); EXPECT_EQ("CANCEL", Http2ErrorCodeToString(Http2ErrorCode::CANCEL)); EXPECT_EQ("CANCEL", Http2ErrorCodeToString(0x8)); EXPECT_EQ("COMPRESSION_ERROR", Http2ErrorCodeToString(Http2ErrorCode::COMPRESSION_ERROR)); EXPECT_EQ("COMPRESSION_ERROR", Http2ErrorCodeToString(0x9)); EXPECT_EQ("CONNECT_ERROR", Http2ErrorCodeToString(Http2ErrorCode::CONNECT_ERROR)); EXPECT_EQ("CONNECT_ERROR", Http2ErrorCodeToString(0xa)); EXPECT_EQ("ENHANCE_YOUR_CALM", Http2ErrorCodeToString(Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_EQ("ENHANCE_YOUR_CALM", Http2ErrorCodeToString(0xb)); EXPECT_EQ("INADEQUATE_SECURITY", Http2ErrorCodeToString(Http2ErrorCode::INADEQUATE_SECURITY)); EXPECT_EQ("INADEQUATE_SECURITY", Http2ErrorCodeToString(0xc)); EXPECT_EQ("HTTP_1_1_REQUIRED", Http2ErrorCodeToString(Http2ErrorCode::HTTP_1_1_REQUIRED)); EXPECT_EQ("HTTP_1_1_REQUIRED", Http2ErrorCodeToString(0xd)); EXPECT_EQ("UnknownErrorCode(0x123)", Http2ErrorCodeToString(0x123)); } TEST(Http2ConstantsTest, Http2SettingsParameter) { EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE, static_cast<Http2SettingsParameter>(0x1)); EXPECT_EQ(Http2SettingsParameter::ENABLE_PUSH, static_cast<Http2SettingsParameter>(0x2)); EXPECT_EQ(Http2SettingsParameter::MAX_CONCURRENT_STREAMS, static_cast<Http2SettingsParameter>(0x3)); EXPECT_EQ(Http2SettingsParameter::INITIAL_WINDOW_SIZE, static_cast<Http2SettingsParameter>(0x4)); EXPECT_EQ(Http2SettingsParameter::MAX_FRAME_SIZE, static_cast<Http2SettingsParameter>(0x5)); EXPECT_EQ(Http2SettingsParameter::MAX_HEADER_LIST_SIZE, static_cast<Http2SettingsParameter>(0x6)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::HEADER_TABLE_SIZE)); EXPECT_TRUE( IsSupportedHttp2SettingsParameter(Http2SettingsParameter::ENABLE_PUSH)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::MAX_CONCURRENT_STREAMS)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::INITIAL_WINDOW_SIZE)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::MAX_FRAME_SIZE)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::MAX_HEADER_LIST_SIZE)); EXPECT_FALSE(IsSupportedHttp2SettingsParameter( static_cast<Http2SettingsParameter>(0))); EXPECT_FALSE(IsSupportedHttp2SettingsParameter( static_cast<Http2SettingsParameter>(7))); } TEST(Http2ConstantsTest, Http2SettingsParameterToString) { EXPECT_EQ("HEADER_TABLE_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::HEADER_TABLE_SIZE)); EXPECT_EQ("HEADER_TABLE_SIZE", Http2SettingsParameterToString(0x1)); EXPECT_EQ("ENABLE_PUSH", Http2SettingsParameterToString( Http2SettingsParameter::ENABLE_PUSH)); EXPECT_EQ("ENABLE_PUSH", Http2SettingsParameterToString(0x2)); EXPECT_EQ("MAX_CONCURRENT_STREAMS", Http2SettingsParameterToString( Http2SettingsParameter::MAX_CONCURRENT_STREAMS)); EXPECT_EQ("MAX_CONCURRENT_STREAMS", Http2SettingsParameterToString(0x3)); EXPECT_EQ("INITIAL_WINDOW_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::INITIAL_WINDOW_SIZE)); EXPECT_EQ("INITIAL_WINDOW_SIZE", Http2SettingsParameterToString(0x4)); EXPECT_EQ("MAX_FRAME_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::MAX_FRAME_SIZE)); EXPECT_EQ("MAX_FRAME_SIZE", Http2SettingsParameterToString(0x5)); EXPECT_EQ("MAX_HEADER_LIST_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::MAX_HEADER_LIST_SIZE)); EXPECT_EQ("MAX_HEADER_LIST_SIZE", Http2SettingsParameterToString(0x6)); EXPECT_EQ("UnknownSettingsParameter(0x123)", Http2SettingsParameterToString(0x123)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/http2_constants.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/http2_constants_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8f776763-05d9-45af-b2dd-3b8ed8745fe5
cpp
google/quiche
http2_structures
quiche/http2/http2_structures.cc
quiche/http2/http2_structures_test.cc
#include "quiche/http2/http2_structures.h" #include <cstring> #include <ostream> #include <sstream> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" namespace http2 { bool Http2FrameHeader::IsProbableHttpResponse() const { return (payload_length == 0x485454 && static_cast<char>(type) == 'P' && flags == '/'); } std::string Http2FrameHeader::ToString() const { return absl::StrCat("length=", payload_length, ", type=", Http2FrameTypeToString(type), ", flags=", FlagsToString(), ", stream=", stream_id); } std::string Http2FrameHeader::FlagsToString() const { return Http2FrameFlagsToString(type, flags); } bool operator==(const Http2FrameHeader& a, const Http2FrameHeader& b) { return a.payload_length == b.payload_length && a.stream_id == b.stream_id && a.type == b.type && a.flags == b.flags; } std::ostream& operator<<(std::ostream& out, const Http2FrameHeader& v) { return out << v.ToString(); } bool operator==(const Http2PriorityFields& a, const Http2PriorityFields& b) { return a.stream_dependency == b.stream_dependency && a.weight == b.weight; } std::string Http2PriorityFields::ToString() const { std::stringstream ss; ss << "E=" << (is_exclusive ? "true" : "false") << ", stream=" << stream_dependency << ", weight=" << static_cast<uint32_t>(weight); return ss.str(); } std::ostream& operator<<(std::ostream& out, const Http2PriorityFields& v) { return out << v.ToString(); } bool operator==(const Http2RstStreamFields& a, const Http2RstStreamFields& b) { return a.error_code == b.error_code; } std::ostream& operator<<(std::ostream& out, const Http2RstStreamFields& v) { return out << "error_code=" << v.error_code; } bool operator==(const Http2SettingFields& a, const Http2SettingFields& b) { return a.parameter == b.parameter && a.value == b.value; } std::ostream& operator<<(std::ostream& out, const Http2SettingFields& v) { return out << "parameter=" << v.parameter << ", value=" << v.value; } bool operator==(const Http2PushPromiseFields& a, const Http2PushPromiseFields& b) { return a.promised_stream_id == b.promised_stream_id; } std::ostream& operator<<(std::ostream& out, const Http2PushPromiseFields& v) { return out << "promised_stream_id=" << v.promised_stream_id; } bool operator==(const Http2PingFields& a, const Http2PingFields& b) { static_assert((sizeof a.opaque_bytes) == Http2PingFields::EncodedSize(), "Why not the same size?"); return 0 == std::memcmp(a.opaque_bytes, b.opaque_bytes, sizeof a.opaque_bytes); } std::ostream& operator<<(std::ostream& out, const Http2PingFields& v) { return out << "opaque_bytes=0x" << absl::BytesToHexString(absl::string_view( reinterpret_cast<const char*>(v.opaque_bytes), sizeof v.opaque_bytes)); } bool operator==(const Http2GoAwayFields& a, const Http2GoAwayFields& b) { return a.last_stream_id == b.last_stream_id && a.error_code == b.error_code; } std::ostream& operator<<(std::ostream& out, const Http2GoAwayFields& v) { return out << "last_stream_id=" << v.last_stream_id << ", error_code=" << v.error_code; } bool operator==(const Http2WindowUpdateFields& a, const Http2WindowUpdateFields& b) { return a.window_size_increment == b.window_size_increment; } std::ostream& operator<<(std::ostream& out, const Http2WindowUpdateFields& v) { return out << "window_size_increment=" << v.window_size_increment; } bool operator==(const Http2AltSvcFields& a, const Http2AltSvcFields& b) { return a.origin_length == b.origin_length; } std::ostream& operator<<(std::ostream& out, const Http2AltSvcFields& v) { return out << "origin_length=" << v.origin_length; } bool operator==(const Http2PriorityUpdateFields& a, const Http2PriorityUpdateFields& b) { return a.prioritized_stream_id == b.prioritized_stream_id; } std::string Http2PriorityUpdateFields::ToString() const { std::stringstream ss; ss << "prioritized_stream_id=" << prioritized_stream_id; return ss.str(); } std::ostream& operator<<(std::ostream& out, const Http2PriorityUpdateFields& v) { return out << v.ToString(); } }
#include "quiche/http2/http2_structures.h" #include <memory> #include <ostream> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::Combine; using ::testing::HasSubstr; using ::testing::MatchesRegex; using ::testing::Not; using ::testing::Values; using ::testing::ValuesIn; namespace http2 { namespace test { namespace { template <typename E> E IncrementEnum(E e) { using I = typename std::underlying_type<E>::type; return static_cast<E>(1 + static_cast<I>(e)); } template <class T> AssertionResult VerifyRandomCalls() { T t1; Http2Random seq1( "6d9a61ddf2bc1fc0b8245505a1f28e324559d8b5c9c3268f38b42b1af3287c47"); Randomize(&t1, &seq1); T t2; Http2Random seq2(seq1.Key()); Randomize(&t2, &seq2); HTTP2_VERIFY_EQ(seq1.Rand64(), seq2.Rand64()); HTTP2_VERIFY_EQ(t1, t2); Randomize(&t2, &seq2); HTTP2_VERIFY_NE(t1, t2); Randomize(&t1, &seq1); HTTP2_VERIFY_EQ(t1, t2); HTTP2_VERIFY_EQ(seq1.Rand64(), seq2.Rand64()); return AssertionSuccess(); } #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) std::vector<Http2FrameType> ValidFrameTypes() { std::vector<Http2FrameType> valid_types{Http2FrameType::DATA}; while (valid_types.back() != Http2FrameType::ALTSVC) { valid_types.push_back(IncrementEnum(valid_types.back())); } return valid_types; } #endif TEST(Http2FrameHeaderTest, Constructor) { Http2Random random; uint8_t frame_type = 0; do { uint32_t payload_length = random.Rand32() & 0xffffff; Http2FrameType type = static_cast<Http2FrameType>(frame_type); uint8_t flags = random.Rand8(); uint32_t stream_id = random.Rand32(); Http2FrameHeader v(payload_length, type, flags, stream_id); EXPECT_EQ(payload_length, v.payload_length); EXPECT_EQ(type, v.type); EXPECT_EQ(flags, v.flags); EXPECT_EQ(stream_id, v.stream_id); } while (frame_type++ != 255); #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) EXPECT_QUICHE_DEBUG_DEATH( Http2FrameHeader(0x01000000, Http2FrameType::DATA, 0, 1), "payload_length"); #endif } TEST(Http2FrameHeaderTest, Eq) { Http2Random random; uint32_t payload_length = random.Rand32() & 0xffffff; Http2FrameType type = static_cast<Http2FrameType>(random.Rand8()); uint8_t flags = random.Rand8(); uint32_t stream_id = random.Rand32(); Http2FrameHeader v(payload_length, type, flags, stream_id); EXPECT_EQ(payload_length, v.payload_length); EXPECT_EQ(type, v.type); EXPECT_EQ(flags, v.flags); EXPECT_EQ(stream_id, v.stream_id); Http2FrameHeader u(0, type, ~flags, stream_id); EXPECT_NE(u, v); EXPECT_NE(v, u); EXPECT_FALSE(u == v); EXPECT_FALSE(v == u); EXPECT_TRUE(u != v); EXPECT_TRUE(v != u); u = v; EXPECT_EQ(u, v); EXPECT_EQ(v, u); EXPECT_TRUE(u == v); EXPECT_TRUE(v == u); EXPECT_FALSE(u != v); EXPECT_FALSE(v != u); EXPECT_TRUE(VerifyRandomCalls<Http2FrameHeader>()); } #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) using TestParams = std::tuple<Http2FrameType, uint8_t>; std::string TestParamToString(const testing::TestParamInfo<TestParams>& info) { Http2FrameType type = std::get<0>(info.param); uint8_t flags = std::get<1>(info.param); return absl::StrCat(Http2FrameTypeToString(type), static_cast<int>(flags)); } class Http2FrameHeaderTypeAndFlagTest : public quiche::test::QuicheTestWithParam<TestParams> { protected: Http2FrameHeaderTypeAndFlagTest() : type_(std::get<0>(GetParam())), flags_(std::get<1>(GetParam())) { QUICHE_LOG(INFO) << "Frame type: " << type_; QUICHE_LOG(INFO) << "Frame flags: " << Http2FrameFlagsToString(type_, flags_); } const Http2FrameType type_; const uint8_t flags_; }; class IsEndStreamTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsEndStream, IsEndStreamTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::END_STREAM, 0xff)), TestParamToString); TEST_P(IsEndStreamTest, IsEndStream) { const bool is_set = (flags_ & Http2FrameFlag::END_STREAM) == Http2FrameFlag::END_STREAM; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::DATA: case Http2FrameType::HEADERS: EXPECT_EQ(is_set, v.IsEndStream()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?END_STREAM\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("END_STREAM"))); } v.RetainFlags(Http2FrameFlag::END_STREAM); EXPECT_EQ(is_set, v.IsEndStream()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=END_STREAM,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsEndStream(), "DATA.*HEADERS"); } } class IsACKTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsAck, IsACKTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::ACK, 0xff)), TestParamToString); TEST_P(IsACKTest, IsAck) { const bool is_set = (flags_ & Http2FrameFlag::ACK) == Http2FrameFlag::ACK; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::SETTINGS: case Http2FrameType::PING: EXPECT_EQ(is_set, v.IsAck()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?ACK\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("ACK"))); } v.RetainFlags(Http2FrameFlag::ACK); EXPECT_EQ(is_set, v.IsAck()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=ACK,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsAck(), "SETTINGS.*PING"); } } class IsEndHeadersTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsEndHeaders, IsEndHeadersTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::END_HEADERS, 0xff)), TestParamToString); TEST_P(IsEndHeadersTest, IsEndHeaders) { const bool is_set = (flags_ & Http2FrameFlag::END_HEADERS) == Http2FrameFlag::END_HEADERS; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::HEADERS: case Http2FrameType::PUSH_PROMISE: case Http2FrameType::CONTINUATION: EXPECT_EQ(is_set, v.IsEndHeaders()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?END_HEADERS\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("END_HEADERS"))); } v.RetainFlags(Http2FrameFlag::END_HEADERS); EXPECT_EQ(is_set, v.IsEndHeaders()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=END_HEADERS,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsEndHeaders(), "HEADERS.*PUSH_PROMISE.*CONTINUATION"); } } class IsPaddedTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsPadded, IsPaddedTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::PADDED, 0xff)), TestParamToString); TEST_P(IsPaddedTest, IsPadded) { const bool is_set = (flags_ & Http2FrameFlag::PADDED) == Http2FrameFlag::PADDED; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::DATA: case Http2FrameType::HEADERS: case Http2FrameType::PUSH_PROMISE: EXPECT_EQ(is_set, v.IsPadded()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?PADDED\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("PADDED"))); } v.RetainFlags(Http2FrameFlag::PADDED); EXPECT_EQ(is_set, v.IsPadded()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=PADDED,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsPadded(), "DATA.*HEADERS.*PUSH_PROMISE"); } } class HasPriorityTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(HasPriority, HasPriorityTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::PRIORITY, 0xff)), TestParamToString); TEST_P(HasPriorityTest, HasPriority) { const bool is_set = (flags_ & Http2FrameFlag::PRIORITY) == Http2FrameFlag::PRIORITY; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::HEADERS: EXPECT_EQ(is_set, v.HasPriority()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?PRIORITY\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("PRIORITY"))); } v.RetainFlags(Http2FrameFlag::PRIORITY); EXPECT_EQ(is_set, v.HasPriority()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=PRIORITY,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.HasPriority(), "HEADERS"); } } TEST(Http2PriorityFieldsTest, Constructor) { Http2Random random; uint32_t stream_dependency = random.Rand32() & StreamIdMask(); uint32_t weight = 1 + random.Rand8(); bool is_exclusive = random.OneIn(2); Http2PriorityFields v(stream_dependency, weight, is_exclusive); EXPECT_EQ(stream_dependency, v.stream_dependency); EXPECT_EQ(weight, v.weight); EXPECT_EQ(is_exclusive, v.is_exclusive); EXPECT_QUICHE_DEBUG_DEATH( Http2PriorityFields(stream_dependency | 0x80000000, weight, is_exclusive), "31-bit"); EXPECT_QUICHE_DEBUG_DEATH( Http2PriorityFields(stream_dependency, 0, is_exclusive), "too small"); EXPECT_QUICHE_DEBUG_DEATH( Http2PriorityFields(stream_dependency, weight + 256, is_exclusive), "too large"); EXPECT_TRUE(VerifyRandomCalls<Http2PriorityFields>()); } #endif TEST(Http2RstStreamFieldsTest, IsSupported) { Http2RstStreamFields v{Http2ErrorCode::HTTP2_NO_ERROR}; EXPECT_TRUE(v.IsSupportedErrorCode()) << v; Http2RstStreamFields u{static_cast<Http2ErrorCode>(~0)}; EXPECT_FALSE(u.IsSupportedErrorCode()) << v; EXPECT_TRUE(VerifyRandomCalls<Http2RstStreamFields>()); } TEST(Http2SettingFieldsTest, Misc) { Http2Random random; Http2SettingsParameter parameter = static_cast<Http2SettingsParameter>(random.Rand16()); uint32_t value = random.Rand32(); Http2SettingFields v(parameter, value); EXPECT_EQ(v, v); EXPECT_EQ(parameter, v.parameter); EXPECT_EQ(value, v.value); if (static_cast<uint16_t>(parameter) < 7) { EXPECT_TRUE(v.IsSupportedParameter()) << v; } else { EXPECT_FALSE(v.IsSupportedParameter()) << v; } Http2SettingFields u(parameter, ~value); EXPECT_NE(v, u); EXPECT_EQ(v.parameter, u.parameter); EXPECT_NE(v.value, u.value); Http2SettingFields w(IncrementEnum(parameter), value); EXPECT_NE(v, w); EXPECT_NE(v.parameter, w.parameter); EXPECT_EQ(v.value, w.value); Http2SettingFields x(Http2SettingsParameter::MAX_FRAME_SIZE, 123); std::stringstream s; s << x; EXPECT_EQ("parameter=MAX_FRAME_SIZE, value=123", s.str()); EXPECT_TRUE(VerifyRandomCalls<Http2SettingFields>()); } TEST(Http2PushPromiseTest, Misc) { Http2Random random; uint32_t promised_stream_id = random.Rand32() & StreamIdMask(); Http2PushPromiseFields v{promised_stream_id}; EXPECT_EQ(promised_stream_id, v.promised_stream_id); EXPECT_EQ(v, v); std::stringstream s; s << v; EXPECT_EQ(absl::StrCat("promised_stream_id=", promised_stream_id), s.str()); promised_stream_id |= 0x80000000; Http2PushPromiseFields w{promised_stream_id}; EXPECT_EQ(w, w); EXPECT_NE(v, w); v.promised_stream_id = promised_stream_id; EXPECT_EQ(v, w); EXPECT_TRUE(VerifyRandomCalls<Http2PushPromiseFields>()); } TEST(Http2PingFieldsTest, Misc) { Http2PingFields v{{'8', ' ', 'b', 'y', 't', 'e', 's', '\0'}}; std::stringstream s; s << v; EXPECT_EQ("opaque_bytes=0x3820627974657300", s.str()); EXPECT_TRUE(VerifyRandomCalls<Http2PingFields>()); } TEST(Http2GoAwayFieldsTest, Misc) { Http2Random random; uint32_t last_stream_id = random.Rand32() & StreamIdMask(); Http2ErrorCode error_code = static_cast<Http2ErrorCode>(random.Rand32()); Http2GoAwayFields v(last_stream_id, error_code); EXPECT_EQ(v, v); EXPECT_EQ(last_stream_id, v.last_stream_id); EXPECT_EQ(error_code, v.error_code); if (static_cast<uint32_t>(error_code) < 14) { EXPECT_TRUE(v.IsSupportedErrorCode()) << v; } else { EXPECT_FALSE(v.IsSupportedErrorCode()) << v; } Http2GoAwayFields u(~last_stream_id, error_code); EXPECT_NE(v, u); EXPECT_NE(v.last_stream_id, u.last_stream_id); EXPECT_EQ(v.error_code, u.error_code); EXPECT_TRUE(VerifyRandomCalls<Http2GoAwayFields>()); } TEST(Http2WindowUpdateTest, Misc) { Http2Random random; uint32_t window_size_increment = random.Rand32() & UInt31Mask(); Http2WindowUpdateFields v{window_size_increment}; EXPECT_EQ(window_size_increment, v.window_size_increment); EXPECT_EQ(v, v); std::stringstream s; s << v; EXPECT_EQ(absl::StrCat("window_size_increment=", window_size_increment), s.str()); window_size_increment |= 0x80000000; Http2WindowUpdateFields w{window_size_increment}; EXPECT_EQ(w, w); EXPECT_NE(v, w); v.window_size_increment = window_size_increment; EXPECT_EQ(v, w); EXPECT_TRUE(VerifyRandomCalls<Http2WindowUpdateFields>()); } TEST(Http2AltSvcTest, Misc) { Http2Random random; uint16_t origin_length = random.Rand16(); Http2AltSvcFields v{origin_length}; EXPECT_EQ(origin_length, v.origin_length); EXPECT_EQ(v, v); std::stringstream s; s << v; EXPECT_EQ(absl::StrCat("origin_length=", origin_length), s.str()); Http2AltSvcFields w{++origin_length}; EXPECT_EQ(w, w); EXPECT_NE(v, w); v.origin_length = w.origin_length; EXPECT_EQ(v, w); EXPECT_TRUE(VerifyRandomCalls<Http2AltSvcFields>()); } TEST(Http2PriorityUpdateFieldsTest, Eq) { Http2PriorityUpdateFields u( 1); Http2PriorityUpdateFields v( 3); EXPECT_NE(u, v); EXPECT_FALSE(u == v); EXPECT_TRUE(u != v); u = v; EXPECT_EQ(u, v); EXPECT_TRUE(u == v); EXPECT_FALSE(u != v); } TEST(Http2PriorityUpdateFieldsTest, Misc) { Http2PriorityUpdateFields u( 1); EXPECT_EQ("prioritized_stream_id=1", u.ToString()); EXPECT_TRUE(VerifyRandomCalls<Http2PriorityUpdateFields>()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/http2_structures.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/http2_structures_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
7d65e279-385d-403d-ae70-cdd9bebf5336
cpp
google/quiche
spdy_framer
quiche/http2/core/spdy_framer.cc
quiche/http2/core/spdy_framer_test.cc
#include "quiche/http2/core/spdy_framer.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/memory/memory.h" #include "quiche/http2/core/spdy_alt_svc_wire_format.h" #include "quiche/http2/core/spdy_frame_builder.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/core/zero_copy_output_buffer.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_encoder.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { namespace { uint32_t PackStreamDependencyValues(bool exclusive, SpdyStreamId parent_stream_id) { uint32_t parent = parent_stream_id & 0x7fffffff; uint32_t e_bit = exclusive ? 0x80000000 : 0; return parent | e_bit; } const uint8_t kNoFlags = 0; const size_t kPadLengthFieldSize = 1; const size_t kOneSettingParameterSize = 6; size_t GetUncompressedSerializedLength(const quiche::HttpHeaderBlock& headers) { const size_t num_name_value_pairs_size = sizeof(uint32_t); const size_t length_of_name_size = num_name_value_pairs_size; const size_t length_of_value_size = num_name_value_pairs_size; size_t total_length = num_name_value_pairs_size; for (const auto& header : headers) { total_length += length_of_name_size + header.first.size() + length_of_value_size + header.second.size(); } return total_length; } uint8_t SerializeHeaderFrameFlags(const SpdyHeadersIR& header_ir, const bool end_headers) { uint8_t flags = 0; if (header_ir.fin()) { flags |= CONTROL_FLAG_FIN; } if (end_headers) { flags |= HEADERS_FLAG_END_HEADERS; } if (header_ir.padded()) { flags |= HEADERS_FLAG_PADDED; } if (header_ir.has_priority()) { flags |= HEADERS_FLAG_PRIORITY; } return flags; } uint8_t SerializePushPromiseFrameFlags(const SpdyPushPromiseIR& push_promise_ir, const bool end_headers) { uint8_t flags = 0; if (push_promise_ir.padded()) { flags = flags | PUSH_PROMISE_FLAG_PADDED; } if (end_headers) { flags |= PUSH_PROMISE_FLAG_END_PUSH_PROMISE; } return flags; } bool SerializeHeadersGivenEncoding(const SpdyHeadersIR& headers, const std::string& encoding, const bool end_headers, ZeroCopyOutputBuffer* output) { const size_t frame_size = GetHeaderFrameSizeSansBlock(headers) + encoding.size(); SpdyFrameBuilder builder(frame_size, output); bool ret = builder.BeginNewFrame( SpdyFrameType::HEADERS, SerializeHeaderFrameFlags(headers, end_headers), headers.stream_id(), frame_size - kFrameHeaderSize); QUICHE_DCHECK_EQ(kFrameHeaderSize, builder.length()); if (ret && headers.padded()) { ret &= builder.WriteUInt8(headers.padding_payload_len()); } if (ret && headers.has_priority()) { int weight = ClampHttp2Weight(headers.weight()); ret &= builder.WriteUInt32(PackStreamDependencyValues( headers.exclusive(), headers.parent_stream_id())); ret &= builder.WriteUInt8(weight - 1); } if (ret) { ret &= builder.WriteBytes(encoding.data(), encoding.size()); } if (ret && headers.padding_payload_len() > 0) { std::string padding(headers.padding_payload_len(), 0); ret &= builder.WriteBytes(padding.data(), padding.length()); } if (!ret) { QUICHE_DLOG(WARNING) << "Failed to build HEADERS. Not enough space in output"; } return ret; } bool SerializePushPromiseGivenEncoding(const SpdyPushPromiseIR& push_promise, const std::string& encoding, const bool end_headers, ZeroCopyOutputBuffer* output) { const size_t frame_size = GetPushPromiseFrameSizeSansBlock(push_promise) + encoding.size(); SpdyFrameBuilder builder(frame_size, output); bool ok = builder.BeginNewFrame( SpdyFrameType::PUSH_PROMISE, SerializePushPromiseFrameFlags(push_promise, end_headers), push_promise.stream_id(), frame_size - kFrameHeaderSize); if (push_promise.padded()) { ok = ok && builder.WriteUInt8(push_promise.padding_payload_len()); } ok = ok && builder.WriteUInt32(push_promise.promised_stream_id()) && builder.WriteBytes(encoding.data(), encoding.size()); if (ok && push_promise.padding_payload_len() > 0) { std::string padding(push_promise.padding_payload_len(), 0); ok = builder.WriteBytes(padding.data(), padding.length()); } QUICHE_DLOG_IF(ERROR, !ok) << "Failed to write PUSH_PROMISE encoding, not enough " << "space in output"; return ok; } bool WritePayloadWithContinuation(SpdyFrameBuilder* builder, const std::string& hpack_encoding, SpdyStreamId stream_id, SpdyFrameType type, int padding_payload_len) { uint8_t end_flag = 0; uint8_t flags = 0; if (type == SpdyFrameType::HEADERS) { end_flag = HEADERS_FLAG_END_HEADERS; } else if (type == SpdyFrameType::PUSH_PROMISE) { end_flag = PUSH_PROMISE_FLAG_END_PUSH_PROMISE; } else { QUICHE_DLOG(FATAL) << "CONTINUATION frames cannot be used with frame type " << FrameTypeToString(type); } size_t bytes_remaining = 0; bytes_remaining = hpack_encoding.size() - std::min(hpack_encoding.size(), kHttp2MaxControlFrameSendSize - builder->length() - padding_payload_len); bool ret = builder->WriteBytes(&hpack_encoding[0], hpack_encoding.size() - bytes_remaining); if (padding_payload_len > 0) { std::string padding = std::string(padding_payload_len, 0); ret &= builder->WriteBytes(padding.data(), padding.length()); } while (bytes_remaining > 0 && ret) { size_t bytes_to_write = std::min(bytes_remaining, kHttp2MaxControlFrameSendSize - kContinuationFrameMinimumSize); if (bytes_remaining == bytes_to_write) { flags |= end_flag; } ret &= builder->BeginNewFrame(SpdyFrameType::CONTINUATION, flags, stream_id, bytes_to_write); ret &= builder->WriteBytes( &hpack_encoding[hpack_encoding.size() - bytes_remaining], bytes_to_write); bytes_remaining -= bytes_to_write; } return ret; } void SerializeDataBuilderHelper(const SpdyDataIR& data_ir, uint8_t* flags, int* num_padding_fields, size_t* size_with_padding) { if (data_ir.fin()) { *flags = DATA_FLAG_FIN; } if (data_ir.padded()) { *flags = *flags | DATA_FLAG_PADDED; ++*num_padding_fields; } *size_with_padding = *num_padding_fields + data_ir.data_len() + data_ir.padding_payload_len() + kDataFrameMinimumSize; } void SerializeDataFrameHeaderWithPaddingLengthFieldBuilderHelper( const SpdyDataIR& data_ir, uint8_t* flags, size_t* frame_size, size_t* num_padding_fields) { *flags = DATA_FLAG_NONE; if (data_ir.fin()) { *flags = DATA_FLAG_FIN; } *frame_size = kDataFrameMinimumSize; if (data_ir.padded()) { *flags = *flags | DATA_FLAG_PADDED; ++(*num_padding_fields); *frame_size = *frame_size + *num_padding_fields; } } void SerializeSettingsBuilderHelper(const SpdySettingsIR& settings, uint8_t* flags, const SettingsMap* values, size_t* size) { if (settings.is_ack()) { *flags = *flags | SETTINGS_FLAG_ACK; } *size = kSettingsFrameMinimumSize + (values->size() * kOneSettingParameterSize); } void SerializeAltSvcBuilderHelper(const SpdyAltSvcIR& altsvc_ir, std::string* value, size_t* size) { *size = kGetAltSvcFrameMinimumSize; *size = *size + altsvc_ir.origin().length(); *value = SpdyAltSvcWireFormat::SerializeHeaderFieldValue( altsvc_ir.altsvc_vector()); *size = *size + value->length(); } } SpdyFramer::SpdyFramer(CompressionOption option) : debug_visitor_(nullptr), compression_option_(option) { static_assert(kHttp2MaxControlFrameSendSize <= kHttp2DefaultFrameSizeLimit, "Our send limit should be at most our receive limit."); } SpdyFramer::~SpdyFramer() = default; void SpdyFramer::set_debug_visitor( SpdyFramerDebugVisitorInterface* debug_visitor) { debug_visitor_ = debug_visitor; } SpdyFramer::SpdyFrameIterator::SpdyFrameIterator(SpdyFramer* framer) : framer_(framer), is_first_frame_(true), has_next_frame_(true) {} SpdyFramer::SpdyFrameIterator::~SpdyFrameIterator() = default; size_t SpdyFramer::SpdyFrameIterator::NextFrame(ZeroCopyOutputBuffer* output) { const SpdyFrameIR* frame_ir = GetIR(); if (!has_next_frame_ || frame_ir == nullptr) { QUICHE_BUG(spdy_bug_75_1) << "SpdyFramer::SpdyFrameIterator::NextFrame called without " << "a next frame."; return false; } const size_t size_without_block = is_first_frame_ ? GetFrameSizeSansBlock() : kContinuationFrameMinimumSize; std::string encoding = encoder_->Next(kHttp2MaxControlFrameSendSize - size_without_block); has_next_frame_ = encoder_->HasNext(); if (framer_->debug_visitor_ != nullptr) { const auto& frame_ref = static_cast<const SpdyFrameWithHeaderBlockIR&>(*frame_ir); const size_t header_list_size = GetUncompressedSerializedLength(frame_ref.header_block()); framer_->debug_visitor_->OnSendCompressedFrame( frame_ref.stream_id(), is_first_frame_ ? frame_ref.frame_type() : SpdyFrameType::CONTINUATION, header_list_size, size_without_block + encoding.size()); } const size_t free_bytes_before = output->BytesFree(); bool ok = false; if (is_first_frame_) { is_first_frame_ = false; ok = SerializeGivenEncoding(encoding, output); } else { SpdyContinuationIR continuation_ir(frame_ir->stream_id()); continuation_ir.take_encoding(std::move(encoding)); continuation_ir.set_end_headers(!has_next_frame_); ok = framer_->SerializeContinuation(continuation_ir, output); } return ok ? free_bytes_before - output->BytesFree() : 0; } bool SpdyFramer::SpdyFrameIterator::HasNextFrame() const { return has_next_frame_; } SpdyFramer::SpdyHeaderFrameIterator::SpdyHeaderFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyHeadersIR> headers_ir) : SpdyFrameIterator(framer), headers_ir_(std::move(headers_ir)) { SetEncoder(headers_ir_.get()); } SpdyFramer::SpdyHeaderFrameIterator::~SpdyHeaderFrameIterator() = default; const SpdyFrameIR* SpdyFramer::SpdyHeaderFrameIterator::GetIR() const { return headers_ir_.get(); } size_t SpdyFramer::SpdyHeaderFrameIterator::GetFrameSizeSansBlock() const { return GetHeaderFrameSizeSansBlock(*headers_ir_); } bool SpdyFramer::SpdyHeaderFrameIterator::SerializeGivenEncoding( const std::string& encoding, ZeroCopyOutputBuffer* output) const { return SerializeHeadersGivenEncoding(*headers_ir_, encoding, !has_next_frame(), output); } SpdyFramer::SpdyPushPromiseFrameIterator::SpdyPushPromiseFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyPushPromiseIR> push_promise_ir) : SpdyFrameIterator(framer), push_promise_ir_(std::move(push_promise_ir)) { SetEncoder(push_promise_ir_.get()); } SpdyFramer::SpdyPushPromiseFrameIterator::~SpdyPushPromiseFrameIterator() = default; const SpdyFrameIR* SpdyFramer::SpdyPushPromiseFrameIterator::GetIR() const { return push_promise_ir_.get(); } size_t SpdyFramer::SpdyPushPromiseFrameIterator::GetFrameSizeSansBlock() const { return GetPushPromiseFrameSizeSansBlock(*push_promise_ir_); } bool SpdyFramer::SpdyPushPromiseFrameIterator::SerializeGivenEncoding( const std::string& encoding, ZeroCopyOutputBuffer* output) const { return SerializePushPromiseGivenEncoding(*push_promise_ir_, encoding, !has_next_frame(), output); } SpdyFramer::SpdyControlFrameIterator::SpdyControlFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyFrameIR> frame_ir) : framer_(framer), frame_ir_(std::move(frame_ir)) {} SpdyFramer::SpdyControlFrameIterator::~SpdyControlFrameIterator() = default; size_t SpdyFramer::SpdyControlFrameIterator::NextFrame( ZeroCopyOutputBuffer* output) { size_t size_written = framer_->SerializeFrame(*frame_ir_, output); has_next_frame_ = false; return size_written; } bool SpdyFramer::SpdyControlFrameIterator::HasNextFrame() const { return has_next_frame_; } const SpdyFrameIR* SpdyFramer::SpdyControlFrameIterator::GetIR() const { return frame_ir_.get(); } std::unique_ptr<SpdyFrameSequence> SpdyFramer::CreateIterator( SpdyFramer* framer, std::unique_ptr<const SpdyFrameIR> frame_ir) { switch (frame_ir->frame_type()) { case SpdyFrameType::HEADERS: { return std::make_unique<SpdyHeaderFrameIterator>( framer, absl::WrapUnique( static_cast<const SpdyHeadersIR*>(frame_ir.release()))); } case SpdyFrameType::PUSH_PROMISE: { return std::make_unique<SpdyPushPromiseFrameIterator>( framer, absl::WrapUnique(static_cast<const SpdyPushPromiseIR*>( frame_ir.release()))); } case SpdyFrameType::DATA: { QUICHE_DVLOG(1) << "Serialize a stream end DATA frame for VTL"; ABSL_FALLTHROUGH_INTENDED; } default: { return std::make_unique<SpdyControlFrameIterator>(framer, std::move(frame_ir)); } } } SpdySerializedFrame SpdyFramer::SerializeData(const SpdyDataIR& data_ir) { uint8_t flags = DATA_FLAG_NONE; int num_padding_fields = 0; size_t size_with_padding = 0; SerializeDataBuilderHelper(data_ir, &flags, &num_padding_fields, &size_with_padding); SpdyFrameBuilder builder(size_with_padding); builder.BeginNewFrame(SpdyFrameType::DATA, flags, data_ir.stream_id()); if (data_ir.padded()) { builder.WriteUInt8(data_ir.padding_payload_len() & 0xff); } builder.WriteBytes(data_ir.data(), data_ir.data_len()); if (data_ir.padding_payload_len() > 0) { std::string padding(data_ir.padding_payload_len(), 0); builder.WriteBytes(padding.data(), padding.length()); } QUICHE_DCHECK_EQ(size_with_padding, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeDataFrameHeaderWithPaddingLengthField( const SpdyDataIR& data_ir) { uint8_t flags = DATA_FLAG_NONE; size_t frame_size = 0; size_t num_padding_fields = 0; SerializeDataFrameHeaderWithPaddingLengthFieldBuilderHelper( data_ir, &flags, &frame_size, &num_padding_fields); SpdyFrameBuilder builder(frame_size); builder.BeginNewFrame( SpdyFrameType::DATA, flags, data_ir.stream_id(), num_padding_fields + data_ir.data_len() + data_ir.padding_payload_len()); if (data_ir.padded()) { builder.WriteUInt8(data_ir.padding_payload_len() & 0xff); } QUICHE_DCHECK_EQ(frame_size, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeRstStream( const SpdyRstStreamIR& rst_stream) const { size_t expected_length = kRstStreamFrameSize; SpdyFrameBuilder builder(expected_length); builder.BeginNewFrame(SpdyFrameType::RST_STREAM, 0, rst_stream.stream_id()); builder.WriteUInt32(rst_stream.error_code()); QUICHE_DCHECK_EQ(expected_length, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeSettings( const SpdySettingsIR& settings) const { uint8_t flags = 0; size_t size = 0; const SettingsMap* values = &(settings.values()); SerializeSettingsBuilderHelper(settings, &flags, values, &size); SpdyFrameBuilder builder(size); builder.BeginNewFrame(SpdyFrameType::SETTINGS, flags, 0); if (settings.is_ack()) { return builder.take(); } QUICHE_DCHECK_EQ(kSettingsFrameMinimumSize, builder.length()); for (auto it = values->begin(); it != values->end(); ++it) { int setting_id = it->first; QUICHE_DCHECK_GE(setting_id, 0); builder.WriteUInt16(static_cast<SpdySettingsId>(setting_id)); builder.WriteUInt32(it->second); } QUICHE_DCHECK_EQ(size, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializePing(const SpdyPingIR& ping) const { SpdyFrameBuilder builder(kPingFrameSize); uint8_t flags = 0; if (ping.is_ack()) { flags |= PING_FLAG_ACK; } builder.BeginNewFrame(SpdyFrameType::PING, flags, 0); builder.WriteUInt64(ping.id()); QUICHE_DCHECK_EQ(kPingFrameSize, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeGoAway( const SpdyGoAwayIR& goaway) const { size_t expected_length = kGoawayFrameMinimumSize; expected_length += goaway.description().size(); SpdyFrameBuilder builder(expected_length); builder.BeginNewFrame(SpdyFrameType::GOAWAY, 0, 0); builder.WriteUInt32(goaway.last_good_stream_id()); builder.WriteUInt32(goaway.error_code()); if (!goaway.description().empty()) { builder.WriteBytes(goaway.description().data(), goaway.description().size()); } QUICHE_DCHECK_EQ(expected_length, builder.length()); return builder.take(); } void SpdyFramer::SerializeHeadersBuilderHelper(const SpdyHeadersIR& headers, uint8_t* flags, size_t* size, std::string* hpack_encoding, int* weight, size_t* length_field) { if (headers.fin()) { *flags = *flags | CONTROL_FLAG_FIN; } *flags = *flags | HEADERS_FLAG_END_HEADERS; if (headers.has_priority()) { *flags = *flags | HEADERS_FLAG_PRIORITY; } if (headers.padded()) { *flags = *flags | HEADERS_FLAG_PADDED; } *size = kHeadersFrameMinimumSize; if (headers.padded()) { *size = *size + kPadLengthFieldSize; *size = *size + headers.padding_payload_len(); } if (headers.has_priority()) { *weight = ClampHttp2Weight(headers.weight()); *size = *size + 5; } *hpack_encoding = GetHpackEncoder()->EncodeHeaderBlock(headers.header_block()); *size = *size + hpack_encoding->size(); if (*size > kHttp2MaxControlFrameSendSize) { *size = *size + GetNumberRequiredContinuationFrames(*size) * kContinuationFrameMinimumSize; *flags = *flags & ~HEADERS_FLAG_END_HEADERS; } if (headers.padded()) { *length_field = *length_field + kPadLengthFieldSize; } if (headers.has_priority()) { *length_field = *length_field + 4; *length_field = *length_field + 1; } *length_field = *length_field + headers.padding_payload_len(); *length_field = *length_field + hpack_encoding->size(); *length_field = std::min(*length_field, kHttp2MaxControlFrameSendSize - kFrameHeaderSize); } SpdySerializedFrame SpdyFramer::SerializeHeaders(const SpdyHeadersIR& headers) { uint8_t flags = 0; size_t size = 0; std::string hpack_encoding; int weight = 0; size_t length_field = 0; SerializeHeadersBuilderHelper(headers, &flags, &size, &hpack_encoding, &weight, &length_field); SpdyFrameBuilder builder(size); builder.BeginNewFrame(SpdyFrameType::HEADERS, flags, headers.stream_id(), length_field); QUICHE_DCHECK_EQ(kHeadersFrameMinimumSize, builder.length()); int padding_payload_len = 0; if (headers.padded()) { builder.WriteUInt8(headers.padding_payload_len()); padding_payload_len = headers.padding_payload_len(); } if (headers.has_priority()) { builder.WriteUInt32(PackStreamDependencyValues(headers.exclusive(), headers.parent_stream_id())); builder.WriteUInt8(weight - 1); } WritePayloadWithContinuation(&builder, hpack_encoding, headers.stream_id(), SpdyFrameType::HEADERS, padding_payload_len); if (debug_visitor_) { const size_t header_list_size = GetUncompressedSerializedLength(headers.header_block()); debug_visitor_->OnSendCompressedFrame(headers.stream_id(), SpdyFrameType::HEADERS, header_list_size, builder.length()); } return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeWindowUpdate( const SpdyWindowUpdateIR& window_update) { SpdyFrameBuilder builder(kWindowUpdateFrameSize); builder.BeginNewFrame(SpdyFrameType::WINDOW_UPDATE, kNoFlags, window_update.stream_id()); builder.WriteUInt32(window_update.delta()); QUICHE_DCHECK_EQ(kWindowUpdateFrameSize, builder.length()); return builder.take(); } void SpdyFramer::SerializePushPromiseBuilderHelper( const SpdyPushPromiseIR& push_promise, uint8_t* flags, std::string* hpack_encoding, size_t* size) { *flags = 0; *flags = *flags | PUSH_PROMISE_FLAG_END_PUSH_PROMISE; *size = kPushPromiseFrameMinimumSize; if (push_promise.padded()) { *flags = *flags | PUSH_PROMISE_FLAG_PADDED; *size = *size + kPadLengthFieldSize; *size = *size + push_promise.padding_payload_len(); } *hpack_encoding = GetHpackEncoder()->EncodeHeaderBlock(push_promise.header_block()); *size = *size + hpack_encoding->size(); if (*size > kHttp2MaxControlFrameSendSize) { *size = *size + GetNumberRequiredContinuationFrames(*size) * kContinuationFrameMinimumSize; *flags = *flags & ~PUSH_PROMISE_FLAG_END_PUSH_PROMISE; } } SpdySerializedFrame SpdyFramer::SerializePushPromise( const SpdyPushPromiseIR& push_promise) { uint8_t flags = 0; size_t size = 0; std::string hpack_encoding; SerializePushPromiseBuilderHelper(push_promise, &flags, &hpack_encoding, &size); SpdyFrameBuilder builder(size); size_t length = std::min(size, kHttp2MaxControlFrameSendSize) - kFrameHeaderSize; builder.BeginNewFrame(SpdyFrameType::PUSH_PROMISE, flags, push_promise.stream_id(), length); int padding_payload_len = 0; if (push_promise.padded()) { builder.WriteUInt8(push_promise.padding_payload_len()); builder.WriteUInt32(push_promise.promised_stream_id()); QUICHE_DCHECK_EQ(kPushPromiseFrameMinimumSize + kPadLengthFieldSize, builder.length()); padding_payload_len = push_promise.padding_payload_len(); } else { builder.WriteUInt32(push_promise.promised_stream_id()); QUICHE_DCHECK_EQ(kPushPromiseFrameMinimumSize, builder.length()); } WritePayloadWithContinuation( &builder, hpack_encoding, push_promise.stream_id(), SpdyFrameType::PUSH_PROMISE, padding_payload_len); if (debug_visitor_) { const size_t header_list_size = GetUncompressedSerializedLength(push_promise.header_block()); debug_visitor_->OnSendCompressedFrame(push_promise.stream_id(), SpdyFrameType::PUSH_PROMISE, header_list_size, builder.length()); } return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeContinuation( const SpdyContinuationIR& continuation) const { const std::string& encoding = continuation.encoding(); size_t frame_size = kContinuationFrameMinimumSize + encoding.size(); SpdyFrameBuilder builder(frame_size); uint8_t flags = continuation.end_headers() ? HEADERS_FLAG_END_HEADERS : 0; builder.BeginNewFrame(SpdyFrameType::CONTINUATION, flags, continuation.stream_id()); QUICHE_DCHECK_EQ(kFrameHeaderSize, builder.length()); builder.WriteBytes(encoding.data(), encoding.size()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeAltSvc(const SpdyAltSvcIR& altsvc_ir) { std::string value; size_t size = 0; SerializeAltSvcBuilderHelper(altsvc_ir, &value, &size); SpdyFrameBuilder builder(size); builder.BeginNewFrame(SpdyFrameType::ALTSVC, kNoFlags, altsvc_ir.stream_id()); builder.WriteUInt16(altsvc_ir.origin().length()); builder.WriteBytes(altsvc_ir.origin().data(), altsvc_ir.origin().length()); builder.WriteBytes(value.data(), value.length()); QUICHE_DCHECK_LT(kGetAltSvcFrameMinimumSize, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializePriority( const SpdyPriorityIR& priority) const { SpdyFrameBuilder builder(kPriorityFrameSize); builder.BeginNewFrame(SpdyFrameType::PRIORITY, kNoFlags, priority.stream_id()); builder.WriteUInt32(PackStreamDependencyValues(priority.exclusive(), priority.parent_stream_id())); builder.WriteUInt8(priority.weight() - 1); QUICHE_DCHECK_EQ(kPriorityFrameSize, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializePriorityUpdate( const SpdyPriorityUpdateIR& priority_update) const { const size_t total_size = kPriorityUpdateFrameMinimumSize + priority_update.priority_field_value().size(); SpdyFrameBuilder builder(total_size); builder.BeginNewFrame(SpdyFrameType::PRIORITY_UPDATE, kNoFlags, priority_update.stream_id()); builder.WriteUInt32(priority_update.prioritized_stream_id()); builder.WriteBytes(priority_update.priority_field_value().data(), priority_update.priority_field_value().size()); QUICHE_DCHECK_EQ(total_size, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeAcceptCh( const SpdyAcceptChIR& accept_ch) const { const size_t total_size = accept_ch.size(); SpdyFrameBuilder builder(total_size); builder.BeginNewFrame(SpdyFrameType::ACCEPT_CH, kNoFlags, accept_ch.stream_id()); for (const AcceptChOriginValuePair& entry : accept_ch.entries()) { builder.WriteUInt16(entry.origin.size()); builder.WriteBytes(entry.origin.data(), entry.origin.size()); builder.WriteUInt16(entry.value.size()); builder.WriteBytes(entry.value.data(), entry.value.size()); } QUICHE_DCHECK_EQ(total_size, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeUnknown( const SpdyUnknownIR& unknown) const { const size_t total_size = kFrameHeaderSize + unknown.payload().size(); SpdyFrameBuilder builder(total_size); builder.BeginNewUncheckedFrame(unknown.type(), unknown.flags(), unknown.stream_id(), unknown.length()); builder.WriteBytes(unknown.payload().data(), unknown.payload().size()); return builder.take(); } namespace { class FrameSerializationVisitor : public SpdyFrameVisitor { public: explicit FrameSerializationVisitor(SpdyFramer* framer) : framer_(framer), frame_() {} ~FrameSerializationVisitor() override = default; SpdySerializedFrame ReleaseSerializedFrame() { return std::move(frame_); } void VisitData(const SpdyDataIR& data) override { frame_ = framer_->SerializeData(data); } void VisitRstStream(const SpdyRstStreamIR& rst_stream) override { frame_ = framer_->SerializeRstStream(rst_stream); } void VisitSettings(const SpdySettingsIR& settings) override { frame_ = framer_->SerializeSettings(settings); } void VisitPing(const SpdyPingIR& ping) override { frame_ = framer_->SerializePing(ping); } void VisitGoAway(const SpdyGoAwayIR& goaway) override { frame_ = framer_->SerializeGoAway(goaway); } void VisitHeaders(const SpdyHeadersIR& headers) override { frame_ = framer_->SerializeHeaders(headers); } void VisitWindowUpdate(const SpdyWindowUpdateIR& window_update) override { frame_ = framer_->SerializeWindowUpdate(window_update); } void VisitPushPromise(const SpdyPushPromiseIR& push_promise) override { frame_ = framer_->SerializePushPromise(push_promise); } void VisitContinuation(const SpdyContinuationIR& continuation) override { frame_ = framer_->SerializeContinuation(continuation); } void VisitAltSvc(const SpdyAltSvcIR& altsvc) override { frame_ = framer_->SerializeAltSvc(altsvc); } void VisitPriority(const SpdyPriorityIR& priority) override { frame_ = framer_->SerializePriority(priority); } void VisitPriorityUpdate( const SpdyPriorityUpdateIR& priority_update) override { frame_ = framer_->SerializePriorityUpdate(priority_update); } void VisitAcceptCh(const SpdyAcceptChIR& accept_ch) override { frame_ = framer_->SerializeAcceptCh(accept_ch); } void VisitUnknown(const SpdyUnknownIR& unknown) override { frame_ = framer_->SerializeUnknown(unknown); } private: SpdyFramer* framer_; SpdySerializedFrame frame_; }; class FlagsSerializationVisitor : public SpdyFrameVisitor { public: void VisitData(const SpdyDataIR& data) override { flags_ = DATA_FLAG_NONE; if (data.fin()) { flags_ |= DATA_FLAG_FIN; } if (data.padded()) { flags_ |= DATA_FLAG_PADDED; } } void VisitRstStream(const SpdyRstStreamIR& ) override { flags_ = kNoFlags; } void VisitSettings(const SpdySettingsIR& settings) override { flags_ = kNoFlags; if (settings.is_ack()) { flags_ |= SETTINGS_FLAG_ACK; } } void VisitPing(const SpdyPingIR& ping) override { flags_ = kNoFlags; if (ping.is_ack()) { flags_ |= PING_FLAG_ACK; } } void VisitGoAway(const SpdyGoAwayIR& ) override { flags_ = kNoFlags; } void VisitHeaders(const SpdyHeadersIR& headers) override { flags_ = HEADERS_FLAG_END_HEADERS; if (headers.fin()) { flags_ |= CONTROL_FLAG_FIN; } if (headers.padded()) { flags_ |= HEADERS_FLAG_PADDED; } if (headers.has_priority()) { flags_ |= HEADERS_FLAG_PRIORITY; } } void VisitWindowUpdate(const SpdyWindowUpdateIR& ) override { flags_ = kNoFlags; } void VisitPushPromise(const SpdyPushPromiseIR& push_promise) override { flags_ = PUSH_PROMISE_FLAG_END_PUSH_PROMISE; if (push_promise.padded()) { flags_ |= PUSH_PROMISE_FLAG_PADDED; } } void VisitContinuation(const SpdyContinuationIR& ) override { flags_ = HEADERS_FLAG_END_HEADERS; } void VisitAltSvc(const SpdyAltSvcIR& ) override { flags_ = kNoFlags; } void VisitPriority(const SpdyPriorityIR& ) override { flags_ = kNoFlags; } void VisitPriorityUpdate( const SpdyPriorityUpdateIR& ) override { flags_ = kNoFlags; } void VisitAcceptCh(const SpdyAcceptChIR& ) override { flags_ = kNoFlags; } uint8_t flags() const { return flags_; } private: uint8_t flags_ = kNoFlags; }; } SpdySerializedFrame SpdyFramer::SerializeFrame(const SpdyFrameIR& frame) { FrameSerializationVisitor visitor(this); frame.Visit(&visitor); return visitor.ReleaseSerializedFrame(); } uint8_t SpdyFramer::GetSerializedFlags(const SpdyFrameIR& frame) { FlagsSerializationVisitor visitor; frame.Visit(&visitor); return visitor.flags(); } bool SpdyFramer::SerializeData(const SpdyDataIR& data_ir, ZeroCopyOutputBuffer* output) const { uint8_t flags = DATA_FLAG_NONE; int num_padding_fields = 0; size_t size_with_padding = 0; SerializeDataBuilderHelper(data_ir, &flags, &num_padding_fields, &size_with_padding); SpdyFrameBuilder builder(size_with_padding, output); bool ok = builder.BeginNewFrame(SpdyFrameType::DATA, flags, data_ir.stream_id()); if (data_ir.padded()) { ok = ok && builder.WriteUInt8(data_ir.padding_payload_len() & 0xff); } ok = ok && builder.WriteBytes(data_ir.data(), data_ir.data_len()); if (data_ir.padding_payload_len() > 0) { std::string padding; padding = std::string(data_ir.padding_payload_len(), 0); ok = ok && builder.WriteBytes(padding.data(), padding.length()); } QUICHE_DCHECK_EQ(size_with_padding, builder.length()); return ok; } bool SpdyFramer::SerializeDataFrameHeaderWithPaddingLengthField( const SpdyDataIR& data_ir, ZeroCopyOutputBuffer* output) const { uint8_t flags = DATA_FLAG_NONE; size_t frame_size = 0; size_t num_padding_fields = 0; SerializeDataFrameHeaderWithPaddingLengthFieldBuilderHelper( data_ir, &flags, &frame_size, &num_padding_fields); SpdyFrameBuilder builder(frame_size, output); bool ok = true; ok = ok && builder.BeginNewFrame(SpdyFrameType::DATA, flags, data_ir.stream_id(), num_padding_fields + data_ir.data_len() + data_ir.padding_payload_len()); if (data_ir.padded()) { ok = ok && builder.WriteUInt8(data_ir.padding_payload_len() & 0xff); } QUICHE_DCHECK_EQ(frame_size, builder.length()); return ok; } bool SpdyFramer::SerializeRstStream(const SpdyRstStreamIR& rst_stream, ZeroCopyOutputBuffer* output) const { size_t expected_length = kRstStreamFrameSize; SpdyFrameBuilder builder(expected_length, output); bool ok = builder.BeginNewFrame(SpdyFrameType::RST_STREAM, 0, rst_stream.stream_id()); ok = ok && builder.WriteUInt32(rst_stream.error_code()); QUICHE_DCHECK_EQ(expected_length, builder.length()); return ok; } bool SpdyFramer::SerializeSettings(const SpdySettingsIR& settings, ZeroCopyOutputBuffer* output) const { uint8_t flags = 0; size_t size = 0; const SettingsMap* values = &(settings.values()); SerializeSettingsBuilderHelper(settings, &flags, values, &size); SpdyFrameBuilder builder(size, output); bool ok = builder.BeginNewFrame(SpdyFrameType::SETTINGS, flags, 0); if (settings.is_ack()) { return ok; } QUICHE_DCHECK_EQ(kSettingsFrameMinimumSize, builder.length()); for (auto it = values->begin(); it != values->end(); ++it) { int setting_id = it->first; QUICHE_DCHECK_GE(setting_id, 0); ok = ok && builder.WriteUInt16(static_cast<SpdySettingsId>(setting_id)) && builder.WriteUInt32(it->second); } QUICHE_DCHECK_EQ(size, builder.length()); return ok; } bool SpdyFramer::SerializePing(const SpdyPingIR& ping, ZeroCopyOutputBuffer* output) const { SpdyFrameBuilder builder(kPingFrameSize, output); uint8_t flags = 0; if (ping.is_ack()) { flags |= PING_FLAG_ACK; } bool ok = builder.BeginNewFrame(SpdyFrameType::PING, flags, 0); ok = ok && builder.WriteUInt64(ping.id()); QUICHE_DCHECK_EQ(kPingFrameSize, builder.length()); return ok; } bool SpdyFramer::SerializeGoAway(const SpdyGoAwayIR& goaway, ZeroCopyOutputBuffer* output) const { size_t expected_length = kGoawayFrameMinimumSize; expected_length += goaway.description().size(); SpdyFrameBuilder builder(expected_length, output); bool ok = builder.BeginNewFrame(SpdyFrameType::GOAWAY, 0, 0); ok = ok && builder.WriteUInt32(goaway.last_good_stream_id()) && builder.WriteUInt32(goaway.error_code()); if (!goaway.description().empty()) { ok = ok && builder.WriteBytes(goaway.description().data(), goaway.description().size()); } QUICHE_DCHECK_EQ(expected_length, builder.length()); return ok; } bool SpdyFramer::SerializeHeaders(const SpdyHeadersIR& headers, ZeroCopyOutputBuffer* output) { uint8_t flags = 0; size_t size = 0; std::string hpack_encoding; int weight = 0; size_t length_field = 0; SerializeHeadersBuilderHelper(headers, &flags, &size, &hpack_encoding, &weight, &length_field); bool ok = true; SpdyFrameBuilder builder(size, output); ok = ok && builder.BeginNewFrame(SpdyFrameType::HEADERS, flags, headers.stream_id(), length_field); QUICHE_DCHECK_EQ(kHeadersFrameMinimumSize, builder.length()); int padding_payload_len = 0; if (headers.padded()) { ok = ok && builder.WriteUInt8(headers.padding_payload_len()); padding_payload_len = headers.padding_payload_len(); } if (headers.has_priority()) { ok = ok && builder.WriteUInt32(PackStreamDependencyValues( headers.exclusive(), headers.parent_stream_id())) && builder.WriteUInt8(weight - 1); } ok = ok && WritePayloadWithContinuation( &builder, hpack_encoding, headers.stream_id(), SpdyFrameType::HEADERS, padding_payload_len); if (debug_visitor_) { const size_t header_list_size = GetUncompressedSerializedLength(headers.header_block()); debug_visitor_->OnSendCompressedFrame(headers.stream_id(), SpdyFrameType::HEADERS, header_list_size, builder.length()); } return ok; } bool SpdyFramer::SerializeWindowUpdate(const SpdyWindowUpdateIR& window_update, ZeroCopyOutputBuffer* output) const { SpdyFrameBuilder builder(kWindowUpdateFrameSize, output); bool ok = builder.BeginNewFrame(SpdyFrameType::WINDOW_UPDATE, kNoFlags, window_update.stream_id()); ok = ok && builder.WriteUInt32(window_update.delta()); QUICHE_DCHECK_EQ(kWindowUpdateFrameSize, builder.length()); return ok; } bool SpdyFramer::SerializePushPromise(const SpdyPushPromiseIR& push_promise, ZeroCopyOutputBuffer* output) { uint8_t flags = 0; size_t size = 0; std::string hpack_encoding; SerializePushPromiseBuilderHelper(push_promise, &flags, &hpack_encoding, &size); bool ok = true; SpdyFrameBuilder builder(size, output); size_t length = std::min(size, kHttp2MaxControlFrameSendSize) - kFrameHeaderSize; ok = builder.BeginNewFrame(SpdyFrameType::PUSH_PROMISE, flags, push_promise.stream_id(), length); int padding_payload_len = 0; if (push_promise.padded()) { ok = ok && builder.WriteUInt8(push_promise.padding_payload_len()) && builder.WriteUInt32(push_promise.promised_stream_id()); QUICHE_DCHECK_EQ(kPushPromiseFrameMinimumSize + kPadLengthFieldSize, builder.length()); padding_payload_len = push_promise.padding_payload_len(); } else { ok = ok && builder.WriteUInt32(push_promise.promised_stream_id()); QUICHE_DCHECK_EQ(kPushPromiseFrameMinimumSize, builder.length()); } ok = ok && WritePayloadWithContinuation( &builder, hpack_encoding, push_promise.stream_id(), SpdyFrameType::PUSH_PROMISE, padding_payload_len); if (debug_visitor_) { const size_t header_list_size = GetUncompressedSerializedLength(push_promise.header_block()); debug_visitor_->OnSendCompressedFrame(push_promise.stream_id(), SpdyFrameType::PUSH_PROMISE, header_list_size, builder.length()); } return ok; } bool SpdyFramer::SerializeContinuation(const SpdyContinuationIR& continuation, ZeroCopyOutputBuffer* output) const { const std::string& encoding = continuation.encoding(); size_t frame_size = kContinuationFrameMinimumSize + encoding.size(); SpdyFrameBuilder builder(frame_size, output); uint8_t flags = continuation.end_headers() ? HEADERS_FLAG_END_HEADERS : 0; bool ok = builder.BeginNewFrame(SpdyFrameType::CONTINUATION, flags, continuation.stream_id(), frame_size - kFrameHeaderSize); QUICHE_DCHECK_EQ(kFrameHeaderSize, builder.length()); ok = ok && builder.WriteBytes(encoding.data(), encoding.size()); return ok; } bool SpdyFramer::SerializeAltSvc(const SpdyAltSvcIR& altsvc_ir, ZeroCopyOutputBuffer* output) { std::string value; size_t size = 0; SerializeAltSvcBuilderHelper(altsvc_ir, &value, &size); SpdyFrameBuilder builder(size, output); bool ok = builder.BeginNewFrame(SpdyFrameType::ALTSVC, kNoFlags, altsvc_ir.stream_id()) && builder.WriteUInt16(altsvc_ir.origin().length()) && builder.WriteBytes(altsvc_ir.origin().data(), altsvc_ir.origin().length()) && builder.WriteBytes(value.data(), value.length()); QUICHE_DCHECK_LT(kGetAltSvcFrameMinimumSize, builder.length()); return ok; } bool SpdyFramer::SerializePriority(const SpdyPriorityIR& priority, ZeroCopyOutputBuffer* output) const { SpdyFrameBuilder builder(kPriorityFrameSize, output); bool ok = builder.BeginNewFrame(SpdyFrameType::PRIORITY, kNoFlags, priority.stream_id()); ok = ok && builder.WriteUInt32(PackStreamDependencyValues( priority.exclusive(), priority.parent_stream_id())) && builder.WriteUInt8(priority.weight() - 1); QUICHE_DCHECK_EQ(kPriorityFrameSize, builder.length()); return ok; } bool SpdyFramer::SerializePriorityUpdate( const SpdyPriorityUpdateIR& priority_update, ZeroCopyOutputBuffer* output) const { const size_t total_size = kPriorityUpdateFrameMinimumSize + priority_update.priority_field_value().size(); SpdyFrameBuilder builder(total_size, output); bool ok = builder.BeginNewFrame(SpdyFrameType::PRIORITY_UPDATE, kNoFlags, priority_update.stream_id()); ok = ok && builder.WriteUInt32(priority_update.prioritized_stream_id()); ok = ok && builder.WriteBytes(priority_update.priority_field_value().data(), priority_update.priority_field_value().size()); QUICHE_DCHECK_EQ(total_size, builder.length()); return ok; } bool SpdyFramer::SerializeAcceptCh(const SpdyAcceptChIR& accept_ch, ZeroCopyOutputBuffer* output) const { const size_t total_size = accept_ch.size(); SpdyFrameBuilder builder(total_size, output); bool ok = builder.BeginNewFrame(SpdyFrameType::ACCEPT_CH, kNoFlags, accept_ch.stream_id()); for (const AcceptChOriginValuePair& entry : accept_ch.entries()) { ok = ok && builder.WriteUInt16(entry.origin.size()); ok = ok && builder.WriteBytes(entry.origin.data(), entry.origin.size()); ok = ok && builder.WriteUInt16(entry.value.size()); ok = ok && builder.WriteBytes(entry.value.data(), entry.value.size()); } QUICHE_DCHECK_EQ(total_size, builder.length()); return ok; } bool SpdyFramer::SerializeUnknown(const SpdyUnknownIR& unknown, ZeroCopyOutputBuffer* output) const { const size_t total_size = kFrameHeaderSize + unknown.payload().size(); SpdyFrameBuilder builder(total_size, output); bool ok = builder.BeginNewUncheckedFrame( unknown.type(), unknown.flags(), unknown.stream_id(), unknown.length()); ok = ok && builder.WriteBytes(unknown.payload().data(), unknown.payload().size()); return ok; } namespace { class FrameSerializationVisitorWithOutput : public SpdyFrameVisitor { public: explicit FrameSerializationVisitorWithOutput(SpdyFramer* framer, ZeroCopyOutputBuffer* output) : framer_(framer), output_(output), result_(false) {} ~FrameSerializationVisitorWithOutput() override = default; size_t Result() { return result_; } void VisitData(const SpdyDataIR& data) override { result_ = framer_->SerializeData(data, output_); } void VisitRstStream(const SpdyRstStreamIR& rst_stream) override { result_ = framer_->SerializeRstStream(rst_stream, output_); } void VisitSettings(const SpdySettingsIR& settings) override { result_ = framer_->SerializeSettings(settings, output_); } void VisitPing(const SpdyPingIR& ping) override { result_ = framer_->SerializePing(ping, output_); } void VisitGoAway(const SpdyGoAwayIR& goaway) override { result_ = framer_->SerializeGoAway(goaway, output_); } void VisitHeaders(const SpdyHeadersIR& headers) override { result_ = framer_->SerializeHeaders(headers, output_); } void VisitWindowUpdate(const SpdyWindowUpdateIR& window_update) override { result_ = framer_->SerializeWindowUpdate(window_update, output_); } void VisitPushPromise(const SpdyPushPromiseIR& push_promise) override { result_ = framer_->SerializePushPromise(push_promise, output_); } void VisitContinuation(const SpdyContinuationIR& continuation) override { result_ = framer_->SerializeContinuation(continuation, output_); } void VisitAltSvc(const SpdyAltSvcIR& altsvc) override { result_ = framer_->SerializeAltSvc(altsvc, output_); } void VisitPriority(const SpdyPriorityIR& priority) override { result_ = framer_->SerializePriority(priority, output_); } void VisitPriorityUpdate( const SpdyPriorityUpdateIR& priority_update) override { result_ = framer_->SerializePriorityUpdate(priority_update, output_); } void VisitAcceptCh(const SpdyAcceptChIR& accept_ch) override { result_ = framer_->SerializeAcceptCh(accept_ch, output_); } void VisitUnknown(const SpdyUnknownIR& unknown) override { result_ = framer_->SerializeUnknown(unknown, output_); } private: SpdyFramer* framer_; ZeroCopyOutputBuffer* output_; bool result_; }; } size_t SpdyFramer::SerializeFrame(const SpdyFrameIR& frame, ZeroCopyOutputBuffer* output) { FrameSerializationVisitorWithOutput visitor(this, output); size_t free_bytes_before = output->BytesFree(); frame.Visit(&visitor); return visitor.Result() ? free_bytes_before - output->BytesFree() : 0; } HpackEncoder* SpdyFramer::GetHpackEncoder() { if (hpack_encoder_ == nullptr) { hpack_encoder_ = std::make_unique<HpackEncoder>(); if (!compression_enabled()) { hpack_encoder_->DisableCompression(); } } return hpack_encoder_.get(); } void SpdyFramer::UpdateHeaderEncoderTableSize(uint32_t value) { GetHpackEncoder()->ApplyHeaderTableSizeSetting(value); } size_t SpdyFramer::header_encoder_table_size() const { if (hpack_encoder_ == nullptr) { return kDefaultHeaderTableSizeSetting; } else { return hpack_encoder_->CurrentHeaderTableSizeSetting(); } } }
#include "quiche/http2/core/spdy_framer.h" #include <stdlib.h> #include <algorithm> #include <cstdint> #include <cstring> #include <ios> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/http2/core/array_output_buffer.h" #include "quiche/http2/core/http2_frame_decoder_adapter.h" #include "quiche/http2/core/recording_headers_handler.h" #include "quiche/http2/core/spdy_alt_svc_wire_format.h" #include "quiche/http2/core/spdy_bitmasks.h" #include "quiche/http2/core/spdy_frame_builder.h" #include "quiche/http2/core/spdy_headers_handler_interface.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/hpack/hpack_encoder.h" #include "quiche/http2/test_tools/mock_spdy_framer_visitor.h" #include "quiche/http2/test_tools/spdy_test_utils.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_text_utils.h" using ::http2::Http2DecoderAdapter; using ::testing::_; namespace spdy { namespace test { namespace { const int64_t kSize = 1024 * 1024; char output_buffer[kSize] = ""; const int64_t buffer_size = 64 * 1024; char frame_list_char[buffer_size] = ""; } class MockDebugVisitor : public SpdyFramerDebugVisitorInterface { public: MOCK_METHOD(void, OnSendCompressedFrame, (SpdyStreamId stream_id, SpdyFrameType type, size_t payload_len, size_t frame_len), (override)); MOCK_METHOD(void, OnReceiveCompressedFrame, (SpdyStreamId stream_id, SpdyFrameType type, size_t frame_len), (override)); }; MATCHER_P(IsFrameUnionOf, frame_list, "") { size_t size_verified = 0; for (const auto& frame : *frame_list) { if (arg.size() < size_verified + frame.size()) { QUICHE_LOG(FATAL) << "Incremental header serialization should not lead to a " << "higher total frame length than non-incremental method."; return false; } if (memcmp(arg.data() + size_verified, frame.data(), frame.size())) { CompareCharArraysWithHexError( "Header serialization methods should be equivalent: ", reinterpret_cast<unsigned char*>(arg.data() + size_verified), frame.size(), reinterpret_cast<unsigned char*>(frame.data()), frame.size()); return false; } size_verified += frame.size(); } return size_verified == arg.size(); } class SpdyFramerPeer { public: static std::unique_ptr<SpdyHeadersIR> CloneSpdyHeadersIR( const SpdyHeadersIR& headers) { auto new_headers = std::make_unique<SpdyHeadersIR>( headers.stream_id(), headers.header_block().Clone()); new_headers->set_fin(headers.fin()); new_headers->set_has_priority(headers.has_priority()); new_headers->set_weight(headers.weight()); new_headers->set_parent_stream_id(headers.parent_stream_id()); new_headers->set_exclusive(headers.exclusive()); if (headers.padded()) { new_headers->set_padding_len(headers.padding_payload_len() + 1); } return new_headers; } static SpdySerializedFrame SerializeHeaders(SpdyFramer* framer, const SpdyHeadersIR& headers) { SpdySerializedFrame serialized_headers_old_version( framer->SerializeHeaders(headers)); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); SpdyFramer::SpdyHeaderFrameIterator it(framer, CloneSpdyHeadersIR(headers)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } static SpdySerializedFrame SerializeHeaders(SpdyFramer* framer, const SpdyHeadersIR& headers, ArrayOutputBuffer* output) { if (output == nullptr) { return SerializeHeaders(framer, headers); } output->Reset(); EXPECT_TRUE(framer->SerializeHeaders(headers, output)); SpdySerializedFrame serialized_headers_old_version = MakeSerializedFrame(output->Begin(), output->Size()); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); SpdyFramer::SpdyHeaderFrameIterator it(framer, CloneSpdyHeadersIR(headers)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } static std::unique_ptr<SpdyPushPromiseIR> CloneSpdyPushPromiseIR( const SpdyPushPromiseIR& push_promise) { auto new_push_promise = std::make_unique<SpdyPushPromiseIR>( push_promise.stream_id(), push_promise.promised_stream_id(), push_promise.header_block().Clone()); new_push_promise->set_fin(push_promise.fin()); if (push_promise.padded()) { new_push_promise->set_padding_len(push_promise.padding_payload_len() + 1); } return new_push_promise; } static SpdySerializedFrame SerializePushPromise( SpdyFramer* framer, const SpdyPushPromiseIR& push_promise) { SpdySerializedFrame serialized_headers_old_version = framer->SerializePushPromise(push_promise); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); frame_list_buffer.Reset(); SpdyFramer::SpdyPushPromiseFrameIterator it( framer, CloneSpdyPushPromiseIR(push_promise)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } static SpdySerializedFrame SerializePushPromise( SpdyFramer* framer, const SpdyPushPromiseIR& push_promise, ArrayOutputBuffer* output) { if (output == nullptr) { return SerializePushPromise(framer, push_promise); } output->Reset(); EXPECT_TRUE(framer->SerializePushPromise(push_promise, output)); SpdySerializedFrame serialized_headers_old_version = MakeSerializedFrame(output->Begin(), output->Size()); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); frame_list_buffer.Reset(); SpdyFramer::SpdyPushPromiseFrameIterator it( framer, CloneSpdyPushPromiseIR(push_promise)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } }; class TestSpdyVisitor : public SpdyFramerVisitorInterface, public SpdyFramerDebugVisitorInterface { public: static constexpr size_t kDefaultHeaderBufferSize = 16 * 1024 * 1024; explicit TestSpdyVisitor(SpdyFramer::CompressionOption option) : framer_(option), error_count_(0), headers_frame_count_(0), push_promise_frame_count_(0), goaway_count_(0), setting_count_(0), settings_ack_sent_(0), settings_ack_received_(0), continuation_count_(0), altsvc_count_(0), priority_count_(0), unknown_frame_count_(0), on_unknown_frame_result_(false), last_window_update_stream_(0), last_window_update_delta_(0), last_push_promise_stream_(0), last_push_promise_promised_stream_(0), data_bytes_(0), fin_frame_count_(0), fin_flag_count_(0), end_of_stream_count_(0), control_frame_header_data_count_(0), zero_length_control_frame_header_data_count_(0), data_frame_count_(0), last_payload_len_(0), last_frame_len_(0), unknown_payload_len_(0), header_buffer_(new char[kDefaultHeaderBufferSize]), header_buffer_length_(0), header_buffer_size_(kDefaultHeaderBufferSize), header_stream_id_(static_cast<SpdyStreamId>(-1)), header_control_type_(SpdyFrameType::DATA), header_buffer_valid_(false) {} void OnError(Http2DecoderAdapter::SpdyFramerError error, std::string ) override { QUICHE_VLOG(1) << "SpdyFramer Error: " << Http2DecoderAdapter::SpdyFramerErrorToString(error); ++error_count_; } void OnDataFrameHeader(SpdyStreamId stream_id, size_t length, bool fin) override { QUICHE_VLOG(1) << "OnDataFrameHeader(" << stream_id << ", " << length << ", " << fin << ")"; ++data_frame_count_; header_stream_id_ = stream_id; } void OnStreamFrameData(SpdyStreamId stream_id, const char* data, size_t len) override { QUICHE_VLOG(1) << "OnStreamFrameData(" << stream_id << ", data, " << len << ", " << ") data:\n" << quiche::QuicheTextUtils::HexDump( absl::string_view(data, len)); EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += len; } void OnStreamEnd(SpdyStreamId stream_id) override { QUICHE_VLOG(1) << "OnStreamEnd(" << stream_id << ")"; EXPECT_EQ(header_stream_id_, stream_id); ++end_of_stream_count_; } void OnStreamPadLength(SpdyStreamId stream_id, size_t value) override { QUICHE_VLOG(1) << "OnStreamPadding(" << stream_id << ", " << value << ")\n"; EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += 1; } void OnStreamPadding(SpdyStreamId stream_id, size_t len) override { QUICHE_VLOG(1) << "OnStreamPadding(" << stream_id << ", " << len << ")\n"; EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += len; } SpdyHeadersHandlerInterface* OnHeaderFrameStart( SpdyStreamId ) override { if (headers_handler_ == nullptr) { headers_handler_ = std::make_unique<RecordingHeadersHandler>(); } return headers_handler_.get(); } void OnHeaderFrameEnd(SpdyStreamId ) override { QUICHE_CHECK(headers_handler_ != nullptr); headers_ = headers_handler_->decoded_block().Clone(); header_bytes_received_ = headers_handler_->uncompressed_header_bytes(); headers_handler_.reset(); } void OnRstStream(SpdyStreamId stream_id, SpdyErrorCode error_code) override { QUICHE_VLOG(1) << "OnRstStream(" << stream_id << ", " << error_code << ")"; ++fin_frame_count_; } void OnSetting(SpdySettingsId id, uint32_t value) override { QUICHE_VLOG(1) << "OnSetting(" << id << ", " << std::hex << value << ")"; ++setting_count_; } void OnSettingsAck() override { QUICHE_VLOG(1) << "OnSettingsAck"; ++settings_ack_received_; } void OnSettingsEnd() override { QUICHE_VLOG(1) << "OnSettingsEnd"; ++settings_ack_sent_; } void OnPing(SpdyPingId unique_id, bool is_ack) override { QUICHE_LOG(DFATAL) << "OnPing(" << unique_id << ", " << (is_ack ? 1 : 0) << ")"; } void OnGoAway(SpdyStreamId last_accepted_stream_id, SpdyErrorCode error_code) override { QUICHE_VLOG(1) << "OnGoAway(" << last_accepted_stream_id << ", " << error_code << ")"; ++goaway_count_; } void OnHeaders(SpdyStreamId stream_id, size_t payload_length, bool has_priority, int weight, SpdyStreamId parent_stream_id, bool exclusive, bool fin, bool end) override { QUICHE_VLOG(1) << "OnHeaders(" << stream_id << ", " << payload_length << ", " << has_priority << ", " << weight << ", " << parent_stream_id << ", " << exclusive << ", " << fin << ", " << end << ")"; ++headers_frame_count_; InitHeaderStreaming(SpdyFrameType::HEADERS, stream_id); if (fin) { ++fin_flag_count_; } header_has_priority_ = has_priority; header_parent_stream_id_ = parent_stream_id; header_exclusive_ = exclusive; } void OnWindowUpdate(SpdyStreamId stream_id, int delta_window_size) override { QUICHE_VLOG(1) << "OnWindowUpdate(" << stream_id << ", " << delta_window_size << ")"; last_window_update_stream_ = stream_id; last_window_update_delta_ = delta_window_size; } void OnPushPromise(SpdyStreamId stream_id, SpdyStreamId promised_stream_id, bool end) override { QUICHE_VLOG(1) << "OnPushPromise(" << stream_id << ", " << promised_stream_id << ", " << end << ")"; ++push_promise_frame_count_; InitHeaderStreaming(SpdyFrameType::PUSH_PROMISE, stream_id); last_push_promise_stream_ = stream_id; last_push_promise_promised_stream_ = promised_stream_id; } void OnContinuation(SpdyStreamId stream_id, size_t payload_size, bool end) override { QUICHE_VLOG(1) << "OnContinuation(" << stream_id << ", " << payload_size << ", " << end << ")"; ++continuation_count_; } void OnAltSvc(SpdyStreamId stream_id, absl::string_view origin, const SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector) override { QUICHE_VLOG(1) << "OnAltSvc(" << stream_id << ", \"" << origin << "\", altsvc_vector)"; test_altsvc_ir_ = std::make_unique<SpdyAltSvcIR>(stream_id); if (origin.length() > 0) { test_altsvc_ir_->set_origin(std::string(origin)); } for (const auto& altsvc : altsvc_vector) { test_altsvc_ir_->add_altsvc(altsvc); } ++altsvc_count_; } void OnPriority(SpdyStreamId stream_id, SpdyStreamId parent_stream_id, int weight, bool exclusive) override { QUICHE_VLOG(1) << "OnPriority(" << stream_id << ", " << parent_stream_id << ", " << weight << ", " << (exclusive ? 1 : 0) << ")"; ++priority_count_; } void OnPriorityUpdate(SpdyStreamId prioritized_stream_id, absl::string_view priority_field_value) override { QUICHE_VLOG(1) << "OnPriorityUpdate(" << prioritized_stream_id << ", " << priority_field_value << ")"; } bool OnUnknownFrame(SpdyStreamId stream_id, uint8_t frame_type) override { QUICHE_VLOG(1) << "OnUnknownFrame(" << stream_id << ", " << frame_type << ")"; return on_unknown_frame_result_; } void OnUnknownFrameStart(SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) override { QUICHE_VLOG(1) << "OnUnknownFrameStart(" << stream_id << ", " << length << ", " << static_cast<int>(type) << ", " << static_cast<int>(flags) << ")"; ++unknown_frame_count_; } void OnUnknownFramePayload(SpdyStreamId stream_id, absl::string_view payload) override { QUICHE_VLOG(1) << "OnUnknownFramePayload(" << stream_id << ", " << payload << ")"; unknown_payload_len_ += payload.length(); } void OnSendCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t payload_len, size_t frame_len) override { QUICHE_VLOG(1) << "OnSendCompressedFrame(" << stream_id << ", " << type << ", " << payload_len << ", " << frame_len << ")"; last_payload_len_ = payload_len; last_frame_len_ = frame_len; } void OnReceiveCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t frame_len) override { QUICHE_VLOG(1) << "OnReceiveCompressedFrame(" << stream_id << ", " << type << ", " << frame_len << ")"; last_frame_len_ = frame_len; } void SimulateInFramer(const unsigned char* input, size_t size) { deframer_.set_visitor(this); size_t input_remaining = size; const char* input_ptr = reinterpret_cast<const char*>(input); while (input_remaining > 0 && deframer_.spdy_framer_error() == Http2DecoderAdapter::SPDY_NO_ERROR) { const size_t kMaxReadSize = 32; size_t bytes_read = (rand() % std::min(input_remaining, kMaxReadSize)) + 1; size_t bytes_processed = deframer_.ProcessInput(input_ptr, bytes_read); input_remaining -= bytes_processed; input_ptr += bytes_processed; } } void InitHeaderStreaming(SpdyFrameType header_control_type, SpdyStreamId stream_id) { if (!IsDefinedFrameType(SerializeFrameType(header_control_type))) { QUICHE_DLOG(FATAL) << "Attempted to init header streaming with " << "invalid control frame type: " << header_control_type; } memset(header_buffer_.get(), 0, header_buffer_size_); header_buffer_length_ = 0; header_stream_id_ = stream_id; header_control_type_ = header_control_type; header_buffer_valid_ = true; } void set_extension_visitor(ExtensionVisitorInterface* extension) { deframer_.set_extension_visitor(extension); } void set_header_buffer_size(size_t header_buffer_size) { header_buffer_size_ = header_buffer_size; header_buffer_.reset(new char[header_buffer_size]); } SpdyFramer framer_; Http2DecoderAdapter deframer_; int error_count_; int headers_frame_count_; int push_promise_frame_count_; int goaway_count_; int setting_count_; int settings_ack_sent_; int settings_ack_received_; int continuation_count_; int altsvc_count_; int priority_count_; std::unique_ptr<SpdyAltSvcIR> test_altsvc_ir_; int unknown_frame_count_; bool on_unknown_frame_result_; SpdyStreamId last_window_update_stream_; int last_window_update_delta_; SpdyStreamId last_push_promise_stream_; SpdyStreamId last_push_promise_promised_stream_; int data_bytes_; int fin_frame_count_; int fin_flag_count_; int end_of_stream_count_; int control_frame_header_data_count_; int zero_length_control_frame_header_data_count_; int data_frame_count_; size_t last_payload_len_; size_t last_frame_len_; size_t unknown_payload_len_; std::unique_ptr<char[]> header_buffer_; size_t header_buffer_length_; size_t header_buffer_size_; size_t header_bytes_received_; SpdyStreamId header_stream_id_; SpdyFrameType header_control_type_; bool header_buffer_valid_; std::unique_ptr<RecordingHeadersHandler> headers_handler_; quiche::HttpHeaderBlock headers_; bool header_has_priority_; SpdyStreamId header_parent_stream_id_; bool header_exclusive_; }; class TestExtension : public ExtensionVisitorInterface { public: void OnSetting(SpdySettingsId id, uint32_t value) override { settings_received_.push_back({id, value}); } bool OnFrameHeader(SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) override { stream_id_ = stream_id; length_ = length; type_ = type; flags_ = flags; return true; } void OnFramePayload(const char* data, size_t len) override { payload_.append(data, len); } std::vector<std::pair<SpdySettingsId, uint32_t>> settings_received_; SpdyStreamId stream_id_ = 0; size_t length_ = 0; uint8_t type_ = 0; uint8_t flags_ = 0; std::string payload_; }; class TestSpdyUnknownIR : public SpdyUnknownIR { public: using SpdyUnknownIR::set_length; using SpdyUnknownIR::SpdyUnknownIR; }; enum Output { USE, NOT_USE }; class SpdyFramerTest : public quiche::test::QuicheTestWithParam<Output> { public: SpdyFramerTest() : output_(output_buffer, kSize), framer_(SpdyFramer::ENABLE_COMPRESSION), deframer_(std::make_unique<Http2DecoderAdapter>()) {} protected: void SetUp() override { switch (GetParam()) { case USE: use_output_ = true; break; case NOT_USE: use_output_ = false; break; } } void CompareFrame(const std::string& description, const SpdySerializedFrame& actual_frame, const unsigned char* expected, const int expected_len) { const unsigned char* actual = reinterpret_cast<const unsigned char*>(actual_frame.data()); CompareCharArraysWithHexError(description, actual, actual_frame.size(), expected, expected_len); } bool use_output_ = false; ArrayOutputBuffer output_; SpdyFramer framer_; std::unique_ptr<Http2DecoderAdapter> deframer_; }; INSTANTIATE_TEST_SUITE_P(SpdyFramerTests, SpdyFramerTest, ::testing::Values(USE, NOT_USE)); TEST_P(SpdyFramerTest, HeaderBlockInBuffer) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdyHeadersIR headers( 1); headers.SetHeader("alpha", "beta"); headers.SetHeader("gamma", "charlie"); headers.SetHeader("cookie", "key1=value1; key2=value2"); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size()); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(headers.header_block(), visitor.headers_); } TEST_P(SpdyFramerTest, UndersizedHeaderBlockInBuffer) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdyHeadersIR headers( 1); headers.SetHeader("alpha", "beta"); headers.SetHeader("gamma", "charlie"); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size() - 2); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_THAT(visitor.headers_, testing::IsEmpty()); } TEST_P(SpdyFramerTest, HeaderStreamDependencyValues) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const SpdyStreamId parent_stream_id_test_array[] = {0, 3}; for (SpdyStreamId parent_stream_id : parent_stream_id_test_array) { const bool exclusive_test_array[] = {true, false}; for (bool exclusive : exclusive_test_array) { SpdyHeadersIR headers(1); headers.set_has_priority(true); headers.set_parent_stream_id(parent_stream_id); headers.set_exclusive(exclusive); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size()); EXPECT_TRUE(visitor.header_has_priority_); EXPECT_EQ(parent_stream_id, visitor.header_parent_stream_id_); EXPECT_EQ(exclusive, visitor.header_exclusive_); } } } TEST_P(SpdyFramerTest, AcceptMaxFrameSizeSetting) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 16384, 0x0, 0x0)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 1 << 14, false)); EXPECT_CALL(visitor, OnStreamFrameData(1, _, 4)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_FALSE(deframer_->HasError()); } TEST_P(SpdyFramerTest, ExceedMaxFrameSizeSetting) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 16385, 0x0, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD, _)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, AcceptLargerMaxFrameSizeSetting) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); const size_t big_frame_size = (1 << 14) + 1; deframer_->SetMaxFrameSize(big_frame_size); unsigned char kH2FrameData[] = { 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, big_frame_size, 0x0, 0x0)); EXPECT_CALL(visitor, OnDataFrameHeader(1, big_frame_size, false)); EXPECT_CALL(visitor, OnStreamFrameData(1, _, 4)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_FALSE(deframer_->HasError()); } TEST_P(SpdyFramerTest, OversizedDataPaddingError) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); { testing::InSequence seq; EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x0, 0x9)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 5, 1)); EXPECT_CALL(visitor, OnStreamPadding(1, 1)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_PADDING, _)); } EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_PADDING, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, CorrectlySizedDataPaddingNoError) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame(kH2FrameData, sizeof(kH2FrameData)); { testing::InSequence seq; EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x0, 0x8)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 5, false)); EXPECT_CALL(visitor, OnStreamPadLength(1, 4)); EXPECT_CALL(visitor, OnError(_, _)).Times(0); EXPECT_CALL(visitor, OnStreamPadding(1, 4)); } EXPECT_EQ(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_FALSE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, OversizedHeadersPaddingError) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x1, 0x8)); EXPECT_CALL(visitor, OnHeaders(1, 5, false, 0, 0, false, false, false)); EXPECT_CALL(visitor, OnHeaderFrameStart(1)).Times(1); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_PADDING, _)); EXPECT_EQ(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_PADDING, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, CorrectlySizedHeadersPaddingNoError) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame(kH2FrameData, sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x1, 0x8)); EXPECT_CALL(visitor, OnHeaders(1, 5, false, 0, 0, false, false, false)); EXPECT_CALL(visitor, OnHeaderFrameStart(1)).Times(1); EXPECT_EQ(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_FALSE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, DataWithStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); const char bytes[] = "hello"; SpdyDataIR data_ir( 0, bytes); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x0, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, HeadersWithStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyHeadersIR headers( 0); headers.SetHeader("alpha", "beta"); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer_, headers, &output_)); EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x1, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, PriorityWithStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyPriorityIR priority_ir( 0, 1, 16, true); SpdySerializedFrame frame(framer_.SerializeFrame(priority_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(priority_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x2, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, RstStreamWithStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyRstStreamIR rst_stream_ir( 0, ERROR_CODE_PROTOCOL_ERROR); SpdySerializedFrame frame(framer_.SerializeRstStream(rst_stream_ir)); if (use_output_) { EXPECT_TRUE(framer_.SerializeRstStream(rst_stream_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x3, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, SettingsWithStreamIdNotZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); char kH2FrameData[] = { 0x00, 0x00, 0x06, 0x04, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x0a, 0x0b, 0x0c, 0x0d, }; SpdySerializedFrame frame = MakeSerializedFrame(kH2FrameData, sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 6, 0x4, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, GoawayWithStreamIdNotZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); char kH2FrameData[] = { 0x00, 0x00, 0x0a, 0x07, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x41, }; SpdySerializedFrame frame = MakeSerializedFrame(kH2FrameData, sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 10, 0x7, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, ContinuationWithStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyContinuationIR continuation( 0); std::string some_nonsense_encoding = "some nonsense encoding"; continuation.take_encoding(std::move(some_nonsense_encoding)); continuation.set_end_headers(true); SpdySerializedFrame frame(framer_.SerializeContinuation(continuation)); if (use_output_) { ASSERT_TRUE(framer_.SerializeContinuation(continuation, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x9, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, PushPromiseWithStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyPushPromiseIR push_promise( 0, 4); push_promise.SetHeader("alpha", "beta"); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer_, push_promise, use_output_ ? &output_ : nullptr)); EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x5, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, PushPromiseWithPromisedStreamIdZero) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyPushPromiseIR push_promise( 3, 0); push_promise.SetHeader("alpha", "beta"); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer_, push_promise, use_output_ ? &output_ : nullptr)); EXPECT_CALL(visitor, OnCommonHeader(3, _, 0x5, _)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, _)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, MultiValueHeader) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); std::string value("value1\0value2", 13); quiche::HttpHeaderBlock header_set; header_set["name"] = value; HpackEncoder encoder; encoder.DisableCompression(); std::string buffer = encoder.EncodeHeaderBlock(header_set); SpdyFrameBuilder frame(1024); frame.BeginNewFrame(SpdyFrameType::HEADERS, HEADERS_FLAG_PRIORITY | HEADERS_FLAG_END_HEADERS, 3, buffer.size() + 5 ); frame.WriteUInt32(0); frame.WriteUInt8(255); frame.WriteBytes(&buffer[0], buffer.size()); SpdySerializedFrame control_frame(frame.take()); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_THAT(visitor.headers_, testing::ElementsAre(testing::Pair( "name", absl::string_view(value)))); } TEST_P(SpdyFramerTest, CompressEmptyHeaders) { SpdyHeadersIR headers(1); headers.SetHeader("server", "SpdyServer 1.0"); headers.SetHeader("date", "Mon 12 Jan 2009 12:12:12 PST"); headers.SetHeader("status", "200"); headers.SetHeader("version", "HTTP/1.1"); headers.SetHeader("content-type", "text/html"); headers.SetHeader("content-length", "12"); headers.SetHeader("x-empty-header", ""); SpdyFramer framer(SpdyFramer::ENABLE_COMPRESSION); SpdySerializedFrame frame1( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); } TEST_P(SpdyFramerTest, Basic) { const unsigned char kH2Input[] = { 0x00, 0x00, 0x05, 0x01, 0x24, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x01, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x05, 0x01, 0x24, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2Input, sizeof(kH2Input)); EXPECT_EQ(24, visitor.data_bytes_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(2, visitor.fin_frame_count_); EXPECT_EQ(3, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.fin_flag_count_); EXPECT_EQ(0, visitor.end_of_stream_count_); EXPECT_EQ(4, visitor.data_frame_count_); } TEST_P(SpdyFramerTest, BasicWithError) { const unsigned char kH2Input[] = { 0x00, 0x00, 0x01, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x06, 0x01, 0x24, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x82, 0x8c, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); testing::InSequence s; EXPECT_CALL(visitor, OnCommonHeader(1, 1, 0x1, 0x4)); EXPECT_CALL(visitor, OnHeaders(1, 1, false, 0, 0, false, false, true)); EXPECT_CALL(visitor, OnHeaderFrameStart(1)); EXPECT_CALL(visitor, OnHeaderFrameEnd(1)); EXPECT_CALL(visitor, OnCommonHeader(1, 12, 0x0, 0x0)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 12, false)); EXPECT_CALL(visitor, OnStreamFrameData(1, _, 12)); EXPECT_CALL(visitor, OnCommonHeader(3, 6, 0x1, 0x24)); EXPECT_CALL(visitor, OnHeaders(3, 6, true, 131, 0, false, false, true)); EXPECT_CALL(visitor, OnHeaderFrameStart(3)); EXPECT_CALL(visitor, OnHeaderFrameEnd(3)); EXPECT_CALL(visitor, OnCommonHeader(3, 8, 0x0, 0x0)); EXPECT_CALL(visitor, OnDataFrameHeader(3, 8, false)) .WillOnce(testing::InvokeWithoutArgs( [this]() { deframer_->StopProcessing(); })); EXPECT_CALL( visitor, OnError(http2::Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING, "Ignoring further events on this connection.")); size_t processed = deframer_->ProcessInput( reinterpret_cast<const char*>(kH2Input), sizeof(kH2Input)); EXPECT_LT(processed, sizeof(kH2Input)); } TEST_P(SpdyFramerTest, FinOnDataFrame) { const unsigned char kH2Input[] = { 0x00, 0x00, 0x05, 0x01, 0x24, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x01, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0xde, 0xad, 0xbe, 0xef, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2Input, sizeof(kH2Input)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(2, visitor.headers_frame_count_); EXPECT_EQ(16, visitor.data_bytes_); EXPECT_EQ(0, visitor.fin_frame_count_); EXPECT_EQ(0, visitor.fin_flag_count_); EXPECT_EQ(1, visitor.end_of_stream_count_); EXPECT_EQ(2, visitor.data_frame_count_); } TEST_P(SpdyFramerTest, FinOnHeadersFrame) { const unsigned char kH2Input[] = { 0x00, 0x00, 0x05, 0x01, 0x24, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x01, 0x01, 0x05, 0x00, 0x00, 0x00, 0x01, 0x8c, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2Input, sizeof(kH2Input)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(2, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.data_bytes_); EXPECT_EQ(0, visitor.fin_frame_count_); EXPECT_EQ(1, visitor.fin_flag_count_); EXPECT_EQ(1, visitor.end_of_stream_count_); EXPECT_EQ(0, visitor.data_frame_count_); } TEST_P(SpdyFramerTest, UnclosedStreamDataCompressorsOneByteAtATime) { const char kHeader1[] = "header1"; const char kHeader2[] = "header2"; const char kValue1[] = "value1"; const char kValue2[] = "value2"; SpdyHeadersIR headers( 1); headers.SetHeader(kHeader1, kValue1); headers.SetHeader(kHeader2, kValue2); SpdySerializedFrame headers_frame(SpdyFramerPeer::SerializeHeaders( &framer_, headers, use_output_ ? &output_ : nullptr)); const char bytes[] = "this is a test test test test test!"; SpdyDataIR data_ir( 1, absl::string_view(bytes, ABSL_ARRAYSIZE(bytes))); data_ir.set_fin(true); SpdySerializedFrame send_frame(framer_.SerializeData(data_ir)); TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); const unsigned char* data; data = reinterpret_cast<const unsigned char*>(headers_frame.data()); for (size_t idx = 0; idx < headers_frame.size(); ++idx) { visitor.SimulateInFramer(data + idx, 1); ASSERT_EQ(0, visitor.error_count_); } data = reinterpret_cast<const unsigned char*>(send_frame.data()); for (size_t idx = 0; idx < send_frame.size(); ++idx) { visitor.SimulateInFramer(data + idx, 1); ASSERT_EQ(0, visitor.error_count_); } EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(ABSL_ARRAYSIZE(bytes), static_cast<unsigned>(visitor.data_bytes_)); EXPECT_EQ(0, visitor.fin_frame_count_); EXPECT_EQ(0, visitor.fin_flag_count_); EXPECT_EQ(1, visitor.end_of_stream_count_); EXPECT_EQ(1, visitor.data_frame_count_); } TEST_P(SpdyFramerTest, WindowUpdateFrame) { SpdyWindowUpdateIR window_update( 1, 0x12345678); SpdySerializedFrame frame(framer_.SerializeWindowUpdate(window_update)); if (use_output_) { ASSERT_TRUE(framer_.SerializeWindowUpdate(window_update, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } const char kDescription[] = "WINDOW_UPDATE frame, stream 1, delta 0x12345678"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x12, 0x34, 0x56, 0x78, }; CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } TEST_P(SpdyFramerTest, CreateDataFrame) { { const char kDescription[] = "'hello' data frame, no FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 'h', 'e', 'l', 'l', 'o', }; const char bytes[] = "hello"; SpdyDataIR data_ir( 1, bytes); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); SpdyDataIR data_header_ir( 1); data_header_ir.SetDataShallow(bytes); frame = framer_.SerializeDataFrameHeaderWithPaddingLengthField(data_header_ir); CompareCharArraysWithHexError( kDescription, reinterpret_cast<const unsigned char*>(frame.data()), kDataFrameMinimumSize, kH2FrameData, kDataFrameMinimumSize); } { const char kDescription[] = "'hello' data frame with more padding, no FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0xfd, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0xf7, 'h', 'e', 'l', 'l', 'o', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; const char bytes[] = "hello"; SpdyDataIR data_ir( 1, bytes); data_ir.set_padding_len(248); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); frame = framer_.SerializeDataFrameHeaderWithPaddingLengthField(data_ir); CompareCharArraysWithHexError( kDescription, reinterpret_cast<const unsigned char*>(frame.data()), kDataFrameMinimumSize, kH2FrameData, kDataFrameMinimumSize); } { const char kDescription[] = "'hello' data frame with few padding, no FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x0d, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x07, 'h', 'e', 'l', 'l', 'o', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; const char bytes[] = "hello"; SpdyDataIR data_ir( 1, bytes); data_ir.set_padding_len(8); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); frame = framer_.SerializeDataFrameHeaderWithPaddingLengthField(data_ir); CompareCharArraysWithHexError( kDescription, reinterpret_cast<const unsigned char*>(frame.data()), kDataFrameMinimumSize, kH2FrameData, kDataFrameMinimumSize); } { const char kDescription[] = "'hello' data frame with 1 byte padding, no FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 'h', 'e', 'l', 'l', 'o', }; const char bytes[] = "hello"; SpdyDataIR data_ir( 1, bytes); data_ir.set_padding_len(1); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); frame = framer_.SerializeDataFrameHeaderWithPaddingLengthField(data_ir); CompareCharArraysWithHexError( kDescription, reinterpret_cast<const unsigned char*>(frame.data()), kDataFrameMinimumSize, kH2FrameData, kDataFrameMinimumSize); } { const char kDescription[] = "Data frame with negative data byte, no FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, }; SpdyDataIR data_ir( 1, "\xff"); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "'hello' data frame, with FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x68, 0x65, 0x6c, 0x6c, 0x6f, }; SpdyDataIR data_ir( 1, "hello"); data_ir.set_fin(true); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "Empty data frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; SpdyDataIR data_ir( 1, ""); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); frame = framer_.SerializeDataFrameHeaderWithPaddingLengthField(data_ir); CompareCharArraysWithHexError( kDescription, reinterpret_cast<const unsigned char*>(frame.data()), kDataFrameMinimumSize, kH2FrameData, kDataFrameMinimumSize); } { const char kDescription[] = "Data frame with max stream ID"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x01, 0x7f, 0xff, 0xff, 0xff, 0x68, 0x65, 0x6c, 0x6c, 0x6f, }; SpdyDataIR data_ir( 0x7fffffff, "hello"); data_ir.set_fin(true); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } } TEST_P(SpdyFramerTest, CreateRstStream) { { const char kDescription[] = "RST_STREAM frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, }; SpdyRstStreamIR rst_stream( 1, ERROR_CODE_PROTOCOL_ERROR); SpdySerializedFrame frame(framer_.SerializeRstStream(rst_stream)); if (use_output_) { ASSERT_TRUE(framer_.SerializeRstStream(rst_stream, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "RST_STREAM frame with max stream ID"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x03, 0x00, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, }; SpdyRstStreamIR rst_stream( 0x7FFFFFFF, ERROR_CODE_PROTOCOL_ERROR); SpdySerializedFrame frame(framer_.SerializeRstStream(rst_stream)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeRstStream(rst_stream, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "RST_STREAM frame with max status code"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x03, 0x00, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, }; SpdyRstStreamIR rst_stream( 0x7FFFFFFF, ERROR_CODE_INTERNAL_ERROR); SpdySerializedFrame frame(framer_.SerializeRstStream(rst_stream)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeRstStream(rst_stream, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } } TEST_P(SpdyFramerTest, CreateSettings) { { const char kDescription[] = "Network byte order SETTINGS frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x06, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x0a, 0x0b, 0x0c, 0x0d, }; uint32_t kValue = 0x0a0b0c0d; SpdySettingsIR settings_ir; SpdyKnownSettingsId kId = SETTINGS_INITIAL_WINDOW_SIZE; settings_ir.AddSetting(kId, kValue); SpdySerializedFrame frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "Basic SETTINGS frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x18, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, }; SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_HEADER_TABLE_SIZE, 5); settings_ir.AddSetting(SETTINGS_ENABLE_PUSH, 6); settings_ir.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, 7); settings_ir.AddSetting(SETTINGS_INITIAL_WINDOW_SIZE, 8); SpdySerializedFrame frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "Empty SETTINGS frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, }; SpdySettingsIR settings_ir; SpdySerializedFrame frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } } TEST_P(SpdyFramerTest, CreatePingFrame) { { const char kDescription[] = "PING frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xff, }; const unsigned char kH2FrameDataWithAck[] = { 0x00, 0x00, 0x08, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xff, }; const SpdyPingId kPingId = 0x123456789abcdeffULL; SpdyPingIR ping_ir(kPingId); ASSERT_FALSE(ping_ir.is_ack()); SpdySerializedFrame frame(framer_.SerializePing(ping_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializePing(ping_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); ping_ir.set_is_ack(true); frame = framer_.SerializePing(ping_ir); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializePing(ping_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameDataWithAck, ABSL_ARRAYSIZE(kH2FrameDataWithAck)); } } TEST_P(SpdyFramerTest, CreateGoAway) { { const char kDescription[] = "GOAWAY frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x0a, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x41, }; SpdyGoAwayIR goaway_ir( 0, ERROR_CODE_NO_ERROR, "GA"); SpdySerializedFrame frame(framer_.SerializeGoAway(goaway_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializeGoAway(goaway_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "GOAWAY frame with max stream ID, status"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x0a, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x47, 0x41, }; SpdyGoAwayIR goaway_ir( 0x7FFFFFFF, ERROR_CODE_INTERNAL_ERROR, "GA"); SpdySerializedFrame frame(framer_.SerializeGoAway(goaway_ir)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeGoAway(goaway_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } } TEST_P(SpdyFramerTest, CreateHeadersUncompressed) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); { const char kDescription[] = "HEADERS frame, no FIN"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x12, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, }; SpdyHeadersIR headers( 1); headers.SetHeader("bar", "foo"); headers.SetHeader("foo", "bar"); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "HEADERS frame with a 0-length header name, FIN, max stream ID"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x0f, 0x01, 0x05, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, }; SpdyHeadersIR headers( 0x7fffffff); headers.set_fin(true); headers.SetHeader("", "foo"); headers.SetHeader("foo", "bar"); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "HEADERS frame with a 0-length header val, FIN, max stream ID"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x0f, 0x01, 0x05, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00, }; SpdyHeadersIR headers_ir( 0x7fffffff); headers_ir.set_fin(true); headers_ir.SetHeader("bar", "foo"); headers_ir.SetHeader("foo", ""); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers_ir, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "HEADERS frame with a 0-length header val, FIN, max stream ID, pri"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x14, 0x01, 0x25, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xdb, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00, }; SpdyHeadersIR headers_ir( 0x7fffffff); headers_ir.set_fin(true); headers_ir.set_has_priority(true); headers_ir.set_weight(220); headers_ir.SetHeader("bar", "foo"); headers_ir.SetHeader("foo", ""); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers_ir, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "HEADERS frame with a 0-length header val, FIN, max stream ID, pri, " "exclusive=true, parent_stream=0"; const unsigned char kV4FrameData[] = { 0x00, 0x00, 0x14, 0x01, 0x25, 0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0xdb, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00, }; SpdyHeadersIR headers_ir( 0x7fffffff); headers_ir.set_fin(true); headers_ir.set_has_priority(true); headers_ir.set_weight(220); headers_ir.set_exclusive(true); headers_ir.set_parent_stream_id(0); headers_ir.SetHeader("bar", "foo"); headers_ir.SetHeader("foo", ""); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers_ir, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kV4FrameData, ABSL_ARRAYSIZE(kV4FrameData)); } { const char kDescription[] = "HEADERS frame with a 0-length header val, FIN, max stream ID, pri, " "exclusive=false, parent_stream=max stream ID"; const unsigned char kV4FrameData[] = { 0x00, 0x00, 0x14, 0x01, 0x25, 0x7f, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xdb, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00, }; SpdyHeadersIR headers_ir( 0x7fffffff); headers_ir.set_fin(true); headers_ir.set_has_priority(true); headers_ir.set_weight(220); headers_ir.set_exclusive(false); headers_ir.set_parent_stream_id(0x7fffffff); headers_ir.SetHeader("bar", "foo"); headers_ir.SetHeader("foo", ""); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers_ir, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kV4FrameData, ABSL_ARRAYSIZE(kV4FrameData)); } { const char kDescription[] = "HEADERS frame with a 0-length header name, FIN, max stream ID, padded"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x15, 0x01, 0x0d, 0x7f, 0xff, 0xff, 0xff, 0x05, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, }; SpdyHeadersIR headers_ir( 0x7fffffff); headers_ir.set_fin(true); headers_ir.SetHeader("", "foo"); headers_ir.SetHeader("foo", "bar"); headers_ir.set_padding_len(6); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers_ir, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } } TEST_P(SpdyFramerTest, CreateWindowUpdate) { { const char kDescription[] = "WINDOW_UPDATE frame"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, }; SpdySerializedFrame frame(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 1, 1))); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 1, 1), &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "WINDOW_UPDATE frame with max stream ID"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x08, 0x00, 0x7f, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, }; SpdySerializedFrame frame(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 0x7FFFFFFF, 1))); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 0x7FFFFFFF, 1), &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } { const char kDescription[] = "WINDOW_UPDATE frame with max window delta"; const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0xff, 0xff, 0xff, }; SpdySerializedFrame frame(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 1, 0x7FFFFFFF))); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 1, 0x7FFFFFFF), &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kH2FrameData, ABSL_ARRAYSIZE(kH2FrameData)); } } TEST_P(SpdyFramerTest, CreatePushPromiseUncompressed) { { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const char kDescription[] = "PUSH_PROMISE frame without padding"; const unsigned char kFrameData[] = { 0x00, 0x00, 0x16, 0x05, 0x04, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, }; SpdyPushPromiseIR push_promise( 41, 58); push_promise.SetHeader("bar", "foo"); push_promise.SetHeader("foo", "bar"); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const char kDescription[] = "PUSH_PROMISE frame with one byte of padding"; const unsigned char kFrameData[] = { 0x00, 0x00, 0x17, 0x05, 0x0c, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, }; SpdyPushPromiseIR push_promise( 41, 58); push_promise.set_padding_len(1); push_promise.SetHeader("bar", "foo"); push_promise.SetHeader("foo", "bar"); output_.Reset(); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const char kDescription[] = "PUSH_PROMISE frame with 177 bytes of padding"; const unsigned char kFrameData[] = { 0x00, 0x00, 0xc7, 0x05, 0x0c, 0x00, 0x00, 0x00, 0x2a, 0xb0, 0x00, 0x00, 0x00, 0x39, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; SpdyPushPromiseIR push_promise( 42, 57); push_promise.set_padding_len(177); push_promise.SetHeader("bar", "foo"); push_promise.SetHeader("foo", "bar"); output_.Reset(); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } } TEST_P(SpdyFramerTest, GetNumberRequiredContinuationFrames) { EXPECT_EQ(1u, GetNumberRequiredContinuationFrames(16383 + 16374)); EXPECT_EQ(2u, GetNumberRequiredContinuationFrames(16383 + 16374 + 1)); EXPECT_EQ(2u, GetNumberRequiredContinuationFrames(16383 + 2 * 16374)); EXPECT_EQ(3u, GetNumberRequiredContinuationFrames(16383 + 2 * 16374 + 1)); } TEST_P(SpdyFramerTest, CreateContinuationUncompressed) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const char kDescription[] = "CONTINUATION frame"; const unsigned char kFrameData[] = { 0x00, 0x00, 0x12, 0x09, 0x04, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, }; quiche::HttpHeaderBlock header_block; header_block["bar"] = "foo"; header_block["foo"] = "bar"; HpackEncoder encoder; encoder.DisableCompression(); std::string buffer = encoder.EncodeHeaderBlock(header_block); SpdyContinuationIR continuation( 42); continuation.take_encoding(std::move(buffer)); continuation.set_end_headers(true); SpdySerializedFrame frame(framer.SerializeContinuation(continuation)); if (use_output_) { ASSERT_TRUE(framer.SerializeContinuation(continuation, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, SendUnexpectedContinuation) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); char kH2FrameData[] = { 0x00, 0x00, 0x12, 0x09, 0x04, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x03, 0x62, 0x61, 0x72, 0x03, 0x66, 0x6f, 0x6f, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72, }; SpdySerializedFrame frame = MakeSerializedFrame(kH2FrameData, sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(42, 18, 0x9, 0x4)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, _)); EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, CreatePushPromiseThenContinuationUncompressed) { { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const char kDescription[] = "PUSH_PROMISE and CONTINUATION frames with one byte of padding"; const unsigned char kPartialPushPromiseFrameData[] = { 0x00, 0x3f, 0xf6, 0x05, 0x08, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x39, 0x00, 0x03, 0x78, 0x78, 0x78, 0x7f, 0x80, 0x7f, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, }; const unsigned char kContinuationFrameData[] = { 0x00, 0x00, 0x16, 0x09, 0x04, 0x00, 0x00, 0x00, 0x2a, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, }; SpdyPushPromiseIR push_promise( 42, 57); push_promise.set_padding_len(1); std::string big_value(kHttp2MaxControlFrameSendSize, 'x'); push_promise.SetHeader("xxx", big_value); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); int len_non_data_payload = 31; EXPECT_EQ(kHttp2MaxControlFrameSendSize + len_non_data_payload, frame.size()); const unsigned char* frame_data = reinterpret_cast<const unsigned char*>(frame.data()); CompareCharArraysWithHexError(kDescription, frame_data, ABSL_ARRAYSIZE(kPartialPushPromiseFrameData), kPartialPushPromiseFrameData, ABSL_ARRAYSIZE(kPartialPushPromiseFrameData)); frame_data += kHttp2MaxControlFrameSendSize; CompareCharArraysWithHexError( kDescription, frame_data, ABSL_ARRAYSIZE(kContinuationFrameData), kContinuationFrameData, ABSL_ARRAYSIZE(kContinuationFrameData)); } } TEST_P(SpdyFramerTest, CreateAltSvc) { const char kDescription[] = "ALTSVC frame"; const unsigned char kType = SerializeFrameType(SpdyFrameType::ALTSVC); const unsigned char kFrameData[] = { 0x00, 0x00, 0x49, kType, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x06, 'o', 'r', 'i', 'g', 'i', 'n', 'p', 'i', 'd', '1', '=', '"', 'h', 'o', 's', 't', ':', '4', '4', '3', '"', ';', ' ', 'm', 'a', '=', '5', ',', 'p', '%', '2', '2', '%', '3', 'D', 'i', '%', '3', 'A', 'd', '=', '"', 'h', '_', '\\', '\\', 'o', '\\', '"', 's', 't', ':', '1', '2', '3', '"', ';', ' ', 'm', 'a', '=', '4', '2', ';', ' ', 'v', '=', '"', '2', '4', '"'}; SpdyAltSvcIR altsvc_ir( 3); altsvc_ir.set_origin("origin"); altsvc_ir.add_altsvc(SpdyAltSvcWireFormat::AlternativeService( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector())); altsvc_ir.add_altsvc(SpdyAltSvcWireFormat::AlternativeService( "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24})); SpdySerializedFrame frame(framer_.SerializeFrame(altsvc_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(altsvc_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, CreatePriority) { const char kDescription[] = "PRIORITY frame"; const unsigned char kFrameData[] = { 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x10, }; SpdyPriorityIR priority_ir( 2, 1, 17, true); SpdySerializedFrame frame(framer_.SerializeFrame(priority_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(priority_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, CreatePriorityUpdate) { const char kDescription[] = "PRIORITY_UPDATE frame"; const unsigned char kType = SerializeFrameType(SpdyFrameType::PRIORITY_UPDATE); const unsigned char kFrameData[] = { 0x00, 0x00, 0x07, kType, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 'u', '=', '0'}; SpdyPriorityUpdateIR priority_update_ir( 0, 3, "u=0"); SpdySerializedFrame frame(framer_.SerializeFrame(priority_update_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(priority_update_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, CreateAcceptCh) { const char kDescription[] = "ACCEPT_CH frame"; const unsigned char kType = SerializeFrameType(SpdyFrameType::ACCEPT_CH); const unsigned char kFrameData[] = { 0x00, 0x00, 0x2d, kType, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 'w', 'w', 'w', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x00, 0x03, 'f', 'o', 'o', 0x00, 0x10, 'm', 'a', 'i', 'l', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 0x00, 0x03, 'b', 'a', 'r'}; SpdyAcceptChIR accept_ch_ir( {{"www.example.com", "foo"}, {"mail.example.com", "bar"}}); SpdySerializedFrame frame(framer_.SerializeFrame(accept_ch_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(accept_ch_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, CreateUnknown) { const char kDescription[] = "Unknown frame"; const uint8_t kType = 0xaf; const uint8_t kFlags = 0x11; const uint8_t kLength = strlen(kDescription); const unsigned char kFrameData[] = { 0x00, 0x00, kLength, kType, kFlags, 0x00, 0x00, 0x00, 0x02, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x20, 0x66, 0x72, 0x61, 0x6d, 0x65, }; SpdyUnknownIR unknown_ir( 2, kType, kFlags, kDescription); SpdySerializedFrame frame(framer_.SerializeFrame(unknown_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(unknown_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, CreateUnknownUnchecked) { const char kDescription[] = "Unknown frame"; const uint8_t kType = 0x00; const uint8_t kFlags = 0x11; const uint8_t kLength = std::numeric_limits<uint8_t>::max(); const unsigned int kStreamId = kStreamIdMask + 42; const unsigned char kFrameData[] = { 0x00, 0x00, kLength, kType, kFlags, 0x80, 0x00, 0x00, 0x29, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x20, 0x66, 0x72, 0x61, 0x6d, 0x65, }; TestSpdyUnknownIR unknown_ir( kStreamId, kType, kFlags, kDescription); unknown_ir.set_length(kLength); SpdySerializedFrame frame(framer_.SerializeFrame(unknown_ir)); if (use_output_) { EXPECT_EQ(framer_.SerializeFrame(unknown_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } CompareFrame(kDescription, frame, kFrameData, ABSL_ARRAYSIZE(kFrameData)); } TEST_P(SpdyFramerTest, ReadCompressedHeadersHeaderBlock) { SpdyHeadersIR headers_ir( 1); headers_ir.SetHeader("alpha", "beta"); headers_ir.SetHeader("gamma", "delta"); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializeHeaders( &framer_, headers_ir, use_output_ ? &output_ : nullptr)); TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.control_frame_header_data_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(0, visitor.end_of_stream_count_); EXPECT_EQ(headers_ir.header_block(), visitor.headers_); } TEST_P(SpdyFramerTest, ReadCompressedHeadersHeaderBlockWithHalfClose) { SpdyHeadersIR headers_ir( 1); headers_ir.set_fin(true); headers_ir.SetHeader("alpha", "beta"); headers_ir.SetHeader("gamma", "delta"); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializeHeaders( &framer_, headers_ir, use_output_ ? &output_ : nullptr)); TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.control_frame_header_data_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(1, visitor.end_of_stream_count_); EXPECT_EQ(headers_ir.header_block(), visitor.headers_); } TEST_P(SpdyFramerTest, TooLargeHeadersFrameUsesContinuation) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdyHeadersIR headers( 1); headers.set_padding_len(256); const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; std::string big_value(kBigValueSize, 'x'); headers.SetHeader("aa", big_value); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializeHeaders( &framer, headers, use_output_ ? &output_ : nullptr)); EXPECT_GT(control_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(1, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); } TEST_P(SpdyFramerTest, MultipleContinuationFramesWithIterator) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); auto headers = std::make_unique<SpdyHeadersIR>( 1); headers->set_padding_len(256); const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; std::string big_valuex(kBigValueSize, 'x'); headers->SetHeader("aa", big_valuex); std::string big_valuez(kBigValueSize, 'z'); headers->SetHeader("bb", big_valuez); SpdyFramer::SpdyHeaderFrameIterator frame_it(&framer, std::move(headers)); EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame headers_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); EXPECT_EQ(headers_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(headers_frame.data()), headers_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); output_.Reset(); EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame first_cont_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); EXPECT_EQ(first_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(first_cont_frame.data()), first_cont_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(1, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); output_.Reset(); EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame second_cont_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); EXPECT_LT(second_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(second_cont_frame.data()), second_cont_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(2, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_FALSE(frame_it.HasNextFrame()); } TEST_P(SpdyFramerTest, PushPromiseFramesWithIterator) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); auto push_promise = std::make_unique<SpdyPushPromiseIR>( 1, 2); push_promise->set_padding_len(256); const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; std::string big_valuex(kBigValueSize, 'x'); push_promise->SetHeader("aa", big_valuex); std::string big_valuez(kBigValueSize, 'z'); push_promise->SetHeader("bb", big_valuez); SpdyFramer::SpdyPushPromiseFrameIterator frame_it(&framer, std::move(push_promise)); EXPECT_TRUE(frame_it.HasNextFrame()); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame push_promise_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); EXPECT_EQ(push_promise_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(push_promise_frame.data()), push_promise_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.push_promise_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_TRUE(frame_it.HasNextFrame()); output_.Reset(); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame first_cont_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); EXPECT_EQ(first_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(first_cont_frame.data()), first_cont_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.push_promise_frame_count_); EXPECT_EQ(1, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_TRUE(frame_it.HasNextFrame()); output_.Reset(); EXPECT_GT(frame_it.NextFrame(&output_), 0u); SpdySerializedFrame second_cont_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); EXPECT_LT(second_cont_frame.size(), kHttp2MaxControlFrameSendSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(second_cont_frame.data()), second_cont_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.push_promise_frame_count_); EXPECT_EQ(2, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_FALSE(frame_it.HasNextFrame()); } class SpdyControlFrameIteratorTest : public quiche::test::QuicheTest { public: SpdyControlFrameIteratorTest() : output_(output_buffer, kSize) {} void RunTest(std::unique_ptr<SpdyFrameIR> ir) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdySerializedFrame frame(framer.SerializeFrame(*ir)); std::unique_ptr<SpdyFrameSequence> it = SpdyFramer::CreateIterator(&framer, std::move(ir)); EXPECT_TRUE(it->HasNextFrame()); EXPECT_EQ(it->NextFrame(&output_), frame.size()); EXPECT_FALSE(it->HasNextFrame()); } private: ArrayOutputBuffer output_; }; TEST_F(SpdyControlFrameIteratorTest, RstStreamFrameWithIterator) { auto ir = std::make_unique<SpdyRstStreamIR>(0, ERROR_CODE_PROTOCOL_ERROR); RunTest(std::move(ir)); } TEST_F(SpdyControlFrameIteratorTest, SettingsFrameWithIterator) { auto ir = std::make_unique<SpdySettingsIR>(); uint32_t kValue = 0x0a0b0c0d; SpdyKnownSettingsId kId = SETTINGS_INITIAL_WINDOW_SIZE; ir->AddSetting(kId, kValue); RunTest(std::move(ir)); } TEST_F(SpdyControlFrameIteratorTest, PingFrameWithIterator) { const SpdyPingId kPingId = 0x123456789abcdeffULL; auto ir = std::make_unique<SpdyPingIR>(kPingId); RunTest(std::move(ir)); } TEST_F(SpdyControlFrameIteratorTest, GoAwayFrameWithIterator) { auto ir = std::make_unique<SpdyGoAwayIR>(0, ERROR_CODE_NO_ERROR, "GA"); RunTest(std::move(ir)); } TEST_F(SpdyControlFrameIteratorTest, WindowUpdateFrameWithIterator) { auto ir = std::make_unique<SpdyWindowUpdateIR>(1, 1); RunTest(std::move(ir)); } TEST_F(SpdyControlFrameIteratorTest, AtlSvcFrameWithIterator) { auto ir = std::make_unique<SpdyAltSvcIR>(3); ir->set_origin("origin"); ir->add_altsvc(SpdyAltSvcWireFormat::AlternativeService( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector())); ir->add_altsvc(SpdyAltSvcWireFormat::AlternativeService( "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24})); RunTest(std::move(ir)); } TEST_F(SpdyControlFrameIteratorTest, PriorityFrameWithIterator) { auto ir = std::make_unique<SpdyPriorityIR>(2, 1, 17, true); RunTest(std::move(ir)); } TEST_P(SpdyFramerTest, TooLargePushPromiseFrameUsesContinuation) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdyPushPromiseIR push_promise( 1, 2); push_promise.set_padding_len(256); const size_t kBigValueSize = kHttp2MaxControlFrameSendSize; std::string big_value(kBigValueSize, 'x'); push_promise.SetHeader("aa", big_value); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); EXPECT_GT(control_frame.size(), kHttp2MaxControlFrameSendSize); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_TRUE(visitor.header_buffer_valid_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.push_promise_frame_count_); EXPECT_EQ(1, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); } TEST_P(SpdyFramerTest, ControlFrameMuchTooLarge) { const size_t kHeaderBufferChunks = 4; const size_t kHeaderBufferSize = kHttp2DefaultFramePayloadLimit / kHeaderBufferChunks; const size_t kBigValueSize = kHeaderBufferSize * 2; std::string big_value(kBigValueSize, 'x'); SpdyHeadersIR headers( 1); headers.set_fin(true); headers.SetHeader("aa", big_value); SpdySerializedFrame control_frame(SpdyFramerPeer::SerializeHeaders( &framer_, headers, use_output_ ? &output_ : nullptr)); TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); visitor.set_header_buffer_size(kHeaderBufferSize); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_GT(visitor.header_bytes_received_, visitor.header_buffer_size_); EXPECT_EQ(1, visitor.end_of_stream_count_); } TEST_P(SpdyFramerTest, ControlFrameSizesAreValidated) { const size_t length = 20; ASSERT_GT(kGoawayFrameMinimumSize, kFrameHeaderSize); const size_t less_than_min_length = kGoawayFrameMinimumSize - kFrameHeaderSize - 1; ASSERT_LE(less_than_min_length, std::numeric_limits<unsigned char>::max()); const unsigned char kH2Len = static_cast<unsigned char>(less_than_min_length); const unsigned char kH2FrameData[] = { 0x00, 0x00, kH2Len, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; const size_t pad_length = length + kFrameHeaderSize - sizeof(kH2FrameData); std::string pad(pad_length, 'A'); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2FrameData, sizeof(kH2FrameData)); visitor.SimulateInFramer(reinterpret_cast<const unsigned char*>(pad.c_str()), pad.length()); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(0, visitor.goaway_count_); } TEST_P(SpdyFramerTest, ReadZeroLenSettingsFrame) { SpdySettingsIR settings_ir; SpdySerializedFrame control_frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); control_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } SetFrameLength(&control_frame, 0); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), kFrameHeaderSize); EXPECT_EQ(0, visitor.error_count_); } TEST_P(SpdyFramerTest, ReadBogusLenSettingsFrame) { SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_INITIAL_WINDOW_SIZE, 0x00000002); settings_ir.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, 0x00000002); SpdySerializedFrame control_frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); control_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } const size_t kNewLength = 8; SetFrameLength(&control_frame, kNewLength); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), kFrameHeaderSize + kNewLength); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadLargeSettingsFrame) { SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_HEADER_TABLE_SIZE, 5); settings_ir.AddSetting(SETTINGS_ENABLE_PUSH, 6); settings_ir.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, 7); SpdySerializedFrame control_frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); control_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(3, visitor.setting_count_); EXPECT_EQ(1, visitor.settings_ack_sent_); size_t framed_data = 0; size_t unframed_data = control_frame.size(); size_t kReadChunkSize = 5; while (unframed_data > 0) { size_t to_read = std::min(kReadChunkSize, unframed_data); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data() + framed_data), to_read); unframed_data -= to_read; framed_data += to_read; } EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(3 * 2, visitor.setting_count_); EXPECT_EQ(2, visitor.settings_ack_sent_); } TEST_P(SpdyFramerTest, ReadDuplicateSettings) { const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2FrameData, sizeof(kH2FrameData)); EXPECT_EQ(3, visitor.setting_count_); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.settings_ack_sent_); } TEST_P(SpdyFramerTest, ReadUnknownSettingsId) { const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x06, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x02, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2FrameData, sizeof(kH2FrameData)); EXPECT_EQ(1, visitor.setting_count_); EXPECT_EQ(0, visitor.error_count_); } TEST_P(SpdyFramerTest, ReadKnownAndUnknownSettingsWithExtension) { const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x18, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x02, 0x00, 0x5f, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); TestExtension extension; visitor.set_extension_visitor(&extension); visitor.SimulateInFramer(kH2FrameData, sizeof(kH2FrameData)); EXPECT_EQ(4, visitor.setting_count_); EXPECT_EQ(0, visitor.error_count_); EXPECT_THAT( extension.settings_received_, testing::ElementsAre(testing::Pair(16, 2), testing::Pair(95, 65538))); } TEST_P(SpdyFramerTest, ReadOutOfOrderSettings) { const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x12, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kH2FrameData, sizeof(kH2FrameData)); EXPECT_EQ(3, visitor.setting_count_); EXPECT_EQ(0, visitor.error_count_); } TEST_P(SpdyFramerTest, ProcessSettingsAckFrame) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, sizeof(kFrameData)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(0, visitor.setting_count_); EXPECT_EQ(1, visitor.settings_ack_received_); } TEST_P(SpdyFramerTest, ProcessDataFrameWithPadding) { const int kPaddingLen = 119; const char data_payload[] = "hello"; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyDataIR data_ir( 1, data_payload); data_ir.set_padding_len(kPaddingLen); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); int bytes_consumed = 0; EXPECT_CALL(visitor, OnCommonHeader(1, kPaddingLen + strlen(data_payload), 0x0, 0x8)); EXPECT_CALL(visitor, OnDataFrameHeader(1, kPaddingLen + strlen(data_payload), false)); QUICHE_CHECK_EQ(kDataFrameMinimumSize, deframer_->ProcessInput(frame.data(), kDataFrameMinimumSize)); QUICHE_CHECK_EQ(deframer_->state(), Http2DecoderAdapter::SPDY_READ_DATA_FRAME_PADDING_LENGTH); QUICHE_CHECK_EQ(deframer_->spdy_framer_error(), Http2DecoderAdapter::SPDY_NO_ERROR); bytes_consumed += kDataFrameMinimumSize; EXPECT_CALL(visitor, OnStreamPadLength(1, kPaddingLen - 1)); QUICHE_CHECK_EQ(1u, deframer_->ProcessInput(frame.data() + bytes_consumed, 1)); QUICHE_CHECK_EQ(deframer_->state(), Http2DecoderAdapter::SPDY_FORWARD_STREAM_FRAME); QUICHE_CHECK_EQ(deframer_->spdy_framer_error(), Http2DecoderAdapter::SPDY_NO_ERROR); bytes_consumed += 1; EXPECT_CALL(visitor, OnStreamFrameData(1, _, 2)); QUICHE_CHECK_EQ(2u, deframer_->ProcessInput(frame.data() + bytes_consumed, 2)); QUICHE_CHECK_EQ(deframer_->state(), Http2DecoderAdapter::SPDY_FORWARD_STREAM_FRAME); QUICHE_CHECK_EQ(deframer_->spdy_framer_error(), Http2DecoderAdapter::SPDY_NO_ERROR); bytes_consumed += 2; EXPECT_CALL(visitor, OnStreamFrameData(1, _, 3)); QUICHE_CHECK_EQ(3u, deframer_->ProcessInput(frame.data() + bytes_consumed, 3)); QUICHE_CHECK_EQ(deframer_->state(), Http2DecoderAdapter::SPDY_CONSUME_PADDING); QUICHE_CHECK_EQ(deframer_->spdy_framer_error(), Http2DecoderAdapter::SPDY_NO_ERROR); bytes_consumed += 3; EXPECT_CALL(visitor, OnStreamPadding(1, 100)); QUICHE_CHECK_EQ(100u, deframer_->ProcessInput(frame.data() + bytes_consumed, 100)); QUICHE_CHECK_EQ(deframer_->state(), Http2DecoderAdapter::SPDY_CONSUME_PADDING); QUICHE_CHECK_EQ(deframer_->spdy_framer_error(), Http2DecoderAdapter::SPDY_NO_ERROR); bytes_consumed += 100; EXPECT_CALL(visitor, OnStreamPadding(1, 18)); QUICHE_CHECK_EQ(18u, deframer_->ProcessInput(frame.data() + bytes_consumed, 18)); QUICHE_CHECK_EQ(deframer_->state(), Http2DecoderAdapter::SPDY_READY_FOR_FRAME); QUICHE_CHECK_EQ(deframer_->spdy_framer_error(), Http2DecoderAdapter::SPDY_NO_ERROR); } TEST_P(SpdyFramerTest, ReadWindowUpdate) { SpdySerializedFrame control_frame(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 1, 2))); if (use_output_) { ASSERT_TRUE(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 1, 2), &output_)); control_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_EQ(1u, visitor.last_window_update_stream_); EXPECT_EQ(2, visitor.last_window_update_delta_); } TEST_P(SpdyFramerTest, ReadCompressedPushPromise) { SpdyPushPromiseIR push_promise( 42, 57); push_promise.SetHeader("foo", "bar"); push_promise.SetHeader("bar", "foofoo"); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer_, push_promise, use_output_ ? &output_ : nullptr)); TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size()); EXPECT_EQ(42u, visitor.last_push_promise_stream_); EXPECT_EQ(57u, visitor.last_push_promise_promised_stream_); EXPECT_EQ(push_promise.header_block(), visitor.headers_); } TEST_P(SpdyFramerTest, ReadHeadersWithContinuation) { const unsigned char kInput[] = { 0x00, 0x00, 0x14, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x06, 'c', 'o', 'o', 'k', 'i', 'e', 0x07, 'f', 'o', 'o', '=', 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 'c', 'o', 'o', 'k', 'i', 'e', 0x08, 'b', 'a', 'z', '=', 'b', 'i', 'n', 'g', 0x00, 0x06, 'c', 0x00, 0x00, 0x12, 0x09, 0x04, 0x00, 0x00, 0x00, 0x01, 'o', 'o', 'k', 'i', 'e', 0x00, 0x00, 0x04, 'n', 'a', 'm', 'e', 0x05, 'v', 'a', 'l', 'u', 'e', }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(2, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(0, visitor.end_of_stream_count_); EXPECT_THAT( visitor.headers_, testing::ElementsAre(testing::Pair("cookie", "foo=bar; baz=bing; "), testing::Pair("name", "value"))); } TEST_P(SpdyFramerTest, ReadHeadersWithContinuationAndFin) { const unsigned char kInput[] = { 0x00, 0x00, 0x10, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 'c', 'o', 'o', 'k', 'i', 'e', 0x07, 'f', 'o', 'o', '=', 'b', 'a', 'r', 0x00, 0x00, 0x14, 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 'c', 'o', 'o', 'k', 'i', 'e', 0x08, 'b', 'a', 'z', '=', 'b', 'i', 'n', 'g', 0x00, 0x06, 'c', 0x00, 0x00, 0x12, 0x09, 0x04, 0x00, 0x00, 0x00, 0x01, 'o', 'o', 'k', 'i', 'e', 0x00, 0x00, 0x04, 'n', 'a', 'm', 'e', 0x05, 'v', 'a', 'l', 'u', 'e', }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(2, visitor.continuation_count_); EXPECT_EQ(1, visitor.fin_flag_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(1, visitor.end_of_stream_count_); EXPECT_THAT( visitor.headers_, testing::ElementsAre(testing::Pair("cookie", "foo=bar; baz=bing; "), testing::Pair("name", "value"))); } TEST_P(SpdyFramerTest, ReadPushPromiseWithContinuation) { const unsigned char kInput[] = { 0x00, 0x00, 0x17, 0x05, 0x08, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x06, 'c', 'o', 'o', 'k', 'i', 'e', 0x07, 'f', 'o', 'o', '=', 'b', 'a', 'r', 0x00, 0x00, 0x00, 0x00, 0x14, 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 'c', 'o', 'o', 'k', 'i', 'e', 0x08, 'b', 'a', 'z', '=', 'b', 'i', 'n', 'g', 0x00, 0x06, 'c', 0x00, 0x00, 0x12, 0x09, 0x04, 0x00, 0x00, 0x00, 0x01, 'o', 'o', 'k', 'i', 'e', 0x00, 0x00, 0x04, 'n', 'a', 'm', 'e', 0x05, 'v', 'a', 'l', 'u', 'e', }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1u, visitor.last_push_promise_stream_); EXPECT_EQ(42u, visitor.last_push_promise_promised_stream_); EXPECT_EQ(2, visitor.continuation_count_); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(0, visitor.end_of_stream_count_); EXPECT_THAT( visitor.headers_, testing::ElementsAre(testing::Pair("cookie", "foo=bar; baz=bing; "), testing::Pair("name", "value"))); } TEST_P(SpdyFramerTest, ReceiveUnknownMidContinuation) { const unsigned char kInput[] = { 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, 0x00, 0x00, 0x14, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x08, 0x62, 0x61, 0x7a, 0x3d, 0x62, 0x69, 0x6e, 0x67, 0x00, 0x06, 0x63, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.on_unknown_frame_result_ = true; deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0u, visitor.header_buffer_length_); } TEST_P(SpdyFramerTest, ReceiveUnknownMidContinuationWithExtension) { const unsigned char kInput[] = { 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, 0x00, 0x00, 0x14, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x08, 0x62, 0x61, 0x7a, 0x3d, 0x62, 0x69, 0x6e, 0x67, 0x00, 0x06, 0x63, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); TestExtension extension; visitor.set_extension_visitor(&extension); deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0u, visitor.header_buffer_length_); } TEST_P(SpdyFramerTest, ReceiveContinuationOnWrongStream) { const unsigned char kInput[] = { 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, 0x00, 0x00, 0x14, 0x09, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x08, 0x62, 0x61, 0x7a, 0x3d, 0x62, 0x69, 0x6e, 0x67, 0x00, 0x06, 0x63, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0u, visitor.header_buffer_length_); } TEST_P(SpdyFramerTest, ReadContinuationOutOfOrder) { const unsigned char kInput[] = { 0x00, 0x00, 0x18, 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0u, visitor.header_buffer_length_); } TEST_P(SpdyFramerTest, ExpectContinuationReceiveData) { const unsigned char kInput[] = { 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0xde, 0xad, 0xbe, 0xef, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0u, visitor.header_buffer_length_); EXPECT_EQ(0, visitor.data_frame_count_); } TEST_P(SpdyFramerTest, ExpectContinuationReceiveControlFrame) { const unsigned char kInput[] = { 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x07, 0x66, 0x6f, 0x6f, 0x3d, 0x62, 0x61, 0x72, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kInput, sizeof(kInput)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); EXPECT_EQ(1, visitor.headers_frame_count_); EXPECT_EQ(0, visitor.continuation_count_); EXPECT_EQ(0u, visitor.header_buffer_length_); EXPECT_EQ(0, visitor.data_frame_count_); } TEST_P(SpdyFramerTest, ReadGarbage) { unsigned char garbage_frame[256]; memset(garbage_frame, ~0, sizeof(garbage_frame)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(garbage_frame, sizeof(garbage_frame)); EXPECT_EQ(1, visitor.error_count_); } TEST_P(SpdyFramerTest, ReadUnknownExtensionFrame) { const unsigned char unknown_frame[] = { 0x00, 0x00, 0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.on_unknown_frame_result_ = true; visitor.SimulateInFramer(unknown_frame, ABSL_ARRAYSIZE(unknown_frame)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.unknown_frame_count_); EXPECT_EQ(8, visitor.unknown_payload_len_); SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_HEADER_TABLE_SIZE, 10); SpdySerializedFrame control_frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); control_frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.setting_count_); EXPECT_EQ(1, visitor.settings_ack_sent_); } TEST_P(SpdyFramerTest, ReadUnknownExtensionFrameWithExtension) { const unsigned char unknown_frame[] = { 0x00, 0x00, 0x14, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); TestExtension extension; visitor.set_extension_visitor(&extension); visitor.SimulateInFramer(unknown_frame, ABSL_ARRAYSIZE(unknown_frame)); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(0x7fffffffu, extension.stream_id_); EXPECT_EQ(20u, extension.length_); EXPECT_EQ(255, extension.type_); EXPECT_EQ(0xff, extension.flags_); EXPECT_EQ(std::string(20, '\xff'), extension.payload_); SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_HEADER_TABLE_SIZE, 10); SpdySerializedFrame control_frame(framer_.SerializeSettings(settings_ir)); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data()), control_frame.size()); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.setting_count_); EXPECT_EQ(1, visitor.settings_ack_sent_); } TEST_P(SpdyFramerTest, ReadGarbageWithValidLength) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, ABSL_ARRAYSIZE(kFrameData)); EXPECT_EQ(1, visitor.error_count_); } TEST_P(SpdyFramerTest, ReadGarbageHPACKEncoding) { const unsigned char kInput[] = { 0x00, 0x12, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0xef, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kInput, ABSL_ARRAYSIZE(kInput)); EXPECT_EQ(1, visitor.error_count_); } TEST_P(SpdyFramerTest, SizesTest) { EXPECT_EQ(9u, kFrameHeaderSize); EXPECT_EQ(9u, kDataFrameMinimumSize); EXPECT_EQ(9u, kHeadersFrameMinimumSize); EXPECT_EQ(14u, kPriorityFrameSize); EXPECT_EQ(13u, kRstStreamFrameSize); EXPECT_EQ(9u, kSettingsFrameMinimumSize); EXPECT_EQ(13u, kPushPromiseFrameMinimumSize); EXPECT_EQ(17u, kPingFrameSize); EXPECT_EQ(17u, kGoawayFrameMinimumSize); EXPECT_EQ(13u, kWindowUpdateFrameSize); EXPECT_EQ(9u, kContinuationFrameMinimumSize); EXPECT_EQ(11u, kGetAltSvcFrameMinimumSize); EXPECT_EQ(9u, kFrameMinimumSize); EXPECT_EQ(16384u, kHttp2DefaultFramePayloadLimit); EXPECT_EQ(16393u, kHttp2DefaultFrameSizeLimit); } TEST_P(SpdyFramerTest, StateToStringTest) { EXPECT_STREQ("ERROR", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_ERROR)); EXPECT_STREQ("FRAME_COMPLETE", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_FRAME_COMPLETE)); EXPECT_STREQ("READY_FOR_FRAME", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_READY_FOR_FRAME)); EXPECT_STREQ("READING_COMMON_HEADER", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_READING_COMMON_HEADER)); EXPECT_STREQ("CONTROL_FRAME_PAYLOAD", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_CONTROL_FRAME_PAYLOAD)); EXPECT_STREQ("IGNORE_REMAINING_PAYLOAD", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_IGNORE_REMAINING_PAYLOAD)); EXPECT_STREQ("FORWARD_STREAM_FRAME", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_FORWARD_STREAM_FRAME)); EXPECT_STREQ( "SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK)); EXPECT_STREQ("SPDY_CONTROL_FRAME_HEADER_BLOCK", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_CONTROL_FRAME_HEADER_BLOCK)); EXPECT_STREQ("SPDY_SETTINGS_FRAME_PAYLOAD", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_SETTINGS_FRAME_PAYLOAD)); EXPECT_STREQ("SPDY_ALTSVC_FRAME_PAYLOAD", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_ALTSVC_FRAME_PAYLOAD)); EXPECT_STREQ("UNKNOWN_STATE", Http2DecoderAdapter::StateToString( Http2DecoderAdapter::SPDY_ALTSVC_FRAME_PAYLOAD + 1)); } TEST_P(SpdyFramerTest, SpdyFramerErrorToStringTest) { EXPECT_STREQ("NO_ERROR", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_NO_ERROR)); EXPECT_STREQ("INVALID_STREAM_ID", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_INVALID_STREAM_ID)); EXPECT_STREQ("INVALID_CONTROL_FRAME", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME)); EXPECT_STREQ("CONTROL_PAYLOAD_TOO_LARGE", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_CONTROL_PAYLOAD_TOO_LARGE)); EXPECT_STREQ("DECOMPRESS_FAILURE", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_DECOMPRESS_FAILURE)); EXPECT_STREQ("INVALID_PADDING", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_INVALID_PADDING)); EXPECT_STREQ("INVALID_DATA_FRAME_FLAGS", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_INVALID_DATA_FRAME_FLAGS)); EXPECT_STREQ("UNEXPECTED_FRAME", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME)); EXPECT_STREQ("INTERNAL_FRAMER_ERROR", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_INTERNAL_FRAMER_ERROR)); EXPECT_STREQ("INVALID_CONTROL_FRAME_SIZE", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE)); EXPECT_STREQ("OVERSIZED_PAYLOAD", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD)); EXPECT_STREQ("UNKNOWN_ERROR", Http2DecoderAdapter::SpdyFramerErrorToString( Http2DecoderAdapter::LAST_ERROR)); EXPECT_STREQ("UNKNOWN_ERROR", Http2DecoderAdapter::SpdyFramerErrorToString( static_cast<Http2DecoderAdapter::SpdyFramerError>( Http2DecoderAdapter::LAST_ERROR + 1))); } TEST_P(SpdyFramerTest, DataFrameFlagsV4) { uint8_t valid_data_flags = DATA_FLAG_FIN | DATA_FLAG_PADDED; uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyDataIR data_ir( 1, "hello"); SpdySerializedFrame frame(framer_.SerializeData(data_ir)); SetFrameFlags(&frame, flags); EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x0, flags)); if (flags & ~valid_data_flags) { EXPECT_CALL(visitor, OnError(_, _)); } else { EXPECT_CALL(visitor, OnDataFrameHeader(1, 5, flags & DATA_FLAG_FIN)); if (flags & DATA_FLAG_PADDED) { EXPECT_CALL(visitor, OnStreamPadding(_, 1)); EXPECT_CALL(visitor, OnError(_, _)); } else { EXPECT_CALL(visitor, OnStreamFrameData(_, _, 5)); if (flags & DATA_FLAG_FIN) { EXPECT_CALL(visitor, OnStreamEnd(_)); } } } deframer_->ProcessInput(frame.data(), frame.size()); if (flags & ~valid_data_flags) { EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_DATA_FRAME_FLAGS, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } else if (flags & DATA_FLAG_PADDED) { EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_PADDING, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } else { EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } deframer_ = std::make_unique<Http2DecoderAdapter>(); } while (++flags != 0); } TEST_P(SpdyFramerTest, RstStreamFrameFlags) { uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyRstStreamIR rst_stream( 13, ERROR_CODE_CANCEL); SpdySerializedFrame frame(framer_.SerializeRstStream(rst_stream)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeRstStream(rst_stream, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } SetFrameFlags(&frame, flags); EXPECT_CALL(visitor, OnCommonHeader(13, 4, 0x3, flags)); EXPECT_CALL(visitor, OnRstStream(13, ERROR_CODE_CANCEL)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); deframer_ = std::make_unique<Http2DecoderAdapter>(); } while (++flags != 0); } TEST_P(SpdyFramerTest, SettingsFrameFlags) { uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_INITIAL_WINDOW_SIZE, 16); SpdySerializedFrame frame(framer_.SerializeSettings(settings_ir)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeSettings(settings_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } SetFrameFlags(&frame, flags); EXPECT_CALL(visitor, OnCommonHeader(0, 6, 0x4, flags)); if (flags & SETTINGS_FLAG_ACK) { EXPECT_CALL(visitor, OnError(_, _)); } else { EXPECT_CALL(visitor, OnSettings()); EXPECT_CALL(visitor, OnSetting(SETTINGS_INITIAL_WINDOW_SIZE, 16)); EXPECT_CALL(visitor, OnSettingsEnd()); } deframer_->ProcessInput(frame.data(), frame.size()); if (flags & SETTINGS_FLAG_ACK) { EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } else { EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } deframer_ = std::make_unique<Http2DecoderAdapter>(); } while (++flags != 0); } TEST_P(SpdyFramerTest, GoawayFrameFlags) { uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyGoAwayIR goaway_ir( 97, ERROR_CODE_NO_ERROR, "test"); SpdySerializedFrame frame(framer_.SerializeGoAway(goaway_ir)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializeGoAway(goaway_ir, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } SetFrameFlags(&frame, flags); EXPECT_CALL(visitor, OnCommonHeader(0, _, 0x7, flags)); EXPECT_CALL(visitor, OnGoAway(97, ERROR_CODE_NO_ERROR)); EXPECT_CALL(visitor, OnGoAwayFrameData) .WillRepeatedly(testing::Return(true)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); deframer_ = std::make_unique<Http2DecoderAdapter>(); } while (++flags != 0); } TEST_P(SpdyFramerTest, HeadersFrameFlags) { uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; SpdyFramer framer(SpdyFramer::ENABLE_COMPRESSION); Http2DecoderAdapter deframer; deframer.set_visitor(&visitor); SpdyHeadersIR headers_ir( 57); if (flags & HEADERS_FLAG_PRIORITY) { headers_ir.set_weight(3); headers_ir.set_has_priority(true); headers_ir.set_parent_stream_id(5); headers_ir.set_exclusive(true); } headers_ir.SetHeader("foo", "bar"); SpdySerializedFrame frame(SpdyFramerPeer::SerializeHeaders( &framer, headers_ir, use_output_ ? &output_ : nullptr)); uint8_t set_flags = flags & ~HEADERS_FLAG_PADDED; SetFrameFlags(&frame, set_flags); SpdyStreamId stream_id = 57; bool has_priority = false; int weight = 0; SpdyStreamId parent_stream_id = 0; bool exclusive = false; bool fin = flags & CONTROL_FLAG_FIN; bool end = flags & HEADERS_FLAG_END_HEADERS; if (flags & HEADERS_FLAG_PRIORITY) { has_priority = true; weight = 3; parent_stream_id = 5; exclusive = true; } EXPECT_CALL(visitor, OnCommonHeader(stream_id, _, 0x1, set_flags)); EXPECT_CALL(visitor, OnHeaders(stream_id, _, has_priority, weight, parent_stream_id, exclusive, fin, end)); EXPECT_CALL(visitor, OnHeaderFrameStart(57)).Times(1); if (end) { EXPECT_CALL(visitor, OnHeaderFrameEnd(57)).Times(1); } if (flags & DATA_FLAG_FIN && end) { EXPECT_CALL(visitor, OnStreamEnd(_)); } else { EXPECT_CALL(visitor, OnStreamEnd(_)).Times(0); } deframer.ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer.spdy_framer_error()); } while (++flags != 0); } TEST_P(SpdyFramerTest, PingFrameFlags) { uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdySerializedFrame frame(framer_.SerializePing(SpdyPingIR(42))); SetFrameFlags(&frame, flags); EXPECT_CALL(visitor, OnCommonHeader(0, 8, 0x6, flags)); EXPECT_CALL(visitor, OnPing(42, flags & PING_FLAG_ACK)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); deframer_ = std::make_unique<Http2DecoderAdapter>(); } while (++flags != 0); } TEST_P(SpdyFramerTest, WindowUpdateFrameFlags) { uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdySerializedFrame frame(framer_.SerializeWindowUpdate( SpdyWindowUpdateIR( 4, 1024))); SetFrameFlags(&frame, flags); EXPECT_CALL(visitor, OnCommonHeader(4, 4, 0x8, flags)); EXPECT_CALL(visitor, OnWindowUpdate(4, 1024)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); deframer_ = std::make_unique<Http2DecoderAdapter>(); } while (++flags != 0); } TEST_P(SpdyFramerTest, PushPromiseFrameFlags) { const SpdyStreamId client_id = 123; const SpdyStreamId promised_id = 22; uint8_t flags = 0; do { SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; testing::StrictMock<test::MockDebugVisitor> debug_visitor; SpdyFramer framer(SpdyFramer::ENABLE_COMPRESSION); Http2DecoderAdapter deframer; deframer.set_visitor(&visitor); deframer.set_debug_visitor(&debug_visitor); framer.set_debug_visitor(&debug_visitor); EXPECT_CALL( debug_visitor, OnSendCompressedFrame(client_id, SpdyFrameType::PUSH_PROMISE, _, _)); SpdyPushPromiseIR push_promise(client_id, promised_id); push_promise.SetHeader("foo", "bar"); SpdySerializedFrame frame(SpdyFramerPeer::SerializePushPromise( &framer, push_promise, use_output_ ? &output_ : nullptr)); SetFrameFlags(&frame, flags & ~HEADERS_FLAG_PADDED); bool end = flags & PUSH_PROMISE_FLAG_END_PUSH_PROMISE; EXPECT_CALL(debug_visitor, OnReceiveCompressedFrame( client_id, SpdyFrameType::PUSH_PROMISE, _)); EXPECT_CALL(visitor, OnCommonHeader(client_id, _, 0x5, flags & ~HEADERS_FLAG_PADDED)); EXPECT_CALL(visitor, OnPushPromise(client_id, promised_id, end)); EXPECT_CALL(visitor, OnHeaderFrameStart(client_id)).Times(1); if (end) { EXPECT_CALL(visitor, OnHeaderFrameEnd(client_id)).Times(1); } deframer.ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer.spdy_framer_error()); } while (++flags != 0); } TEST_P(SpdyFramerTest, ContinuationFrameFlags) { uint8_t flags = 0; do { if (use_output_) { output_.Reset(); } SCOPED_TRACE(testing::Message() << "Flags " << std::hex << static_cast<int>(flags)); testing::StrictMock<test::MockSpdyFramerVisitor> visitor; testing::StrictMock<test::MockDebugVisitor> debug_visitor; SpdyFramer framer(SpdyFramer::ENABLE_COMPRESSION); Http2DecoderAdapter deframer; deframer.set_visitor(&visitor); deframer.set_debug_visitor(&debug_visitor); framer.set_debug_visitor(&debug_visitor); EXPECT_CALL(debug_visitor, OnSendCompressedFrame(42, SpdyFrameType::HEADERS, _, _)); EXPECT_CALL(debug_visitor, OnReceiveCompressedFrame(42, SpdyFrameType::HEADERS, _)); EXPECT_CALL(visitor, OnCommonHeader(42, _, 0x1, 0)); EXPECT_CALL(visitor, OnHeaders(42, _, false, 0, 0, false, false, false)); EXPECT_CALL(visitor, OnHeaderFrameStart(42)).Times(1); SpdyHeadersIR headers_ir( 42); headers_ir.SetHeader("foo", "bar"); SpdySerializedFrame frame0; if (use_output_) { EXPECT_TRUE(framer.SerializeHeaders(headers_ir, &output_)); frame0 = MakeSerializedFrame(output_.Begin(), output_.Size()); } else { frame0 = framer.SerializeHeaders(headers_ir); } SetFrameFlags(&frame0, 0); SpdyContinuationIR continuation( 42); SpdySerializedFrame frame1; if (use_output_) { char* begin = output_.Begin() + output_.Size(); ASSERT_TRUE(framer.SerializeContinuation(continuation, &output_)); frame1 = MakeSerializedFrame(begin, output_.Size() - frame0.size()); } else { frame1 = framer.SerializeContinuation(continuation); } SetFrameFlags(&frame1, flags); EXPECT_CALL(debug_visitor, OnReceiveCompressedFrame(42, SpdyFrameType::CONTINUATION, _)); EXPECT_CALL(visitor, OnCommonHeader(42, _, 0x9, flags)); EXPECT_CALL(visitor, OnContinuation(42, _, flags & HEADERS_FLAG_END_HEADERS)); bool end = flags & HEADERS_FLAG_END_HEADERS; if (end) { EXPECT_CALL(visitor, OnHeaderFrameEnd(42)).Times(1); } deframer.ProcessInput(frame0.data(), frame0.size()); deframer.ProcessInput(frame1.data(), frame1.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer.spdy_framer_error()); } while (++flags != 0); } TEST_P(SpdyFramerTest, RstStreamStatusBounds) { const unsigned char kH2RstStreamInvalid[] = { 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; const unsigned char kH2RstStreamNumStatusCodes[] = { 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(1, 4, 0x3, 0x0)); EXPECT_CALL(visitor, OnRstStream(1, ERROR_CODE_NO_ERROR)); deframer_->ProcessInput(reinterpret_cast<const char*>(kH2RstStreamInvalid), ABSL_ARRAYSIZE(kH2RstStreamInvalid)); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); deframer_ = std::make_unique<Http2DecoderAdapter>(); deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(1, 4, 0x3, 0x0)); EXPECT_CALL(visitor, OnRstStream(1, ERROR_CODE_INTERNAL_ERROR)); deframer_->ProcessInput( reinterpret_cast<const char*>(kH2RstStreamNumStatusCodes), ABSL_ARRAYSIZE(kH2RstStreamNumStatusCodes)); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, GoAwayStatusBounds) { const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x0a, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0x47, 0x41, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 10, 0x7, 0x0)); EXPECT_CALL(visitor, OnGoAway(1, ERROR_CODE_INTERNAL_ERROR)); EXPECT_CALL(visitor, OnGoAwayFrameData).WillRepeatedly(testing::Return(true)); deframer_->ProcessInput(reinterpret_cast<const char*>(kH2FrameData), ABSL_ARRAYSIZE(kH2FrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, GoAwayStreamIdBounds) { const unsigned char kH2FrameData[] = { 0x00, 0x00, 0x08, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 8, 0x7, 0x0)); EXPECT_CALL(visitor, OnGoAway(0x7fffffff, ERROR_CODE_NO_ERROR)); EXPECT_CALL(visitor, OnGoAwayFrameData).WillRepeatedly(testing::Return(true)); deframer_->ProcessInput(reinterpret_cast<const char*>(kH2FrameData), ABSL_ARRAYSIZE(kH2FrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, OnAltSvcWithOrigin) { const SpdyStreamId kStreamId = 0; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyAltSvcWireFormat::AlternativeService altsvc1( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector()); SpdyAltSvcWireFormat::AlternativeService altsvc2( "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24}); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; altsvc_vector.push_back(altsvc1); altsvc_vector.push_back(altsvc2); EXPECT_CALL(visitor, OnCommonHeader(kStreamId, _, 0x0A, 0x0)); EXPECT_CALL(visitor, OnAltSvc(kStreamId, absl::string_view("o_r|g!n"), altsvc_vector)); SpdyAltSvcIR altsvc_ir(kStreamId); altsvc_ir.set_origin("o_r|g!n"); altsvc_ir.add_altsvc(altsvc1); altsvc_ir.add_altsvc(altsvc2); SpdySerializedFrame frame(framer_.SerializeFrame(altsvc_ir)); if (use_output_) { output_.Reset(); EXPECT_EQ(framer_.SerializeFrame(altsvc_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, OnAltSvcNoOrigin) { const SpdyStreamId kStreamId = 1; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); SpdyAltSvcWireFormat::AlternativeService altsvc1( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector()); SpdyAltSvcWireFormat::AlternativeService altsvc2( "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24}); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; altsvc_vector.push_back(altsvc1); altsvc_vector.push_back(altsvc2); EXPECT_CALL(visitor, OnCommonHeader(kStreamId, _, 0x0A, 0x0)); EXPECT_CALL(visitor, OnAltSvc(kStreamId, absl::string_view(""), altsvc_vector)); SpdyAltSvcIR altsvc_ir(kStreamId); altsvc_ir.add_altsvc(altsvc1); altsvc_ir.add_altsvc(altsvc2); SpdySerializedFrame frame(framer_.SerializeFrame(altsvc_ir)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, OnAltSvcEmptyProtocolId) { const SpdyStreamId kStreamId = 0; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(kStreamId, _, 0x0A, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, _)); SpdyAltSvcIR altsvc_ir(kStreamId); altsvc_ir.set_origin("o1"); altsvc_ir.add_altsvc(SpdyAltSvcWireFormat::AlternativeService( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector())); altsvc_ir.add_altsvc(SpdyAltSvcWireFormat::AlternativeService( "", "h1", 443, 10, SpdyAltSvcWireFormat::VersionVector())); SpdySerializedFrame frame(framer_.SerializeFrame(altsvc_ir)); if (use_output_) { output_.Reset(); EXPECT_EQ(framer_.SerializeFrame(altsvc_ir, &output_), frame.size()); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, OnAltSvcBadLengths) { const unsigned char kType = SerializeFrameType(SpdyFrameType::ALTSVC); const unsigned char kFrameDataOriginLenLargerThanFrame[] = { 0x00, 0x00, 0x05, kType, 0x00, 0x00, 0x00, 0x00, 0x03, 0x42, 0x42, 'f', 'o', 'o', }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); deframer_->set_visitor(&visitor); visitor.SimulateInFramer(kFrameDataOriginLenLargerThanFrame, sizeof(kFrameDataOriginLenLargerThanFrame)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadChunkedAltSvcFrame) { SpdyAltSvcIR altsvc_ir( 1); SpdyAltSvcWireFormat::AlternativeService altsvc1( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector()); SpdyAltSvcWireFormat::AlternativeService altsvc2( "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24}); altsvc_ir.add_altsvc(altsvc1); altsvc_ir.add_altsvc(altsvc2); SpdySerializedFrame control_frame(framer_.SerializeAltSvc(altsvc_ir)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); size_t framed_data = 0; size_t unframed_data = control_frame.size(); size_t kReadChunkSize = 5; while (unframed_data > 0) { size_t to_read = std::min(kReadChunkSize, unframed_data); visitor.SimulateInFramer( reinterpret_cast<unsigned char*>(control_frame.data() + framed_data), to_read); unframed_data -= to_read; framed_data += to_read; } EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.altsvc_count_); ASSERT_NE(nullptr, visitor.test_altsvc_ir_); ASSERT_EQ(2u, visitor.test_altsvc_ir_->altsvc_vector().size()); EXPECT_TRUE(visitor.test_altsvc_ir_->altsvc_vector()[0] == altsvc1); EXPECT_TRUE(visitor.test_altsvc_ir_->altsvc_vector()[1] == altsvc2); } TEST_P(SpdyFramerTest, ReadAltSvcFrame) { constexpr struct { uint32_t stream_id; const char* origin; } test_cases[] = {{0, ""}, {1, ""}, {0, "https: {1, "https: for (const auto& test_case : test_cases) { SpdyAltSvcIR altsvc_ir(test_case.stream_id); SpdyAltSvcWireFormat::AlternativeService altsvc( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector()); altsvc_ir.add_altsvc(altsvc); altsvc_ir.set_origin(test_case.origin); SpdySerializedFrame frame(framer_.SerializeAltSvc(altsvc_ir)); TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); deframer_->set_visitor(&visitor); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(0, visitor.error_count_); EXPECT_EQ(1, visitor.altsvc_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } } TEST_P(SpdyFramerTest, ErrorOnAltSvcFrameWithInvalidValue) { const char kFrameData[] = { 0x00, 0x00, 0x16, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x74, 0x68, 0x69, 0x73, 0x69, 0x73, 0x6e, 0x6f, 0x74, 0x61, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x76, 0x61, 0x6c, 0x75, 0x65, }; TestSpdyVisitor visitor(SpdyFramer::ENABLE_COMPRESSION); deframer_->set_visitor(&visitor); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_EQ(1, visitor.error_count_); EXPECT_EQ(0, visitor.altsvc_count_); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadPriorityUpdateFrame) { const char kFrameData[] = { 0x00, 0x00, 0x07, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 'f', 'o', 'o' }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 7, 0x10, 0x0)); EXPECT_CALL(visitor, OnPriorityUpdate(3, "foo")); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_FALSE(deframer_->HasError()); } TEST_P(SpdyFramerTest, ReadPriorityUpdateFrameWithEmptyPriorityFieldValue) { const char kFrameData[] = { 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 4, 0x10, 0x0)); EXPECT_CALL(visitor, OnPriorityUpdate(3, "")); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_FALSE(deframer_->HasError()); } TEST_P(SpdyFramerTest, PriorityUpdateFrameWithEmptyPayload) { const char kFrameData[] = { 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 0, 0x10, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, _)); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_TRUE(deframer_->HasError()); } TEST_P(SpdyFramerTest, PriorityUpdateFrameWithShortPayload) { const char kFrameData[] = { 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 2, 0x10, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, _)); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_TRUE(deframer_->HasError()); } TEST_P(SpdyFramerTest, PriorityUpdateFrameOnIncorrectStream) { const char kFrameData[] = { 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(1, 4, 0x10, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_TRUE(deframer_->HasError()); } TEST_P(SpdyFramerTest, PriorityUpdateFramePrioritizingIncorrectStream) { const char kFrameData[] = { 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(0, 4, 0x10, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_STREAM_ID, _)); deframer_->ProcessInput(kFrameData, sizeof(kFrameData)); EXPECT_TRUE(deframer_->HasError()); } TEST_P(SpdyFramerTest, ReadPriority) { SpdyPriorityIR priority( 3, 1, 256, false); SpdySerializedFrame frame(framer_.SerializePriority(priority)); if (use_output_) { output_.Reset(); ASSERT_TRUE(framer_.SerializePriority(priority, &output_)); frame = MakeSerializedFrame(output_.Begin(), output_.Size()); } testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); EXPECT_CALL(visitor, OnCommonHeader(3, 5, 0x2, 0x0)); EXPECT_CALL(visitor, OnPriority(3, 1, 256, false)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_NO_ERROR, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadIncorrectlySizedPriority) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, sizeof(kFrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, visitor.deframer_.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadIncorrectlySizedPing) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x04, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, sizeof(kFrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, visitor.deframer_.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadIncorrectlySizedWindowUpdate) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x01, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, sizeof(kFrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, visitor.deframer_.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadIncorrectlySizedRstStream) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x01, }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, sizeof(kFrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, visitor.deframer_.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ReadInvalidRstStreamWithPayload) { const unsigned char kFrameData[] = { 0x00, 0x00, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 'f', 'o', 'o' }; TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(kFrameData, sizeof(kFrameData)); EXPECT_EQ(Http2DecoderAdapter::SPDY_ERROR, visitor.deframer_.state()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE, visitor.deframer_.spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( visitor.deframer_.spdy_framer_error()); } TEST_P(SpdyFramerTest, ProcessAllInput) { auto visitor = std::make_unique<TestSpdyVisitor>(SpdyFramer::DISABLE_COMPRESSION); deframer_->set_visitor(visitor.get()); SpdyHeadersIR headers( 1); headers.SetHeader("alpha", "beta"); headers.SetHeader("gamma", "charlie"); headers.SetHeader("cookie", "key1=value1; key2=value2"); SpdySerializedFrame headers_frame(SpdyFramerPeer::SerializeHeaders( &framer_, headers, use_output_ ? &output_ : nullptr)); const char four_score[] = "Four score and seven years ago"; SpdyDataIR four_score_ir( 1, four_score); SpdySerializedFrame four_score_frame(framer_.SerializeData(four_score_ir)); SpdySerializedFrame frame1 = std::move(headers_frame); SpdySerializedFrame frame2 = std::move(four_score_frame); const size_t frame1_size = frame1.size(); const size_t frame2_size = frame2.size(); QUICHE_VLOG(1) << "frame1_size = " << frame1_size; QUICHE_VLOG(1) << "frame2_size = " << frame2_size; std::string input_buffer; input_buffer.append(frame1.data(), frame1_size); input_buffer.append(frame2.data(), frame2_size); const char* buf = input_buffer.data(); const size_t buf_size = input_buffer.size(); QUICHE_VLOG(1) << "buf_size = " << buf_size; size_t processed = deframer_->ProcessInput(buf, buf_size); EXPECT_EQ(buf_size, processed); EXPECT_EQ(Http2DecoderAdapter::SPDY_READY_FOR_FRAME, deframer_->state()); EXPECT_EQ(1, visitor->headers_frame_count_); EXPECT_EQ(1, visitor->data_frame_count_); EXPECT_EQ(strlen(four_score), static_cast<unsigned>(visitor->data_bytes_)); } namespace { void CheckFrameAndIRSize(SpdyFrameIR* ir, SpdyFramer* framer, ArrayOutputBuffer* array_output_buffer) { array_output_buffer->Reset(); SpdyFrameType type = ir->frame_type(); size_t ir_size = ir->size(); framer->SerializeFrame(*ir, array_output_buffer); if (type == SpdyFrameType::HEADERS || type == SpdyFrameType::PUSH_PROMISE) { EXPECT_GE(ir_size, array_output_buffer->Size() * 9 / 10); EXPECT_LT(ir_size, array_output_buffer->Size() * 11 / 10); } else { EXPECT_EQ(ir_size, array_output_buffer->Size()); } } } TEST_P(SpdyFramerTest, SpdyFrameIRSize) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const char bytes[] = "this is a very short data frame"; SpdyDataIR data_ir(1, absl::string_view(bytes, ABSL_ARRAYSIZE(bytes))); CheckFrameAndIRSize(&data_ir, &framer, &output_); SpdyRstStreamIR rst_ir( 1, ERROR_CODE_PROTOCOL_ERROR); CheckFrameAndIRSize(&rst_ir, &framer, &output_); SpdySettingsIR settings_ir; settings_ir.AddSetting(SETTINGS_HEADER_TABLE_SIZE, 5); settings_ir.AddSetting(SETTINGS_ENABLE_PUSH, 6); settings_ir.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, 7); CheckFrameAndIRSize(&settings_ir, &framer, &output_); SpdyPingIR ping_ir(42); CheckFrameAndIRSize(&ping_ir, &framer, &output_); SpdyGoAwayIR goaway_ir(97, ERROR_CODE_NO_ERROR, "Goaway description"); CheckFrameAndIRSize(&goaway_ir, &framer, &output_); SpdyHeadersIR headers_ir(1); headers_ir.SetHeader("alpha", "beta"); headers_ir.SetHeader("gamma", "charlie"); headers_ir.SetHeader("cookie", "key1=value1; key2=value2"); CheckFrameAndIRSize(&headers_ir, &framer, &output_); SpdyHeadersIR headers_ir_with_continuation(1); headers_ir_with_continuation.SetHeader("alpha", std::string(100000, 'x')); headers_ir_with_continuation.SetHeader("beta", std::string(100000, 'x')); headers_ir_with_continuation.SetHeader("cookie", "key1=value1; key2=value2"); CheckFrameAndIRSize(&headers_ir_with_continuation, &framer, &output_); SpdyWindowUpdateIR window_update_ir(4, 1024); CheckFrameAndIRSize(&window_update_ir, &framer, &output_); SpdyPushPromiseIR push_promise_ir(3, 8); push_promise_ir.SetHeader("alpha", std::string(100000, 'x')); push_promise_ir.SetHeader("beta", std::string(100000, 'x')); push_promise_ir.SetHeader("cookie", "key1=value1; key2=value2"); CheckFrameAndIRSize(&push_promise_ir, &framer, &output_); SpdyAltSvcWireFormat::AlternativeService altsvc1( "pid1", "host", 443, 5, SpdyAltSvcWireFormat::VersionVector()); SpdyAltSvcWireFormat::AlternativeService altsvc2( "p\"=i:d", "h_\\o\"st", 123, 42, SpdyAltSvcWireFormat::VersionVector{24}); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; altsvc_vector.push_back(altsvc1); altsvc_vector.push_back(altsvc2); SpdyAltSvcIR altsvc_ir(0); altsvc_ir.set_origin("o_r|g!n"); altsvc_ir.add_altsvc(altsvc1); altsvc_ir.add_altsvc(altsvc2); CheckFrameAndIRSize(&altsvc_ir, &framer, &output_); SpdyPriorityIR priority_ir(3, 1, 256, false); CheckFrameAndIRSize(&priority_ir, &framer, &output_); const char kDescription[] = "Unknown frame"; const uint8_t kType = 0xaf; const uint8_t kFlags = 0x11; SpdyUnknownIR unknown_ir(2, kType, kFlags, kDescription); CheckFrameAndIRSize(&unknown_ir, &framer, &output_); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_framer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_framer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a440b6ec-0039-4608-bdc9-1f4f65da6810
cpp
google/quiche
spdy_frame_builder
quiche/http2/core/spdy_frame_builder.cc
quiche/http2/core/spdy_frame_builder_test.cc
#include "quiche/http2/core/spdy_frame_builder.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include "absl/strings/string_view.h" #include "quiche/http2/core/spdy_bitmasks.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/core/zero_copy_output_buffer.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { SpdyFrameBuilder::SpdyFrameBuilder(size_t size) : buffer_(new char[size]), capacity_(size), length_(0), offset_(0) {} SpdyFrameBuilder::SpdyFrameBuilder(size_t size, ZeroCopyOutputBuffer* output) : buffer_(output == nullptr ? new char[size] : nullptr), output_(output), capacity_(size), length_(0), offset_(0) {} SpdyFrameBuilder::~SpdyFrameBuilder() = default; char* SpdyFrameBuilder::GetWritableBuffer(size_t length) { if (!CanWrite(length)) { return nullptr; } return buffer_.get() + offset_ + length_; } char* SpdyFrameBuilder::GetWritableOutput(size_t length, size_t* actual_length) { char* dest = nullptr; int size = 0; if (!CanWrite(length)) { return nullptr; } output_->Next(&dest, &size); *actual_length = std::min<size_t>(length, size); return dest; } bool SpdyFrameBuilder::Seek(size_t length) { if (!CanWrite(length)) { return false; } if (output_ == nullptr) { length_ += length; } else { output_->AdvanceWritePtr(length); length_ += length; } return true; } bool SpdyFrameBuilder::BeginNewFrame(SpdyFrameType type, uint8_t flags, SpdyStreamId stream_id) { uint8_t raw_frame_type = SerializeFrameType(type); QUICHE_DCHECK(IsDefinedFrameType(raw_frame_type)); QUICHE_DCHECK_EQ(0u, stream_id & ~kStreamIdMask); bool success = true; if (length_ > 0) { QUICHE_BUG(spdy_bug_73_1) << "SpdyFrameBuilder doesn't have a clean state when BeginNewFrame" << "is called. Leftover length_ is " << length_; offset_ += length_; length_ = 0; } success &= WriteUInt24(capacity_ - offset_ - kFrameHeaderSize); success &= WriteUInt8(raw_frame_type); success &= WriteUInt8(flags); success &= WriteUInt32(stream_id); QUICHE_DCHECK_EQ(kDataFrameMinimumSize, length_); return success; } bool SpdyFrameBuilder::BeginNewFrame(SpdyFrameType type, uint8_t flags, SpdyStreamId stream_id, size_t length) { uint8_t raw_frame_type = SerializeFrameType(type); QUICHE_DCHECK(IsDefinedFrameType(raw_frame_type)); QUICHE_DCHECK_EQ(0u, stream_id & ~kStreamIdMask); QUICHE_BUG_IF(spdy_bug_73_2, length > kSpdyMaxFrameSizeLimit) << "Frame length " << length << " is longer than frame size limit."; return BeginNewFrameInternal(raw_frame_type, flags, stream_id, length); } bool SpdyFrameBuilder::BeginNewUncheckedFrame(uint8_t raw_frame_type, uint8_t flags, SpdyStreamId stream_id, size_t length) { return BeginNewFrameInternal(raw_frame_type, flags, stream_id, length); } bool SpdyFrameBuilder::BeginNewFrameInternal(uint8_t raw_frame_type, uint8_t flags, SpdyStreamId stream_id, size_t length) { QUICHE_DCHECK_EQ(length, length & kLengthMask); bool success = true; offset_ += length_; length_ = 0; success &= WriteUInt24(length); success &= WriteUInt8(raw_frame_type); success &= WriteUInt8(flags); success &= WriteUInt32(stream_id); QUICHE_DCHECK_EQ(kDataFrameMinimumSize, length_); return success; } bool SpdyFrameBuilder::WriteStringPiece32(const absl::string_view value) { if (!WriteUInt32(value.size())) { return false; } return WriteBytes(value.data(), value.size()); } bool SpdyFrameBuilder::WriteBytes(const void* data, uint32_t data_len) { if (!CanWrite(data_len)) { return false; } if (output_ == nullptr) { char* dest = GetWritableBuffer(data_len); memcpy(dest, data, data_len); Seek(data_len); } else { char* dest = nullptr; size_t size = 0; size_t total_written = 0; const char* data_ptr = reinterpret_cast<const char*>(data); while (data_len > 0) { dest = GetWritableOutput(data_len, &size); if (dest == nullptr || size == 0) { return false; } uint32_t to_copy = std::min<uint32_t>(data_len, size); const char* src = data_ptr + total_written; memcpy(dest, src, to_copy); Seek(to_copy); data_len -= to_copy; total_written += to_copy; } } return true; } bool SpdyFrameBuilder::CanWrite(size_t length) const { if (length > kLengthMask) { QUICHE_DCHECK(false); return false; } if (output_ == nullptr) { if (offset_ + length_ + length > capacity_) { QUICHE_DLOG(FATAL) << "Requested: " << length << " capacity: " << capacity_ << " used: " << offset_ + length_; return false; } } else { if (length > output_->BytesFree()) { return false; } } return true; } }
#include "quiche/http2/core/spdy_frame_builder.h" #include <cstddef> #include <cstdint> #include <cstring> #include "absl/strings/string_view.h" #include "quiche/http2/core/array_output_buffer.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/test_tools/spdy_test_utils.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace test { class QUICHE_EXPORT SpdyFrameBuilderPeer { public: static char* GetWritableBuffer(SpdyFrameBuilder* builder, size_t length) { return builder->GetWritableBuffer(length); } static char* GetWritableOutput(SpdyFrameBuilder* builder, size_t desired_length, size_t* actual_length) { return builder->GetWritableOutput(desired_length, actual_length); } }; namespace { const int64_t kSize = 64 * 1024; char output_buffer[kSize] = ""; } TEST(SpdyFrameBuilderTest, GetWritableBuffer) { const size_t kBuilderSize = 10; SpdyFrameBuilder builder(kBuilderSize); char* writable_buffer = SpdyFrameBuilderPeer::GetWritableBuffer(&builder, kBuilderSize); memset(writable_buffer, ~1, kBuilderSize); EXPECT_TRUE(builder.Seek(kBuilderSize)); SpdySerializedFrame frame(builder.take()); char expected[kBuilderSize]; memset(expected, ~1, kBuilderSize); EXPECT_EQ(absl::string_view(expected, kBuilderSize), frame); } TEST(SpdyFrameBuilderTest, GetWritableOutput) { ArrayOutputBuffer output(output_buffer, kSize); const size_t kBuilderSize = 10; SpdyFrameBuilder builder(kBuilderSize, &output); size_t actual_size = 0; char* writable_buffer = SpdyFrameBuilderPeer::GetWritableOutput( &builder, kBuilderSize, &actual_size); memset(writable_buffer, ~1, kBuilderSize); EXPECT_TRUE(builder.Seek(kBuilderSize)); SpdySerializedFrame frame = MakeSerializedFrame(output.Begin(), kBuilderSize); char expected[kBuilderSize]; memset(expected, ~1, kBuilderSize); EXPECT_EQ(absl::string_view(expected, kBuilderSize), frame); } TEST(SpdyFrameBuilderTest, GetWritableOutputNegative) { size_t small_cap = 1; ArrayOutputBuffer output(output_buffer, small_cap); const size_t kBuilderSize = 10; SpdyFrameBuilder builder(kBuilderSize, &output); size_t actual_size = 0; char* writable_buffer = SpdyFrameBuilderPeer::GetWritableOutput( &builder, kBuilderSize, &actual_size); EXPECT_EQ(0u, actual_size); EXPECT_EQ(nullptr, writable_buffer); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_frame_builder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_frame_builder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e80839a8-1faa-4935-8730-513eb511a49b
cpp
google/quiche
spdy_protocol
quiche/http2/core/spdy_protocol.cc
quiche/http2/core/spdy_protocol_test.cc
#include "quiche/http2/core/spdy_protocol.h" #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <ostream> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/http2/core/spdy_alt_svc_wire_format.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { const char* const kHttp2ConnectionHeaderPrefix = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; std::ostream& operator<<(std::ostream& out, SpdyKnownSettingsId id) { return out << static_cast<SpdySettingsId>(id); } std::ostream& operator<<(std::ostream& out, SpdyFrameType frame_type) { return out << SerializeFrameType(frame_type); } SpdyPriority ClampSpdy3Priority(SpdyPriority priority) { static_assert(std::numeric_limits<SpdyPriority>::min() == kV3HighestPriority, "The value of given priority shouldn't be smaller than highest " "priority. Check this invariant explicitly."); if (priority > kV3LowestPriority) { QUICHE_BUG(spdy_bug_22_1) << "Invalid priority: " << static_cast<int>(priority); return kV3LowestPriority; } return priority; } int ClampHttp2Weight(int weight) { if (weight < kHttp2MinStreamWeight) { QUICHE_BUG(spdy_bug_22_2) << "Invalid weight: " << weight; return kHttp2MinStreamWeight; } if (weight > kHttp2MaxStreamWeight) { QUICHE_BUG(spdy_bug_22_3) << "Invalid weight: " << weight; return kHttp2MaxStreamWeight; } return weight; } int Spdy3PriorityToHttp2Weight(SpdyPriority priority) { priority = ClampSpdy3Priority(priority); const float kSteps = 255.9f / 7.f; return static_cast<int>(kSteps * (7.f - priority)) + 1; } SpdyPriority Http2WeightToSpdy3Priority(int weight) { weight = ClampHttp2Weight(weight); const float kSteps = 255.9f / 7.f; return static_cast<SpdyPriority>(7.f - (weight - 1) / kSteps); } bool IsDefinedFrameType(uint8_t frame_type_field) { switch (static_cast<SpdyFrameType>(frame_type_field)) { case SpdyFrameType::DATA: return true; case SpdyFrameType::HEADERS: return true; case SpdyFrameType::PRIORITY: return true; case SpdyFrameType::RST_STREAM: return true; case SpdyFrameType::SETTINGS: return true; case SpdyFrameType::PUSH_PROMISE: return true; case SpdyFrameType::PING: return true; case SpdyFrameType::GOAWAY: return true; case SpdyFrameType::WINDOW_UPDATE: return true; case SpdyFrameType::CONTINUATION: return true; case SpdyFrameType::ALTSVC: return true; case SpdyFrameType::PRIORITY_UPDATE: return true; case SpdyFrameType::ACCEPT_CH: return true; } return false; } SpdyFrameType ParseFrameType(uint8_t frame_type_field) { QUICHE_BUG_IF(spdy_bug_22_4, !IsDefinedFrameType(frame_type_field)) << "Frame type not defined: " << static_cast<int>(frame_type_field); return static_cast<SpdyFrameType>(frame_type_field); } uint8_t SerializeFrameType(SpdyFrameType frame_type) { return static_cast<uint8_t>(frame_type); } bool IsValidHTTP2FrameStreamId(SpdyStreamId current_frame_stream_id, SpdyFrameType frame_type_field) { if (current_frame_stream_id == 0) { switch (frame_type_field) { case SpdyFrameType::DATA: case SpdyFrameType::HEADERS: case SpdyFrameType::PRIORITY: case SpdyFrameType::RST_STREAM: case SpdyFrameType::CONTINUATION: case SpdyFrameType::PUSH_PROMISE: return false; default: return true; } } else { switch (frame_type_field) { case SpdyFrameType::GOAWAY: case SpdyFrameType::SETTINGS: case SpdyFrameType::PING: return false; default: return true; } } } const char* FrameTypeToString(SpdyFrameType frame_type) { switch (frame_type) { case SpdyFrameType::DATA: return "DATA"; case SpdyFrameType::RST_STREAM: return "RST_STREAM"; case SpdyFrameType::SETTINGS: return "SETTINGS"; case SpdyFrameType::PING: return "PING"; case SpdyFrameType::GOAWAY: return "GOAWAY"; case SpdyFrameType::HEADERS: return "HEADERS"; case SpdyFrameType::WINDOW_UPDATE: return "WINDOW_UPDATE"; case SpdyFrameType::PUSH_PROMISE: return "PUSH_PROMISE"; case SpdyFrameType::CONTINUATION: return "CONTINUATION"; case SpdyFrameType::PRIORITY: return "PRIORITY"; case SpdyFrameType::ALTSVC: return "ALTSVC"; case SpdyFrameType::PRIORITY_UPDATE: return "PRIORITY_UPDATE"; case SpdyFrameType::ACCEPT_CH: return "ACCEPT_CH"; } return "UNKNOWN_FRAME_TYPE"; } bool ParseSettingsId(SpdySettingsId wire_setting_id, SpdyKnownSettingsId* setting_id) { if (wire_setting_id != SETTINGS_EXPERIMENT_SCHEDULER && (wire_setting_id < SETTINGS_MIN || wire_setting_id > SETTINGS_MAX)) { return false; } *setting_id = static_cast<SpdyKnownSettingsId>(wire_setting_id); switch (*setting_id) { case SETTINGS_HEADER_TABLE_SIZE: case SETTINGS_ENABLE_PUSH: case SETTINGS_MAX_CONCURRENT_STREAMS: case SETTINGS_INITIAL_WINDOW_SIZE: case SETTINGS_MAX_FRAME_SIZE: case SETTINGS_MAX_HEADER_LIST_SIZE: case SETTINGS_ENABLE_CONNECT_PROTOCOL: case SETTINGS_DEPRECATE_HTTP2_PRIORITIES: case SETTINGS_EXPERIMENT_SCHEDULER: return true; } return false; } std::string SettingsIdToString(SpdySettingsId id) { SpdyKnownSettingsId known_id; if (!ParseSettingsId(id, &known_id)) { return absl::StrCat("SETTINGS_UNKNOWN_", absl::Hex(uint32_t{id})); } switch (known_id) { case SETTINGS_HEADER_TABLE_SIZE: return "SETTINGS_HEADER_TABLE_SIZE"; case SETTINGS_ENABLE_PUSH: return "SETTINGS_ENABLE_PUSH"; case SETTINGS_MAX_CONCURRENT_STREAMS: return "SETTINGS_MAX_CONCURRENT_STREAMS"; case SETTINGS_INITIAL_WINDOW_SIZE: return "SETTINGS_INITIAL_WINDOW_SIZE"; case SETTINGS_MAX_FRAME_SIZE: return "SETTINGS_MAX_FRAME_SIZE"; case SETTINGS_MAX_HEADER_LIST_SIZE: return "SETTINGS_MAX_HEADER_LIST_SIZE"; case SETTINGS_ENABLE_CONNECT_PROTOCOL: return "SETTINGS_ENABLE_CONNECT_PROTOCOL"; case SETTINGS_DEPRECATE_HTTP2_PRIORITIES: return "SETTINGS_DEPRECATE_HTTP2_PRIORITIES"; case SETTINGS_EXPERIMENT_SCHEDULER: return "SETTINGS_EXPERIMENT_SCHEDULER"; } return absl::StrCat("SETTINGS_UNKNOWN_", absl::Hex(uint32_t{id})); } SpdyErrorCode ParseErrorCode(uint32_t wire_error_code) { if (wire_error_code > ERROR_CODE_MAX) { return ERROR_CODE_INTERNAL_ERROR; } return static_cast<SpdyErrorCode>(wire_error_code); } const char* ErrorCodeToString(SpdyErrorCode error_code) { switch (error_code) { case ERROR_CODE_NO_ERROR: return "NO_ERROR"; case ERROR_CODE_PROTOCOL_ERROR: return "PROTOCOL_ERROR"; case ERROR_CODE_INTERNAL_ERROR: return "INTERNAL_ERROR"; case ERROR_CODE_FLOW_CONTROL_ERROR: return "FLOW_CONTROL_ERROR"; case ERROR_CODE_SETTINGS_TIMEOUT: return "SETTINGS_TIMEOUT"; case ERROR_CODE_STREAM_CLOSED: return "STREAM_CLOSED"; case ERROR_CODE_FRAME_SIZE_ERROR: return "FRAME_SIZE_ERROR"; case ERROR_CODE_REFUSED_STREAM: return "REFUSED_STREAM"; case ERROR_CODE_CANCEL: return "CANCEL"; case ERROR_CODE_COMPRESSION_ERROR: return "COMPRESSION_ERROR"; case ERROR_CODE_CONNECT_ERROR: return "CONNECT_ERROR"; case ERROR_CODE_ENHANCE_YOUR_CALM: return "ENHANCE_YOUR_CALM"; case ERROR_CODE_INADEQUATE_SECURITY: return "INADEQUATE_SECURITY"; case ERROR_CODE_HTTP_1_1_REQUIRED: return "HTTP_1_1_REQUIRED"; } return "UNKNOWN_ERROR_CODE"; } const char* WriteSchedulerTypeToString(WriteSchedulerType type) { switch (type) { case WriteSchedulerType::LIFO: return "LIFO"; case WriteSchedulerType::SPDY: return "SPDY"; case WriteSchedulerType::HTTP2: return "HTTP2"; case WriteSchedulerType::FIFO: return "FIFO"; } return "UNKNOWN"; } size_t GetNumberRequiredContinuationFrames(size_t size) { QUICHE_DCHECK_GT(size, kHttp2MaxControlFrameSendSize); size_t overflow = size - kHttp2MaxControlFrameSendSize; int payload_size = kHttp2MaxControlFrameSendSize - kContinuationFrameMinimumSize; return (overflow - 1) / payload_size + 1; } const char* const kHttp2Npn = "h2"; const char* const kHttp2AuthorityHeader = ":authority"; const char* const kHttp2MethodHeader = ":method"; const char* const kHttp2PathHeader = ":path"; const char* const kHttp2SchemeHeader = ":scheme"; const char* const kHttp2ProtocolHeader = ":protocol"; const char* const kHttp2StatusHeader = ":status"; bool SpdyFrameIR::fin() const { return false; } int SpdyFrameIR::flow_control_window_consumed() const { return 0; } bool SpdyFrameWithFinIR::fin() const { return fin_; } SpdyFrameWithHeaderBlockIR::SpdyFrameWithHeaderBlockIR( SpdyStreamId stream_id, quiche::HttpHeaderBlock header_block) : SpdyFrameWithFinIR(stream_id), header_block_(std::move(header_block)) {} SpdyFrameWithHeaderBlockIR::~SpdyFrameWithHeaderBlockIR() = default; SpdyDataIR::SpdyDataIR(SpdyStreamId stream_id, absl::string_view data) : SpdyFrameWithFinIR(stream_id), data_(nullptr), data_len_(0), padded_(false), padding_payload_len_(0) { SetDataDeep(data); } SpdyDataIR::SpdyDataIR(SpdyStreamId stream_id, const char* data) : SpdyDataIR(stream_id, absl::string_view(data)) {} SpdyDataIR::SpdyDataIR(SpdyStreamId stream_id, std::string data) : SpdyFrameWithFinIR(stream_id), data_store_(std::make_unique<std::string>(std::move(data))), data_(data_store_->data()), data_len_(data_store_->size()), padded_(false), padding_payload_len_(0) {} SpdyDataIR::SpdyDataIR(SpdyStreamId stream_id) : SpdyFrameWithFinIR(stream_id), data_(nullptr), data_len_(0), padded_(false), padding_payload_len_(0) {} SpdyDataIR::~SpdyDataIR() = default; void SpdyDataIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitData(*this); } SpdyFrameType SpdyDataIR::frame_type() const { return SpdyFrameType::DATA; } int SpdyDataIR::flow_control_window_consumed() const { return padded_ ? 1 + padding_payload_len_ + data_len_ : data_len_; } size_t SpdyDataIR::size() const { return kFrameHeaderSize + (padded() ? 1 + padding_payload_len() + data_len() : data_len()); } SpdyRstStreamIR::SpdyRstStreamIR(SpdyStreamId stream_id, SpdyErrorCode error_code) : SpdyFrameIR(stream_id) { set_error_code(error_code); } SpdyRstStreamIR::~SpdyRstStreamIR() = default; void SpdyRstStreamIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitRstStream(*this); } SpdyFrameType SpdyRstStreamIR::frame_type() const { return SpdyFrameType::RST_STREAM; } size_t SpdyRstStreamIR::size() const { return kRstStreamFrameSize; } SpdySettingsIR::SpdySettingsIR() : is_ack_(false) {} SpdySettingsIR::~SpdySettingsIR() = default; void SpdySettingsIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitSettings(*this); } SpdyFrameType SpdySettingsIR::frame_type() const { return SpdyFrameType::SETTINGS; } size_t SpdySettingsIR::size() const { return kFrameHeaderSize + values_.size() * kSettingsOneSettingSize; } void SpdyPingIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPing(*this); } SpdyFrameType SpdyPingIR::frame_type() const { return SpdyFrameType::PING; } size_t SpdyPingIR::size() const { return kPingFrameSize; } SpdyGoAwayIR::SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, absl::string_view description) : description_(description) { set_last_good_stream_id(last_good_stream_id); set_error_code(error_code); } SpdyGoAwayIR::SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, const char* description) : SpdyGoAwayIR(last_good_stream_id, error_code, absl::string_view(description)) {} SpdyGoAwayIR::SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, std::string description) : description_store_(std::move(description)), description_(description_store_) { set_last_good_stream_id(last_good_stream_id); set_error_code(error_code); } SpdyGoAwayIR::~SpdyGoAwayIR() = default; void SpdyGoAwayIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitGoAway(*this); } SpdyFrameType SpdyGoAwayIR::frame_type() const { return SpdyFrameType::GOAWAY; } size_t SpdyGoAwayIR::size() const { return kGoawayFrameMinimumSize + description_.size(); } SpdyContinuationIR::SpdyContinuationIR(SpdyStreamId stream_id) : SpdyFrameIR(stream_id), end_headers_(false) {} SpdyContinuationIR::~SpdyContinuationIR() = default; void SpdyContinuationIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitContinuation(*this); } SpdyFrameType SpdyContinuationIR::frame_type() const { return SpdyFrameType::CONTINUATION; } size_t SpdyContinuationIR::size() const { QUICHE_DLOG(WARNING) << "Shouldn't not call size() for CONTINUATION frame."; return 0; } void SpdyHeadersIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitHeaders(*this); } SpdyFrameType SpdyHeadersIR::frame_type() const { return SpdyFrameType::HEADERS; } size_t SpdyHeadersIR::size() const { size_t size = kHeadersFrameMinimumSize; if (padded_) { size += 1; size += padding_payload_len_; } if (has_priority_) { size += 5; } size += header_block().TotalBytesUsed() + header_block().size() * kPerHeaderHpackOverhead; if (size > kHttp2MaxControlFrameSendSize) { size += GetNumberRequiredContinuationFrames(size) * kContinuationFrameMinimumSize; } return size; } void SpdyWindowUpdateIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitWindowUpdate(*this); } SpdyFrameType SpdyWindowUpdateIR::frame_type() const { return SpdyFrameType::WINDOW_UPDATE; } size_t SpdyWindowUpdateIR::size() const { return kWindowUpdateFrameSize; } void SpdyPushPromiseIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPushPromise(*this); } SpdyFrameType SpdyPushPromiseIR::frame_type() const { return SpdyFrameType::PUSH_PROMISE; } size_t SpdyPushPromiseIR::size() const { size_t size = kPushPromiseFrameMinimumSize; if (padded_) { size += 1; size += padding_payload_len_; } size += header_block().TotalBytesUsed(); if (size > kHttp2MaxControlFrameSendSize) { size += GetNumberRequiredContinuationFrames(size) * kContinuationFrameMinimumSize; } return size; } SpdyAltSvcIR::SpdyAltSvcIR(SpdyStreamId stream_id) : SpdyFrameIR(stream_id) {} SpdyAltSvcIR::~SpdyAltSvcIR() = default; void SpdyAltSvcIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitAltSvc(*this); } SpdyFrameType SpdyAltSvcIR::frame_type() const { return SpdyFrameType::ALTSVC; } size_t SpdyAltSvcIR::size() const { size_t size = kGetAltSvcFrameMinimumSize; size += origin_.length(); std::string str = SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector_); size += str.size(); return size; } void SpdyPriorityIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPriority(*this); } SpdyFrameType SpdyPriorityIR::frame_type() const { return SpdyFrameType::PRIORITY; } size_t SpdyPriorityIR::size() const { return kPriorityFrameSize; } void SpdyPriorityUpdateIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitPriorityUpdate(*this); } SpdyFrameType SpdyPriorityUpdateIR::frame_type() const { return SpdyFrameType::PRIORITY_UPDATE; } size_t SpdyPriorityUpdateIR::size() const { return kPriorityUpdateFrameMinimumSize + priority_field_value_.size(); } void SpdyAcceptChIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitAcceptCh(*this); } SpdyFrameType SpdyAcceptChIR::frame_type() const { return SpdyFrameType::ACCEPT_CH; } size_t SpdyAcceptChIR::size() const { size_t total_size = kAcceptChFrameMinimumSize; for (const AcceptChOriginValuePair& entry : entries_) { total_size += entry.origin.size() + entry.value.size() + kAcceptChFramePerEntryOverhead; } return total_size; } void SpdyUnknownIR::Visit(SpdyFrameVisitor* visitor) const { return visitor->VisitUnknown(*this); } SpdyFrameType SpdyUnknownIR::frame_type() const { return static_cast<SpdyFrameType>(type()); } size_t SpdyUnknownIR::size() const { return kFrameHeaderSize + payload_.size(); } int SpdyUnknownIR::flow_control_window_consumed() const { if (frame_type() == SpdyFrameType::DATA) { return payload_.size(); } else { return 0; } } const size_t kPadLengthFieldSize = 1; size_t GetHeaderFrameSizeSansBlock(const SpdyHeadersIR& header_ir) { size_t min_size = kFrameHeaderSize; if (header_ir.padded()) { min_size += kPadLengthFieldSize; min_size += header_ir.padding_payload_len(); } if (header_ir.has_priority()) { min_size += 5; } return min_size; } size_t GetPushPromiseFrameSizeSansBlock( const SpdyPushPromiseIR& push_promise_ir) { size_t min_size = kPushPromiseFrameMinimumSize; if (push_promise_ir.padded()) { min_size += kPadLengthFieldSize; min_size += push_promise_ir.padding_payload_len(); } return min_size; } }
#include "quiche/http2/core/spdy_protocol.h" #include <iostream> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { std::ostream& operator<<(std::ostream& os, const SpdyStreamPrecedence precedence) { if (precedence.is_spdy3_priority()) { os << "SpdyStreamPrecedence[spdy3_priority=" << precedence.spdy3_priority() << "]"; } else { os << "SpdyStreamPrecedence[parent_id=" << precedence.parent_id() << ", weight=" << precedence.weight() << ", is_exclusive=" << precedence.is_exclusive() << "]"; } return os; } namespace test { TEST(SpdyProtocolTest, ClampSpdy3Priority) { EXPECT_QUICHE_BUG(EXPECT_EQ(7, ClampSpdy3Priority(8)), "Invalid priority: 8"); EXPECT_EQ(kV3LowestPriority, ClampSpdy3Priority(kV3LowestPriority)); EXPECT_EQ(kV3HighestPriority, ClampSpdy3Priority(kV3HighestPriority)); } TEST(SpdyProtocolTest, ClampHttp2Weight) { EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MinStreamWeight, ClampHttp2Weight(0)), "Invalid weight: 0"); EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MaxStreamWeight, ClampHttp2Weight(300)), "Invalid weight: 300"); EXPECT_EQ(kHttp2MinStreamWeight, ClampHttp2Weight(kHttp2MinStreamWeight)); EXPECT_EQ(kHttp2MaxStreamWeight, ClampHttp2Weight(kHttp2MaxStreamWeight)); } TEST(SpdyProtocolTest, Spdy3PriorityToHttp2Weight) { EXPECT_EQ(256, Spdy3PriorityToHttp2Weight(0)); EXPECT_EQ(220, Spdy3PriorityToHttp2Weight(1)); EXPECT_EQ(183, Spdy3PriorityToHttp2Weight(2)); EXPECT_EQ(147, Spdy3PriorityToHttp2Weight(3)); EXPECT_EQ(110, Spdy3PriorityToHttp2Weight(4)); EXPECT_EQ(74, Spdy3PriorityToHttp2Weight(5)); EXPECT_EQ(37, Spdy3PriorityToHttp2Weight(6)); EXPECT_EQ(1, Spdy3PriorityToHttp2Weight(7)); } TEST(SpdyProtocolTest, Http2WeightToSpdy3Priority) { EXPECT_EQ(0u, Http2WeightToSpdy3Priority(256)); EXPECT_EQ(0u, Http2WeightToSpdy3Priority(221)); EXPECT_EQ(1u, Http2WeightToSpdy3Priority(220)); EXPECT_EQ(1u, Http2WeightToSpdy3Priority(184)); EXPECT_EQ(2u, Http2WeightToSpdy3Priority(183)); EXPECT_EQ(2u, Http2WeightToSpdy3Priority(148)); EXPECT_EQ(3u, Http2WeightToSpdy3Priority(147)); EXPECT_EQ(3u, Http2WeightToSpdy3Priority(111)); EXPECT_EQ(4u, Http2WeightToSpdy3Priority(110)); EXPECT_EQ(4u, Http2WeightToSpdy3Priority(75)); EXPECT_EQ(5u, Http2WeightToSpdy3Priority(74)); EXPECT_EQ(5u, Http2WeightToSpdy3Priority(38)); EXPECT_EQ(6u, Http2WeightToSpdy3Priority(37)); EXPECT_EQ(6u, Http2WeightToSpdy3Priority(2)); EXPECT_EQ(7u, Http2WeightToSpdy3Priority(1)); } TEST(SpdyProtocolTest, IsValidHTTP2FrameStreamId) { EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::DATA)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::DATA)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::HEADERS)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::HEADERS)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::PRIORITY)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::PRIORITY)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::RST_STREAM)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::RST_STREAM)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::CONTINUATION)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::CONTINUATION)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::PUSH_PROMISE)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::PUSH_PROMISE)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::GOAWAY)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::GOAWAY)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::SETTINGS)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::SETTINGS)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::PING)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::PING)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::WINDOW_UPDATE)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::WINDOW_UPDATE)); } TEST(SpdyProtocolTest, ParseSettingsId) { SpdyKnownSettingsId setting_id; EXPECT_FALSE(ParseSettingsId(0, &setting_id)); EXPECT_TRUE(ParseSettingsId(1, &setting_id)); EXPECT_EQ(SETTINGS_HEADER_TABLE_SIZE, setting_id); EXPECT_TRUE(ParseSettingsId(2, &setting_id)); EXPECT_EQ(SETTINGS_ENABLE_PUSH, setting_id); EXPECT_TRUE(ParseSettingsId(3, &setting_id)); EXPECT_EQ(SETTINGS_MAX_CONCURRENT_STREAMS, setting_id); EXPECT_TRUE(ParseSettingsId(4, &setting_id)); EXPECT_EQ(SETTINGS_INITIAL_WINDOW_SIZE, setting_id); EXPECT_TRUE(ParseSettingsId(5, &setting_id)); EXPECT_EQ(SETTINGS_MAX_FRAME_SIZE, setting_id); EXPECT_TRUE(ParseSettingsId(6, &setting_id)); EXPECT_EQ(SETTINGS_MAX_HEADER_LIST_SIZE, setting_id); EXPECT_FALSE(ParseSettingsId(7, &setting_id)); EXPECT_TRUE(ParseSettingsId(8, &setting_id)); EXPECT_EQ(SETTINGS_ENABLE_CONNECT_PROTOCOL, setting_id); EXPECT_TRUE(ParseSettingsId(9, &setting_id)); EXPECT_EQ(SETTINGS_DEPRECATE_HTTP2_PRIORITIES, setting_id); EXPECT_FALSE(ParseSettingsId(10, &setting_id)); EXPECT_FALSE(ParseSettingsId(0xFF44, &setting_id)); EXPECT_TRUE(ParseSettingsId(0xFF45, &setting_id)); EXPECT_EQ(SETTINGS_EXPERIMENT_SCHEDULER, setting_id); EXPECT_FALSE(ParseSettingsId(0xFF46, &setting_id)); } TEST(SpdyProtocolTest, SettingsIdToString) { struct { SpdySettingsId setting_id; const std::string expected_string; } test_cases[] = { {0, "SETTINGS_UNKNOWN_0"}, {SETTINGS_HEADER_TABLE_SIZE, "SETTINGS_HEADER_TABLE_SIZE"}, {SETTINGS_ENABLE_PUSH, "SETTINGS_ENABLE_PUSH"}, {SETTINGS_MAX_CONCURRENT_STREAMS, "SETTINGS_MAX_CONCURRENT_STREAMS"}, {SETTINGS_INITIAL_WINDOW_SIZE, "SETTINGS_INITIAL_WINDOW_SIZE"}, {SETTINGS_MAX_FRAME_SIZE, "SETTINGS_MAX_FRAME_SIZE"}, {SETTINGS_MAX_HEADER_LIST_SIZE, "SETTINGS_MAX_HEADER_LIST_SIZE"}, {7, "SETTINGS_UNKNOWN_7"}, {SETTINGS_ENABLE_CONNECT_PROTOCOL, "SETTINGS_ENABLE_CONNECT_PROTOCOL"}, {SETTINGS_DEPRECATE_HTTP2_PRIORITIES, "SETTINGS_DEPRECATE_HTTP2_PRIORITIES"}, {0xa, "SETTINGS_UNKNOWN_a"}, {0xFF44, "SETTINGS_UNKNOWN_ff44"}, {0xFF45, "SETTINGS_EXPERIMENT_SCHEDULER"}, {0xFF46, "SETTINGS_UNKNOWN_ff46"}}; for (auto test_case : test_cases) { EXPECT_EQ(test_case.expected_string, SettingsIdToString(test_case.setting_id)); } } TEST(SpdyStreamPrecedenceTest, Basic) { SpdyStreamPrecedence spdy3_prec(2); EXPECT_TRUE(spdy3_prec.is_spdy3_priority()); EXPECT_EQ(2, spdy3_prec.spdy3_priority()); EXPECT_EQ(kHttp2RootStreamId, spdy3_prec.parent_id()); EXPECT_EQ(Spdy3PriorityToHttp2Weight(2), spdy3_prec.weight()); EXPECT_FALSE(spdy3_prec.is_exclusive()); for (bool is_exclusive : {true, false}) { SpdyStreamPrecedence h2_prec(7, 123, is_exclusive); EXPECT_FALSE(h2_prec.is_spdy3_priority()); EXPECT_EQ(Http2WeightToSpdy3Priority(123), h2_prec.spdy3_priority()); EXPECT_EQ(7u, h2_prec.parent_id()); EXPECT_EQ(123, h2_prec.weight()); EXPECT_EQ(is_exclusive, h2_prec.is_exclusive()); } } TEST(SpdyStreamPrecedenceTest, Clamping) { EXPECT_QUICHE_BUG(EXPECT_EQ(7, SpdyStreamPrecedence(8).spdy3_priority()), "Invalid priority: 8"); EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MinStreamWeight, SpdyStreamPrecedence(3, 0, false).weight()), "Invalid weight: 0"); EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MaxStreamWeight, SpdyStreamPrecedence(3, 300, false).weight()), "Invalid weight: 300"); } TEST(SpdyStreamPrecedenceTest, Copying) { SpdyStreamPrecedence prec1(3); SpdyStreamPrecedence copy1(prec1); EXPECT_TRUE(copy1.is_spdy3_priority()); EXPECT_EQ(3, copy1.spdy3_priority()); SpdyStreamPrecedence prec2(4, 5, true); SpdyStreamPrecedence copy2(prec2); EXPECT_FALSE(copy2.is_spdy3_priority()); EXPECT_EQ(4u, copy2.parent_id()); EXPECT_EQ(5, copy2.weight()); EXPECT_TRUE(copy2.is_exclusive()); copy1 = prec2; EXPECT_FALSE(copy1.is_spdy3_priority()); EXPECT_EQ(4u, copy1.parent_id()); EXPECT_EQ(5, copy1.weight()); EXPECT_TRUE(copy1.is_exclusive()); copy2 = prec1; EXPECT_TRUE(copy2.is_spdy3_priority()); EXPECT_EQ(3, copy2.spdy3_priority()); } TEST(SpdyStreamPrecedenceTest, Equals) { EXPECT_EQ(SpdyStreamPrecedence(3), SpdyStreamPrecedence(3)); EXPECT_NE(SpdyStreamPrecedence(3), SpdyStreamPrecedence(4)); EXPECT_EQ(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(1, 2, false)); EXPECT_NE(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(2, 2, false)); EXPECT_NE(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(1, 3, false)); EXPECT_NE(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(1, 2, true)); SpdyStreamPrecedence spdy3_prec(3); SpdyStreamPrecedence h2_prec(spdy3_prec.parent_id(), spdy3_prec.weight(), spdy3_prec.is_exclusive()); EXPECT_NE(spdy3_prec, h2_prec); } TEST(SpdyDataIRTest, Construct) { absl::string_view s1; SpdyDataIR d1( 1, s1); EXPECT_EQ(0u, d1.data_len()); EXPECT_NE(nullptr, d1.data()); const char s2[] = "something"; SpdyDataIR d2( 2, s2); EXPECT_EQ(absl::string_view(d2.data(), d2.data_len()), s2); EXPECT_NE(absl::string_view(d1.data(), d1.data_len()), s2); EXPECT_EQ((int)d1.data_len(), d1.flow_control_window_consumed()); const std::string foo = "foo"; SpdyDataIR d3( 3, foo); EXPECT_EQ(foo, d3.data()); EXPECT_EQ((int)d3.data_len(), d3.flow_control_window_consumed()); std::string bar = "bar"; SpdyDataIR d4( 4, bar); EXPECT_EQ("bar", bar); EXPECT_EQ("bar", absl::string_view(d4.data(), d4.data_len())); std::string baz = "the quick brown fox"; SpdyDataIR d5( 5, std::move(baz)); EXPECT_EQ("", baz); EXPECT_EQ(absl::string_view(d5.data(), d5.data_len()), "the quick brown fox"); SpdyDataIR d7( 7, "something else"); EXPECT_EQ(absl::string_view(d7.data(), d7.data_len()), "something else"); SpdyDataIR d8( 8, "shawarma"); d8.set_padding_len(20); EXPECT_EQ(28, d8.flow_control_window_consumed()); } TEST(SpdySerializedFrameTest, Basic) { const std::string data = "0123456789"; auto buffer = std::make_unique<char[]>(data.length()); memcpy(buffer.get(), &data[0], data.length()); SpdySerializedFrame frame(std::move(buffer), data.length()); EXPECT_EQ(data.length(), frame.size()); EXPECT_EQ(data, std::string(frame.data(), frame.size())); EXPECT_EQ(frame.begin(), frame.data()); EXPECT_EQ(frame.end(), frame.data() + frame.size()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_protocol.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_protocol_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
375ef4d6-64ae-424f-ae82-cd2438b0dec3
cpp
google/quiche
spdy_alt_svc_wire_format
quiche/http2/core/spdy_alt_svc_wire_format.cc
quiche/http2/core/spdy_alt_svc_wire_format_test.cc
#include "quiche/http2/core/spdy_alt_svc_wire_format.h" #include <algorithm> #include <cctype> #include <cstdint> #include <limits> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { namespace { template <class T> bool ParsePositiveIntegerImpl(absl::string_view::const_iterator c, absl::string_view::const_iterator end, T* value) { *value = 0; for (; c != end && std::isdigit(*c); ++c) { if (*value > std::numeric_limits<T>::max() / 10) { return false; } *value *= 10; if (*value > std::numeric_limits<T>::max() - (*c - '0')) { return false; } *value += *c - '0'; } return (c == end && *value > 0); } } SpdyAltSvcWireFormat::AlternativeService::AlternativeService() = default; SpdyAltSvcWireFormat::AlternativeService::AlternativeService( const std::string& protocol_id, const std::string& host, uint16_t port, uint32_t max_age_seconds, VersionVector version) : protocol_id(protocol_id), host(host), port(port), max_age_seconds(max_age_seconds), version(std::move(version)) {} SpdyAltSvcWireFormat::AlternativeService::~AlternativeService() = default; SpdyAltSvcWireFormat::AlternativeService::AlternativeService( const AlternativeService& other) = default; bool SpdyAltSvcWireFormat::ParseHeaderFieldValue( absl::string_view value, AlternativeServiceVector* altsvc_vector) { if (value.empty()) { return false; } altsvc_vector->clear(); if (value == absl::string_view("clear")) { return true; } absl::string_view::const_iterator c = value.begin(); while (c != value.end()) { absl::string_view::const_iterator percent_encoded_protocol_id_end = std::find(c, value.end(), '='); std::string protocol_id; if (percent_encoded_protocol_id_end == c || !PercentDecode(c, percent_encoded_protocol_id_end, &protocol_id)) { return false; } const bool is_ietf_format_quic = (protocol_id == "hq"); c = percent_encoded_protocol_id_end; if (c == value.end()) { return false; } QUICHE_DCHECK_EQ('=', *c); ++c; if (c == value.end() || *c != '"') { return false; } ++c; absl::string_view::const_iterator alt_authority_begin = c; for (; c != value.end() && *c != '"'; ++c) { if (*c != '\\') { continue; } ++c; if (c == value.end()) { return false; } } if (c == alt_authority_begin || c == value.end()) { return false; } QUICHE_DCHECK_EQ('"', *c); std::string host; uint16_t port; if (!ParseAltAuthority(alt_authority_begin, c, &host, &port)) { return false; } ++c; uint32_t max_age_seconds = 86400; VersionVector version; absl::string_view::const_iterator parameters_end = std::find(c, value.end(), ','); while (c != parameters_end) { SkipWhiteSpace(&c, parameters_end); if (c == parameters_end) { break; } if (*c != ';') { return false; } ++c; SkipWhiteSpace(&c, parameters_end); if (c == parameters_end) { break; } std::string parameter_name; for (; c != parameters_end && *c != '=' && *c != ' ' && *c != '\t'; ++c) { parameter_name.push_back(tolower(*c)); } SkipWhiteSpace(&c, parameters_end); if (c == parameters_end || *c != '=') { return false; } ++c; SkipWhiteSpace(&c, parameters_end); absl::string_view::const_iterator parameter_value_begin = c; for (; c != parameters_end && *c != ';' && *c != ' ' && *c != '\t'; ++c) { } if (c == parameter_value_begin) { return false; } if (parameter_name == "ma") { if (!ParsePositiveInteger32(parameter_value_begin, c, &max_age_seconds)) { return false; } } else if (!is_ietf_format_quic && parameter_name == "v") { if (*parameter_value_begin != '"') { return false; } c = std::find(parameter_value_begin + 1, value.end(), '"'); if (c == value.end()) { return false; } ++c; parameters_end = std::find(c, value.end(), ','); absl::string_view::const_iterator v_begin = parameter_value_begin + 1; while (v_begin < c) { absl::string_view::const_iterator v_end = v_begin; while (v_end < c - 1 && *v_end != ',') { ++v_end; } uint16_t v; if (!ParsePositiveInteger16(v_begin, v_end, &v)) { return false; } version.push_back(v); v_begin = v_end + 1; if (v_begin == c - 1) { return false; } } } else if (is_ietf_format_quic && parameter_name == "quic") { if (*parameter_value_begin == '0') { return false; } uint32_t quic_version; if (!HexDecodeToUInt32(absl::string_view(&*parameter_value_begin, c - parameter_value_begin), &quic_version) || quic_version == 0) { return false; } version.push_back(quic_version); } } altsvc_vector->emplace_back(protocol_id, host, port, max_age_seconds, version); for (; c != value.end() && (*c == ' ' || *c == '\t' || *c == ','); ++c) { } } return true; } std::string SpdyAltSvcWireFormat::SerializeHeaderFieldValue( const AlternativeServiceVector& altsvc_vector) { if (altsvc_vector.empty()) { return std::string("clear"); } const char kNibbleToHex[] = "0123456789ABCDEF"; std::string value; for (const AlternativeService& altsvc : altsvc_vector) { if (!value.empty()) { value.push_back(','); } const bool is_ietf_format_quic = (altsvc.protocol_id == "hq"); for (char c : altsvc.protocol_id) { if (isalnum(c)) { value.push_back(c); continue; } switch (c) { case '!': case '#': case '$': case '&': case '\'': case '*': case '+': case '-': case '.': case '^': case '_': case '`': case '|': case '~': value.push_back(c); break; default: value.push_back('%'); value.push_back(kNibbleToHex[c >> 4]); value.push_back(kNibbleToHex[c & 0x0f]); break; } } value.push_back('='); value.push_back('"'); for (char c : altsvc.host) { if (c == '"' || c == '\\') { value.push_back('\\'); } value.push_back(c); } absl::StrAppend(&value, ":", altsvc.port, "\""); if (altsvc.max_age_seconds != 86400) { absl::StrAppend(&value, "; ma=", altsvc.max_age_seconds); } if (!altsvc.version.empty()) { if (is_ietf_format_quic) { for (uint32_t quic_version : altsvc.version) { absl::StrAppend(&value, "; quic=", absl::Hex(quic_version)); } } else { value.append("; v=\""); for (auto it = altsvc.version.begin(); it != altsvc.version.end(); ++it) { if (it != altsvc.version.begin()) { value.append(","); } absl::StrAppend(&value, *it); } value.append("\""); } } } return value; } void SpdyAltSvcWireFormat::SkipWhiteSpace( absl::string_view::const_iterator* c, absl::string_view::const_iterator end) { for (; *c != end && (**c == ' ' || **c == '\t'); ++*c) { } } bool SpdyAltSvcWireFormat::PercentDecode(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* output) { output->clear(); for (; c != end; ++c) { if (*c != '%') { output->push_back(*c); continue; } QUICHE_DCHECK_EQ('%', *c); ++c; if (c == end || !std::isxdigit(*c)) { return false; } char decoded = HexDigitToInt(*c) << 4; ++c; if (c == end || !std::isxdigit(*c)) { return false; } decoded += HexDigitToInt(*c); output->push_back(decoded); } return true; } bool SpdyAltSvcWireFormat::ParseAltAuthority( absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* host, uint16_t* port) { host->clear(); if (c == end) { return false; } if (*c == '[') { for (; c != end && *c != ']'; ++c) { if (*c == '"') { return false; } host->push_back(*c); } if (c == end) { return false; } QUICHE_DCHECK_EQ(']', *c); host->push_back(*c); ++c; } else { for (; c != end && *c != ':'; ++c) { if (*c == '"') { return false; } if (*c == '\\') { ++c; if (c == end) { return false; } } host->push_back(*c); } } if (c == end || *c != ':') { return false; } QUICHE_DCHECK_EQ(':', *c); ++c; return ParsePositiveInteger16(c, end, port); } bool SpdyAltSvcWireFormat::ParsePositiveInteger16( absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint16_t* value) { return ParsePositiveIntegerImpl<uint16_t>(c, end, value); } bool SpdyAltSvcWireFormat::ParsePositiveInteger32( absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint32_t* value) { return ParsePositiveIntegerImpl<uint32_t>(c, end, value); } char SpdyAltSvcWireFormat::HexDigitToInt(char c) { QUICHE_DCHECK(std::isxdigit(c)); if (std::isdigit(c)) { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } return 0; } bool SpdyAltSvcWireFormat::HexDecodeToUInt32(absl::string_view data, uint32_t* value) { if (data.empty() || data.length() > 8u) { return false; } *value = 0; for (char c : data) { if (!std::isxdigit(c)) { return false; } *value <<= 4; *value += HexDigitToInt(c); } return true; } }
#include "quiche/http2/core/spdy_alt_svc_wire_format.h" #include <cstddef> #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace test { class SpdyAltSvcWireFormatPeer { public: static void SkipWhiteSpace(absl::string_view::const_iterator* c, absl::string_view::const_iterator end) { SpdyAltSvcWireFormat::SkipWhiteSpace(c, end); } static bool PercentDecode(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* output) { return SpdyAltSvcWireFormat::PercentDecode(c, end, output); } static bool ParseAltAuthority(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* host, uint16_t* port) { return SpdyAltSvcWireFormat::ParseAltAuthority(c, end, host, port); } static bool ParsePositiveInteger16(absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint16_t* max_age_seconds) { return SpdyAltSvcWireFormat::ParsePositiveInteger16(c, end, max_age_seconds); } static bool ParsePositiveInteger32(absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint32_t* max_age_seconds) { return SpdyAltSvcWireFormat::ParsePositiveInteger32(c, end, max_age_seconds); } static char HexDigitToInt(char c) { return SpdyAltSvcWireFormat::HexDigitToInt(c); } static bool HexDecodeToUInt32(absl::string_view data, uint32_t* value) { return SpdyAltSvcWireFormat::HexDecodeToUInt32(data, value); } }; namespace { void FuzzHeaderFieldValue( int i, std::string* header_field_value, SpdyAltSvcWireFormat::AlternativeService* expected_altsvc) { if (!header_field_value->empty()) { header_field_value->push_back(','); } bool is_ietf_format_quic = (i & 1 << 0) != 0; if (i & 1 << 0) { expected_altsvc->protocol_id = "hq"; header_field_value->append("hq=\""); } else { expected_altsvc->protocol_id = "a=b%c"; header_field_value->append("a%3Db%25c=\""); } if (i & 1 << 1) { expected_altsvc->host = "foo\"bar\\baz"; header_field_value->append("foo\\\"bar\\\\baz"); } else { expected_altsvc->host = ""; } expected_altsvc->port = 42; header_field_value->append(":42\""); if (i & 1 << 2) { header_field_value->append(" "); } if (i & 3 << 3) { expected_altsvc->max_age_seconds = 1111; header_field_value->append(";"); if (i & 1 << 3) { header_field_value->append(" "); } header_field_value->append("mA=1111"); if (i & 2 << 3) { header_field_value->append(" "); } } if (i & 1 << 5) { header_field_value->append("; J=s"); } if (i & 1 << 6) { if (is_ietf_format_quic) { if (i & 1 << 7) { expected_altsvc->version.push_back(0x923457e); header_field_value->append("; quic=923457E"); } else { expected_altsvc->version.push_back(1); expected_altsvc->version.push_back(0xFFFFFFFF); header_field_value->append("; quic=1; quic=fFfFffFf"); } } else { if (i & i << 7) { expected_altsvc->version.push_back(24); header_field_value->append("; v=\"24\""); } else { expected_altsvc->version.push_back(1); expected_altsvc->version.push_back(65535); header_field_value->append("; v=\"1,65535\""); } } } if (i & 1 << 8) { expected_altsvc->max_age_seconds = 999999999; header_field_value->append("; Ma=999999999"); } if (i & 1 << 9) { header_field_value->append(";"); } if (i & 1 << 10) { header_field_value->append(" "); } if (i & 1 << 11) { header_field_value->append(","); } if (i & 1 << 12) { header_field_value->append(" "); } } void FuzzAlternativeService(int i, SpdyAltSvcWireFormat::AlternativeService* altsvc, std::string* expected_header_field_value) { if (!expected_header_field_value->empty()) { expected_header_field_value->push_back(','); } altsvc->protocol_id = "a=b%c"; altsvc->port = 42; expected_header_field_value->append("a%3Db%25c=\""); if (i & 1 << 0) { altsvc->host = "foo\"bar\\baz"; expected_header_field_value->append("foo\\\"bar\\\\baz"); } expected_header_field_value->append(":42\""); if (i & 1 << 1) { altsvc->max_age_seconds = 1111; expected_header_field_value->append("; ma=1111"); } if (i & 1 << 2) { altsvc->version.push_back(24); altsvc->version.push_back(25); expected_header_field_value->append("; v=\"24,25\""); } } TEST(SpdyAltSvcWireFormatTest, DefaultValues) { SpdyAltSvcWireFormat::AlternativeService altsvc; EXPECT_EQ("", altsvc.protocol_id); EXPECT_EQ("", altsvc.host); EXPECT_EQ(0u, altsvc.port); EXPECT_EQ(86400u, altsvc.max_age_seconds); EXPECT_TRUE(altsvc.version.empty()); } TEST(SpdyAltSvcWireFormatTest, ParseInvalidEmptyHeaderFieldValue) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_FALSE(SpdyAltSvcWireFormat::ParseHeaderFieldValue("", &altsvc_vector)); } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValueClear) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE( SpdyAltSvcWireFormat::ParseHeaderFieldValue("clear", &altsvc_vector)); EXPECT_EQ(0u, altsvc_vector.size()); } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValue) { for (int i = 0; i < 1 << 13; ++i) { std::string header_field_value; SpdyAltSvcWireFormat::AlternativeService expected_altsvc; FuzzHeaderFieldValue(i, &header_field_value, &expected_altsvc); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue(header_field_value, &altsvc_vector)); ASSERT_EQ(1u, altsvc_vector.size()); EXPECT_EQ(expected_altsvc.protocol_id, altsvc_vector[0].protocol_id); EXPECT_EQ(expected_altsvc.host, altsvc_vector[0].host); EXPECT_EQ(expected_altsvc.port, altsvc_vector[0].port); EXPECT_EQ(expected_altsvc.max_age_seconds, altsvc_vector[0].max_age_seconds); EXPECT_EQ(expected_altsvc.version, altsvc_vector[0].version); std::string reserialized_header_field_value = SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector); SpdyAltSvcWireFormat::AlternativeServiceVector roundtrip_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( reserialized_header_field_value, &roundtrip_altsvc_vector)); ASSERT_EQ(1u, roundtrip_altsvc_vector.size()); EXPECT_EQ(expected_altsvc.protocol_id, roundtrip_altsvc_vector[0].protocol_id); EXPECT_EQ(expected_altsvc.host, roundtrip_altsvc_vector[0].host); EXPECT_EQ(expected_altsvc.port, roundtrip_altsvc_vector[0].port); EXPECT_EQ(expected_altsvc.max_age_seconds, roundtrip_altsvc_vector[0].max_age_seconds); EXPECT_EQ(expected_altsvc.version, roundtrip_altsvc_vector[0].version); } } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValueMultiple) { for (int i = 0; i < 1 << 13;) { std::string header_field_value; SpdyAltSvcWireFormat::AlternativeServiceVector expected_altsvc_vector; do { SpdyAltSvcWireFormat::AlternativeService expected_altsvc; FuzzHeaderFieldValue(i, &header_field_value, &expected_altsvc); expected_altsvc_vector.push_back(expected_altsvc); ++i; } while (i % 6 < i % 7); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue(header_field_value, &altsvc_vector)); ASSERT_EQ(expected_altsvc_vector.size(), altsvc_vector.size()); for (unsigned int j = 0; j < altsvc_vector.size(); ++j) { EXPECT_EQ(expected_altsvc_vector[j].protocol_id, altsvc_vector[j].protocol_id); EXPECT_EQ(expected_altsvc_vector[j].host, altsvc_vector[j].host); EXPECT_EQ(expected_altsvc_vector[j].port, altsvc_vector[j].port); EXPECT_EQ(expected_altsvc_vector[j].max_age_seconds, altsvc_vector[j].max_age_seconds); EXPECT_EQ(expected_altsvc_vector[j].version, altsvc_vector[j].version); } std::string reserialized_header_field_value = SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector); SpdyAltSvcWireFormat::AlternativeServiceVector roundtrip_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( reserialized_header_field_value, &roundtrip_altsvc_vector)); ASSERT_EQ(expected_altsvc_vector.size(), roundtrip_altsvc_vector.size()); for (unsigned int j = 0; j < roundtrip_altsvc_vector.size(); ++j) { EXPECT_EQ(expected_altsvc_vector[j].protocol_id, roundtrip_altsvc_vector[j].protocol_id); EXPECT_EQ(expected_altsvc_vector[j].host, roundtrip_altsvc_vector[j].host); EXPECT_EQ(expected_altsvc_vector[j].port, roundtrip_altsvc_vector[j].port); EXPECT_EQ(expected_altsvc_vector[j].max_age_seconds, roundtrip_altsvc_vector[j].max_age_seconds); EXPECT_EQ(expected_altsvc_vector[j].version, roundtrip_altsvc_vector[j].version); } } } TEST(SpdyAltSvcWireFormatTest, SerializeEmptyHeaderFieldValue) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; EXPECT_EQ("clear", SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector)); } TEST(SpdyAltSvcWireFormatTest, RoundTrip) { for (int i = 0; i < 1 << 3; ++i) { SpdyAltSvcWireFormat::AlternativeService altsvc; std::string expected_header_field_value; FuzzAlternativeService(i, &altsvc, &expected_header_field_value); SpdyAltSvcWireFormat::AlternativeServiceVector parsed_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( expected_header_field_value, &parsed_altsvc_vector)); ASSERT_EQ(1u, parsed_altsvc_vector.size()); EXPECT_EQ(altsvc.protocol_id, parsed_altsvc_vector[0].protocol_id); EXPECT_EQ(altsvc.host, parsed_altsvc_vector[0].host); EXPECT_EQ(altsvc.port, parsed_altsvc_vector[0].port); EXPECT_EQ(altsvc.max_age_seconds, parsed_altsvc_vector[0].max_age_seconds); EXPECT_EQ(altsvc.version, parsed_altsvc_vector[0].version); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; altsvc_vector.push_back(altsvc); EXPECT_EQ(expected_header_field_value, SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector)); } } TEST(SpdyAltSvcWireFormatTest, RoundTripMultiple) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; std::string expected_header_field_value; for (int i = 0; i < 1 << 3; ++i) { SpdyAltSvcWireFormat::AlternativeService altsvc; FuzzAlternativeService(i, &altsvc, &expected_header_field_value); altsvc_vector.push_back(altsvc); } SpdyAltSvcWireFormat::AlternativeServiceVector parsed_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( expected_header_field_value, &parsed_altsvc_vector)); ASSERT_EQ(altsvc_vector.size(), parsed_altsvc_vector.size()); auto expected_it = altsvc_vector.begin(); auto parsed_it = parsed_altsvc_vector.begin(); for (; expected_it != altsvc_vector.end(); ++expected_it, ++parsed_it) { EXPECT_EQ(expected_it->protocol_id, parsed_it->protocol_id); EXPECT_EQ(expected_it->host, parsed_it->host); EXPECT_EQ(expected_it->port, parsed_it->port); EXPECT_EQ(expected_it->max_age_seconds, parsed_it->max_age_seconds); EXPECT_EQ(expected_it->version, parsed_it->version); } EXPECT_EQ(expected_header_field_value, SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector)); } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValueInvalid) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; const char* invalid_field_value_array[] = {"a%", "a%x", "a%b", "a%9z", "a=", "a=\"", "a=\"b\"", "a=\":\"", "a=\"c:\"", "a=\"c:foo\"", "a=\"c:42foo\"", "a=\"b:42\"bar", "a=\"b:42\" ; m", "a=\"b:42\" ; min-age", "a=\"b:42\" ; ma", "a=\"b:42\" ; ma=", "a=\"b:42\" ; v=\"..\"", "a=\"b:42\" ; ma=ma", "a=\"b:42\" ; ma=123bar", "a=\"b:42\" ; v=24", "a=\"b:42\" ; v=24,25", "a=\"b:42\" ; v=\"-3\"", "a=\"b:42\" ; v=\"1.2\"", "a=\"b:42\" ; v=\"24,\""}; for (const char* invalid_field_value : invalid_field_value_array) { EXPECT_FALSE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( invalid_field_value, &altsvc_vector)) << invalid_field_value; } } TEST(SpdyAltSvcWireFormatTest, ParseTruncatedHeaderFieldValue) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; const char* field_value_array[] = {"a=\":137\"", "a=\"foo:137\"", "a%25=\"foo\\\"bar\\\\baz:137\""}; for (const absl::string_view field_value : field_value_array) { for (size_t len = 1; len < field_value.size(); ++len) { EXPECT_FALSE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( field_value.substr(0, len), &altsvc_vector)) << len; } } } TEST(SpdyAltSvcWireFormatTest, SkipWhiteSpace) { absl::string_view input("a \tb "); absl::string_view::const_iterator c = input.begin(); SpdyAltSvcWireFormatPeer::SkipWhiteSpace(&c, input.end()); ASSERT_EQ(input.begin(), c); ++c; SpdyAltSvcWireFormatPeer::SkipWhiteSpace(&c, input.end()); ASSERT_EQ(input.begin() + 3, c); ++c; SpdyAltSvcWireFormatPeer::SkipWhiteSpace(&c, input.end()); ASSERT_EQ(input.end(), c); } TEST(SpdyAltSvcWireFormatTest, PercentDecodeValid) { absl::string_view input(""); std::string output; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)); EXPECT_EQ("", output); input = absl::string_view("foo"); output.clear(); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)); EXPECT_EQ("foo", output); input = absl::string_view("%2ca%5Cb"); output.clear(); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)); EXPECT_EQ(",a\\b", output); } TEST(SpdyAltSvcWireFormatTest, PercentDecodeInvalid) { const char* invalid_input_array[] = {"a%", "a%x", "a%b", "%J22", "%9z"}; for (const char* invalid_input : invalid_input_array) { absl::string_view input(invalid_input); std::string output; EXPECT_FALSE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)) << input; } } TEST(SpdyAltSvcWireFormatTest, ParseAltAuthorityValid) { absl::string_view input(":42"); std::string host; uint16_t port; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)); EXPECT_TRUE(host.empty()); EXPECT_EQ(42, port); input = absl::string_view("foo:137"); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)); EXPECT_EQ("foo", host); EXPECT_EQ(137, port); input = absl::string_view("[2003:8:0:16::509d:9615]:443"); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)); EXPECT_EQ("[2003:8:0:16::509d:9615]", host); EXPECT_EQ(443, port); } TEST(SpdyAltSvcWireFormatTest, ParseAltAuthorityInvalid) { const char* invalid_input_array[] = {"", ":", "foo:", ":bar", ":0", "foo:0", ":12bar", "foo:23bar", " ", ":12 ", "foo:12 ", "[2003:8:0:16::509d:9615]", "[2003:8:0:16::509d:9615]:", "[2003:8:0:16::509d:9615]foo:443", "[2003:8:0:16::509d:9615:443", "2003:8:0:16::509d:9615]:443"}; for (const char* invalid_input : invalid_input_array) { absl::string_view input(invalid_input); std::string host; uint16_t port; EXPECT_FALSE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)) << input; } } TEST(SpdyAltSvcWireFormatTest, ParseIntegerValid) { absl::string_view input("3"); uint16_t value; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value)); EXPECT_EQ(3, value); input = absl::string_view("1337"); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value)); EXPECT_EQ(1337, value); } TEST(SpdyAltSvcWireFormatTest, ParseIntegerInvalid) { const char* invalid_input_array[] = {"", " ", "a", "0", "00", "1 ", "12b"}; for (const char* invalid_input : invalid_input_array) { absl::string_view input(invalid_input); uint16_t value; EXPECT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value)) << input; } } TEST(SpdyAltSvcWireFormatTest, ParseIntegerOverflow) { absl::string_view input("65535"); uint16_t value16; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value16)); EXPECT_EQ(65535, value16); input = absl::string_view("65536"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value16)); input = absl::string_view("65537"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value16)); input = absl::string_view("4294967295"); uint32_t value32; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger32( input.begin(), input.end(), &value32)); EXPECT_EQ(4294967295, value32); input = absl::string_view("4294967296"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger32( input.begin(), input.end(), &value32)); input = absl::string_view("4294967297"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger32( input.begin(), input.end(), &value32)); } TEST(SpdyAltSvcWireFormatTest, ParseIPLiteral) { const char* input = "quic=\"[2003:8:0:16::509d:9615]:443\"; v=\"36,35\"; ma=60"; SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE( SpdyAltSvcWireFormat::ParseHeaderFieldValue(input, &altsvc_vector)); EXPECT_EQ(1u, altsvc_vector.size()); EXPECT_EQ("quic", altsvc_vector[0].protocol_id); EXPECT_EQ("[2003:8:0:16::509d:9615]", altsvc_vector[0].host); EXPECT_EQ(443u, altsvc_vector[0].port); EXPECT_EQ(60u, altsvc_vector[0].max_age_seconds); EXPECT_THAT(altsvc_vector[0].version, ::testing::ElementsAre(36, 35)); } TEST(SpdyAltSvcWireFormatTest, HexDigitToInt) { EXPECT_EQ(0, SpdyAltSvcWireFormatPeer::HexDigitToInt('0')); EXPECT_EQ(1, SpdyAltSvcWireFormatPeer::HexDigitToInt('1')); EXPECT_EQ(2, SpdyAltSvcWireFormatPeer::HexDigitToInt('2')); EXPECT_EQ(3, SpdyAltSvcWireFormatPeer::HexDigitToInt('3')); EXPECT_EQ(4, SpdyAltSvcWireFormatPeer::HexDigitToInt('4')); EXPECT_EQ(5, SpdyAltSvcWireFormatPeer::HexDigitToInt('5')); EXPECT_EQ(6, SpdyAltSvcWireFormatPeer::HexDigitToInt('6')); EXPECT_EQ(7, SpdyAltSvcWireFormatPeer::HexDigitToInt('7')); EXPECT_EQ(8, SpdyAltSvcWireFormatPeer::HexDigitToInt('8')); EXPECT_EQ(9, SpdyAltSvcWireFormatPeer::HexDigitToInt('9')); EXPECT_EQ(10, SpdyAltSvcWireFormatPeer::HexDigitToInt('a')); EXPECT_EQ(11, SpdyAltSvcWireFormatPeer::HexDigitToInt('b')); EXPECT_EQ(12, SpdyAltSvcWireFormatPeer::HexDigitToInt('c')); EXPECT_EQ(13, SpdyAltSvcWireFormatPeer::HexDigitToInt('d')); EXPECT_EQ(14, SpdyAltSvcWireFormatPeer::HexDigitToInt('e')); EXPECT_EQ(15, SpdyAltSvcWireFormatPeer::HexDigitToInt('f')); EXPECT_EQ(10, SpdyAltSvcWireFormatPeer::HexDigitToInt('A')); EXPECT_EQ(11, SpdyAltSvcWireFormatPeer::HexDigitToInt('B')); EXPECT_EQ(12, SpdyAltSvcWireFormatPeer::HexDigitToInt('C')); EXPECT_EQ(13, SpdyAltSvcWireFormatPeer::HexDigitToInt('D')); EXPECT_EQ(14, SpdyAltSvcWireFormatPeer::HexDigitToInt('E')); EXPECT_EQ(15, SpdyAltSvcWireFormatPeer::HexDigitToInt('F')); } TEST(SpdyAltSvcWireFormatTest, HexDecodeToUInt32) { uint32_t out; EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("0", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("00", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("0000000", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("00000000", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("1", &out)); EXPECT_EQ(1u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("ffffFFF", &out)); EXPECT_EQ(0xFFFFFFFu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("fFfFffFf", &out)); EXPECT_EQ(0xFFFFFFFFu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("01AEF", &out)); EXPECT_EQ(0x1AEFu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("abcde", &out)); EXPECT_EQ(0xABCDEu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("1234abcd", &out)); EXPECT_EQ(0x1234ABCDu, out); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("", &out)); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("111111111", &out)); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("1111111111", &out)); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("0x1111", &out)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_alt_svc_wire_format.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/spdy_alt_svc_wire_format_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
51570f0d-4ef4-48ce-8d82-5c34931cc933
cpp
google/quiche
array_output_buffer
quiche/http2/core/array_output_buffer.cc
quiche/http2/core/array_output_buffer_test.cc
#include "quiche/http2/core/array_output_buffer.h" #include <cstdint> namespace spdy { void ArrayOutputBuffer::Next(char** data, int* size) { *data = current_; *size = capacity_ > 0 ? capacity_ : 0; } void ArrayOutputBuffer::AdvanceWritePtr(int64_t count) { current_ += count; capacity_ -= count; } uint64_t ArrayOutputBuffer::BytesFree() const { return capacity_; } }
#include "quiche/http2/core/array_output_buffer.h" #include <cstdint> #include <cstring> #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace test { TEST(ArrayOutputBufferTest, InitializedFromArray) { char array[100]; ArrayOutputBuffer buffer(array, sizeof(array)); EXPECT_EQ(sizeof(array), buffer.BytesFree()); EXPECT_EQ(0u, buffer.Size()); EXPECT_EQ(array, buffer.Begin()); } TEST(ArrayOutputBufferTest, WriteAndReset) { char array[100]; ArrayOutputBuffer buffer(array, sizeof(array)); char* dst; int size; buffer.Next(&dst, &size); ASSERT_GT(size, 1); ASSERT_NE(nullptr, dst); const int64_t written = size / 2; memset(dst, 'x', written); buffer.AdvanceWritePtr(written); EXPECT_EQ(static_cast<uint64_t>(size) - written, buffer.BytesFree()); EXPECT_EQ(static_cast<uint64_t>(written), buffer.Size()); buffer.Reset(); EXPECT_EQ(sizeof(array), buffer.BytesFree()); EXPECT_EQ(0u, buffer.Size()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/array_output_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/core/array_output_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8c29c712-c7a8-476a-9c88-27afb11d1cb1
cpp
google/quiche
http2_hpack_constants
quiche/http2/hpack/http2_hpack_constants.cc
quiche/http2/hpack/http2_hpack_constants_test.cc
#include "quiche/http2/hpack/http2_hpack_constants.h" #include <ostream> #include <string> #include "absl/strings/str_cat.h" namespace http2 { std::string HpackEntryTypeToString(HpackEntryType v) { switch (v) { case HpackEntryType::kIndexedHeader: return "kIndexedHeader"; case HpackEntryType::kDynamicTableSizeUpdate: return "kDynamicTableSizeUpdate"; case HpackEntryType::kIndexedLiteralHeader: return "kIndexedLiteralHeader"; case HpackEntryType::kUnindexedLiteralHeader: return "kUnindexedLiteralHeader"; case HpackEntryType::kNeverIndexedLiteralHeader: return "kNeverIndexedLiteralHeader"; } return absl::StrCat("UnknownHpackEntryType(", static_cast<int>(v), ")"); } std::ostream& operator<<(std::ostream& out, HpackEntryType v) { return out << HpackEntryTypeToString(v); } }
#include "quiche/http2/hpack/http2_hpack_constants.h" #include <sstream> #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { TEST(HpackEntryTypeTest, HpackEntryTypeToString) { EXPECT_EQ("kIndexedHeader", HpackEntryTypeToString(HpackEntryType::kIndexedHeader)); EXPECT_EQ("kDynamicTableSizeUpdate", HpackEntryTypeToString(HpackEntryType::kDynamicTableSizeUpdate)); EXPECT_EQ("kIndexedLiteralHeader", HpackEntryTypeToString(HpackEntryType::kIndexedLiteralHeader)); EXPECT_EQ("kUnindexedLiteralHeader", HpackEntryTypeToString(HpackEntryType::kUnindexedLiteralHeader)); EXPECT_EQ("kNeverIndexedLiteralHeader", HpackEntryTypeToString(HpackEntryType::kNeverIndexedLiteralHeader)); EXPECT_EQ("UnknownHpackEntryType(12321)", HpackEntryTypeToString(static_cast<HpackEntryType>(12321))); } TEST(HpackEntryTypeTest, OutputHpackEntryType) { { std::stringstream log; log << HpackEntryType::kIndexedHeader; EXPECT_EQ("kIndexedHeader", log.str()); } { std::stringstream log; log << HpackEntryType::kDynamicTableSizeUpdate; EXPECT_EQ("kDynamicTableSizeUpdate", log.str()); } { std::stringstream log; log << HpackEntryType::kIndexedLiteralHeader; EXPECT_EQ("kIndexedLiteralHeader", log.str()); } { std::stringstream log; log << HpackEntryType::kUnindexedLiteralHeader; EXPECT_EQ("kUnindexedLiteralHeader", log.str()); } { std::stringstream log; log << HpackEntryType::kNeverIndexedLiteralHeader; EXPECT_EQ("kNeverIndexedLiteralHeader", log.str()); } { std::stringstream log; log << static_cast<HpackEntryType>(1234321); EXPECT_EQ("UnknownHpackEntryType(1234321)", log.str()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/http2_hpack_constants.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/http2_hpack_constants_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
0f922a03-0b86-4815-9e7d-f4c7c156aa1f
cpp
google/quiche
hpack_static_table
quiche/http2/hpack/hpack_static_table.cc
quiche/http2/hpack/hpack_static_table_test.cc
#include "quiche/http2/hpack/hpack_static_table.h" #include <cstddef> #include <string> #include <utility> #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_entry.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { HpackStaticTable::HpackStaticTable() = default; HpackStaticTable::~HpackStaticTable() = default; void HpackStaticTable::Initialize(const HpackStaticEntry* static_entry_table, size_t static_entry_count) { QUICHE_CHECK(!IsInitialized()); static_entries_.reserve(static_entry_count); for (const HpackStaticEntry* it = static_entry_table; it != static_entry_table + static_entry_count; ++it) { std::string name(it->name, it->name_len); std::string value(it->value, it->value_len); static_entries_.push_back(HpackEntry(std::move(name), std::move(value))); } int insertion_count = 0; for (const auto& entry : static_entries_) { auto result = static_index_.insert(std::make_pair( HpackLookupEntry{entry.name(), entry.value()}, insertion_count)); QUICHE_CHECK(result.second); static_name_index_.insert(std::make_pair(entry.name(), insertion_count)); ++insertion_count; } } bool HpackStaticTable::IsInitialized() const { return !static_entries_.empty(); } }
#include "quiche/http2/hpack/hpack_static_table.h" #include <set> #include <vector> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_header_table.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace test { namespace { class HpackStaticTableTest : public quiche::test::QuicheTest { protected: HpackStaticTableTest() : table_() {} HpackStaticTable table_; }; TEST_F(HpackStaticTableTest, Initialize) { EXPECT_FALSE(table_.IsInitialized()); table_.Initialize(HpackStaticTableVector().data(), HpackStaticTableVector().size()); EXPECT_TRUE(table_.IsInitialized()); const HpackHeaderTable::StaticEntryTable& static_entries = table_.GetStaticEntries(); EXPECT_EQ(kStaticTableSize, static_entries.size()); const HpackHeaderTable::NameValueToEntryMap& static_index = table_.GetStaticIndex(); EXPECT_EQ(kStaticTableSize, static_index.size()); const HpackHeaderTable::NameToEntryMap& static_name_index = table_.GetStaticNameIndex(); std::set<absl::string_view> names; for (const auto& entry : static_entries) { names.insert(entry.name()); } EXPECT_EQ(names.size(), static_name_index.size()); } TEST_F(HpackStaticTableTest, IsSingleton) { const HpackStaticTable* static_table_one = &ObtainHpackStaticTable(); const HpackStaticTable* static_table_two = &ObtainHpackStaticTable(); EXPECT_EQ(static_table_one, static_table_two); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_static_table.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_static_table_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
c92b34de-4bee-4567-aaac-b8cb9c8886ee
cpp
google/quiche
hpack_decoder_adapter
quiche/http2/hpack/hpack_decoder_adapter.cc
quiche/http2/hpack/hpack_decoder_adapter_test.cc
#include "quiche/http2/hpack/hpack_decoder_adapter.h" #include <cstddef> #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/core/spdy_headers_handler_interface.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/hpack/decoder/hpack_decoding_error.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { namespace { const size_t kMaxDecodeBufferSizeBytes = 32 * 1024; } HpackDecoderAdapter::HpackDecoderAdapter() : hpack_decoder_(&listener_adapter_, kMaxDecodeBufferSizeBytes), max_decode_buffer_size_bytes_(kMaxDecodeBufferSizeBytes), max_header_block_bytes_(0), header_block_started_(false), error_(http2::HpackDecodingError::kOk) {} HpackDecoderAdapter::~HpackDecoderAdapter() = default; void HpackDecoderAdapter::ApplyHeaderTableSizeSetting(size_t size_setting) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ApplyHeaderTableSizeSetting"; hpack_decoder_.ApplyHeaderTableSizeSetting(size_setting); } size_t HpackDecoderAdapter::GetCurrentHeaderTableSizeSetting() const { return hpack_decoder_.GetCurrentHeaderTableSizeSetting(); } void HpackDecoderAdapter::HandleControlFrameHeadersStart( SpdyHeadersHandlerInterface* handler) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::HandleControlFrameHeadersStart"; QUICHE_DCHECK(!header_block_started_); listener_adapter_.set_handler(handler); } bool HpackDecoderAdapter::HandleControlFrameHeadersData( const char* headers_data, size_t headers_data_length) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::HandleControlFrameHeadersData: len=" << headers_data_length; if (!header_block_started_) { header_block_started_ = true; if (!hpack_decoder_.StartDecodingBlock()) { header_block_started_ = false; error_ = hpack_decoder_.error(); return false; } } if (headers_data_length > 0) { QUICHE_DCHECK_NE(headers_data, nullptr); if (headers_data_length > max_decode_buffer_size_bytes_) { QUICHE_DVLOG(1) << "max_decode_buffer_size_bytes_ < headers_data_length: " << max_decode_buffer_size_bytes_ << " < " << headers_data_length; error_ = http2::HpackDecodingError::kFragmentTooLong; return false; } listener_adapter_.AddToTotalHpackBytes(headers_data_length); if (max_header_block_bytes_ != 0 && listener_adapter_.total_hpack_bytes() > max_header_block_bytes_) { error_ = http2::HpackDecodingError::kCompressedHeaderSizeExceedsLimit; return false; } http2::DecodeBuffer db(headers_data, headers_data_length); bool ok = hpack_decoder_.DecodeFragment(&db); QUICHE_DCHECK(!ok || db.Empty()) << "Remaining=" << db.Remaining(); if (!ok) { error_ = hpack_decoder_.error(); } return ok; } return true; } bool HpackDecoderAdapter::HandleControlFrameHeadersComplete() { QUICHE_DVLOG(2) << "HpackDecoderAdapter::HandleControlFrameHeadersComplete"; if (!hpack_decoder_.EndDecodingBlock()) { QUICHE_DVLOG(3) << "EndDecodingBlock returned false"; error_ = hpack_decoder_.error(); return false; } header_block_started_ = false; return true; } void HpackDecoderAdapter::set_max_decode_buffer_size_bytes( size_t max_decode_buffer_size_bytes) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::set_max_decode_buffer_size_bytes"; max_decode_buffer_size_bytes_ = max_decode_buffer_size_bytes; hpack_decoder_.set_max_string_size_bytes(max_decode_buffer_size_bytes); } void HpackDecoderAdapter::set_max_header_block_bytes( size_t max_header_block_bytes) { max_header_block_bytes_ = max_header_block_bytes; } HpackDecoderAdapter::ListenerAdapter::ListenerAdapter() : no_op_handler_(nullptr), handler_(&no_op_handler_) {} HpackDecoderAdapter::ListenerAdapter::~ListenerAdapter() = default; void HpackDecoderAdapter::ListenerAdapter::set_handler( SpdyHeadersHandlerInterface* handler) { QUICHE_CHECK_NE(handler, nullptr); handler_ = handler; } void HpackDecoderAdapter::ListenerAdapter::OnHeaderListStart() { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ListenerAdapter::OnHeaderListStart"; total_hpack_bytes_ = 0; total_uncompressed_bytes_ = 0; handler_->OnHeaderBlockStart(); } void HpackDecoderAdapter::ListenerAdapter::OnHeader(absl::string_view name, absl::string_view value) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ListenerAdapter::OnHeader:\n name: " << name << "\n value: " << value; total_uncompressed_bytes_ += name.size() + value.size(); handler_->OnHeader(name, value); } void HpackDecoderAdapter::ListenerAdapter::OnHeaderListEnd() { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ListenerAdapter::OnHeaderListEnd"; handler_->OnHeaderBlockEnd(total_uncompressed_bytes_, total_hpack_bytes_); handler_ = &no_op_handler_; } void HpackDecoderAdapter::ListenerAdapter::OnHeaderErrorDetected( absl::string_view error_message) { QUICHE_VLOG(1) << error_message; } }
#include "quiche/http2/hpack/hpack_decoder_adapter.h" #include <stdint.h> #include <cstddef> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/http2/core/recording_headers_handler.h" #include "quiche/http2/hpack/decoder/hpack_decoder.h" #include "quiche/http2/hpack/decoder/hpack_decoder_state.h" #include "quiche/http2/hpack/decoder/hpack_decoder_tables.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_encoder.h" #include "quiche/http2/hpack/hpack_output_stream.h" #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_text_utils.h" using ::http2::HpackEntryType; using ::http2::HpackStringPair; using ::http2::test::HpackBlockBuilder; using ::http2::test::HpackDecoderPeer; using ::testing::ElementsAre; using ::testing::Pair; namespace http2 { namespace test { class HpackDecoderStatePeer { public: static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) { return &state->decoder_tables_; } }; class HpackDecoderPeer { public: static HpackDecoderState* GetDecoderState(HpackDecoder* decoder) { return &decoder->decoder_state_; } static HpackDecoderTables* GetDecoderTables(HpackDecoder* decoder) { return HpackDecoderStatePeer::GetDecoderTables(GetDecoderState(decoder)); } }; } } namespace spdy { namespace test { class HpackDecoderAdapterPeer { public: explicit HpackDecoderAdapterPeer(HpackDecoderAdapter* decoder) : decoder_(decoder) {} void HandleHeaderRepresentation(const std::string& name, const std::string& value) { decoder_->listener_adapter_.OnHeader(name, value); } http2::HpackDecoderTables* GetDecoderTables() { return HpackDecoderPeer::GetDecoderTables(&decoder_->hpack_decoder_); } const HpackStringPair* GetTableEntry(uint32_t index) { return GetDecoderTables()->Lookup(index); } size_t current_header_table_size() { return GetDecoderTables()->current_header_table_size(); } size_t header_table_size_limit() { return GetDecoderTables()->header_table_size_limit(); } void set_header_table_size_limit(size_t size) { return GetDecoderTables()->DynamicTableSizeUpdate(size); } private: HpackDecoderAdapter* decoder_; }; class HpackEncoderPeer { public: static void CookieToCrumbs(const HpackEncoder::Representation& cookie, HpackEncoder::Representations* crumbs_out) { HpackEncoder::CookieToCrumbs(cookie, crumbs_out); } }; namespace { const bool kNoCheckDecodedSize = false; const char* kCookieKey = "cookie"; class HpackDecoderAdapterTest : public quiche::test::QuicheTestWithParam<bool> { protected: HpackDecoderAdapterTest() : decoder_(), decoder_peer_(&decoder_) {} void SetUp() override { randomly_split_input_buffer_ = GetParam(); } void HandleControlFrameHeadersStart() { bytes_passed_in_ = 0; decoder_.HandleControlFrameHeadersStart(&handler_); } bool HandleControlFrameHeadersData(absl::string_view str) { QUICHE_VLOG(3) << "HandleControlFrameHeadersData:\n" << quiche::QuicheTextUtils::HexDump(str); bytes_passed_in_ += str.size(); return decoder_.HandleControlFrameHeadersData(str.data(), str.size()); } bool HandleControlFrameHeadersComplete() { bool rc = decoder_.HandleControlFrameHeadersComplete(); return rc; } bool DecodeHeaderBlock(absl::string_view str, bool check_decoded_size = true) { EXPECT_FALSE(decode_has_failed_); HandleControlFrameHeadersStart(); if (randomly_split_input_buffer_) { do { size_t bytes = str.size(); if (!str.empty()) { bytes = random_.Uniform(str.size()) + 1; } EXPECT_LE(bytes, str.size()); if (!HandleControlFrameHeadersData(str.substr(0, bytes))) { decode_has_failed_ = true; return false; } str.remove_prefix(bytes); } while (!str.empty()); } else if (!HandleControlFrameHeadersData(str)) { decode_has_failed_ = true; return false; } if (!HandleControlFrameHeadersComplete()) { decode_has_failed_ = true; return false; } EXPECT_EQ(handler_.compressed_header_bytes(), bytes_passed_in_); if (check_decoded_size) { EXPECT_EQ(handler_.uncompressed_header_bytes(), SizeOfHeaders(decoded_block())); } return true; } bool EncodeAndDecodeDynamicTableSizeUpdates(size_t first, size_t second) { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(first); if (second != first) { hbb.AppendDynamicTableSizeUpdate(second); } return DecodeHeaderBlock(hbb.buffer()); } const quiche::HttpHeaderBlock& decoded_block() const { return handler_.decoded_block(); } static size_t SizeOfHeaders(const quiche::HttpHeaderBlock& headers) { size_t size = 0; for (const auto& kv : headers) { if (kv.first == kCookieKey) { HpackEncoder::Representations crumbs; HpackEncoderPeer::CookieToCrumbs(kv, &crumbs); for (const auto& crumb : crumbs) { size += crumb.first.size() + crumb.second.size(); } } else { size += kv.first.size() + kv.second.size(); } } return size; } const quiche::HttpHeaderBlock& DecodeBlockExpectingSuccess( absl::string_view str) { EXPECT_TRUE(DecodeHeaderBlock(str)); return decoded_block(); } void expectEntry(size_t index, size_t size, const std::string& name, const std::string& value) { const HpackStringPair* entry = decoder_peer_.GetTableEntry(index); EXPECT_EQ(name, entry->name) << "index " << index; EXPECT_EQ(value, entry->value); EXPECT_EQ(size, entry->size()); } quiche::HttpHeaderBlock MakeHeaderBlock( const std::vector<std::pair<std::string, std::string>>& headers) { quiche::HttpHeaderBlock result; for (const auto& kv : headers) { result.AppendValueOrAddHeader(kv.first, kv.second); } return result; } http2::test::Http2Random random_; HpackDecoderAdapter decoder_; test::HpackDecoderAdapterPeer decoder_peer_; RecordingHeadersHandler handler_; const quiche::HttpHeaderBlock dummy_block_; bool randomly_split_input_buffer_; bool decode_has_failed_ = false; size_t bytes_passed_in_; }; INSTANTIATE_TEST_SUITE_P(NoHandler, HpackDecoderAdapterTest, ::testing::Bool()); INSTANTIATE_TEST_SUITE_P(WithHandler, HpackDecoderAdapterTest, ::testing::Bool()); TEST_P(HpackDecoderAdapterTest, ApplyHeaderTableSizeSetting) { EXPECT_EQ(4096u, decoder_.GetCurrentHeaderTableSizeSetting()); decoder_.ApplyHeaderTableSizeSetting(12 * 1024); EXPECT_EQ(12288u, decoder_.GetCurrentHeaderTableSizeSetting()); } TEST_P(HpackDecoderAdapterTest, AddHeaderDataWithHandleControlFrameHeadersData) { HandleControlFrameHeadersStart(); const size_t kMaxBufferSizeBytes = 50; const std::string a_value = std::string(49, 'x'); decoder_.set_max_decode_buffer_size_bytes(kMaxBufferSizeBytes); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, "a", false, a_value); const std::string& s = hbb.buffer(); EXPECT_GT(s.size(), kMaxBufferSizeBytes); EXPECT_TRUE(HandleControlFrameHeadersData(s.substr(0, s.size() / 2))); EXPECT_TRUE(HandleControlFrameHeadersData(s.substr(s.size() / 2))); EXPECT_FALSE(HandleControlFrameHeadersData(s)); quiche::HttpHeaderBlock expected_block = MakeHeaderBlock({{"a", a_value}}); EXPECT_EQ(expected_block, decoded_block()); } TEST_P(HpackDecoderAdapterTest, NameTooLong) { const size_t kMaxBufferSizeBytes = 50; const std::string name = std::string(2 * kMaxBufferSizeBytes, 'x'); const std::string value = "abc"; decoder_.set_max_decode_buffer_size_bytes(kMaxBufferSizeBytes); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, name, false, value); const size_t fragment_size = (3 * kMaxBufferSizeBytes) / 2; const std::string fragment = hbb.buffer().substr(0, fragment_size); HandleControlFrameHeadersStart(); EXPECT_FALSE(HandleControlFrameHeadersData(fragment)); } TEST_P(HpackDecoderAdapterTest, HeaderTooLongToBuffer) { const std::string name = "some-key"; const std::string value = "some-value"; const size_t kMaxBufferSizeBytes = name.size() + value.size() - 2; decoder_.set_max_decode_buffer_size_bytes(kMaxBufferSizeBytes); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, name, false, value); const size_t fragment_size = hbb.size() - 1; const std::string fragment = hbb.buffer().substr(0, fragment_size); HandleControlFrameHeadersStart(); EXPECT_FALSE(HandleControlFrameHeadersData(fragment)); } TEST_P(HpackDecoderAdapterTest, HeaderBlockTooLong) { const std::string name = "some-key"; const std::string value = "some-value"; const size_t kMaxBufferSizeBytes = 1024; HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, false, name, false, value); while (hbb.size() < kMaxBufferSizeBytes) { hbb.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, false, "", false, ""); } HandleControlFrameHeadersStart(); EXPECT_TRUE(HandleControlFrameHeadersData(hbb.buffer())); EXPECT_TRUE(HandleControlFrameHeadersComplete()); decoder_.set_max_header_block_bytes(kMaxBufferSizeBytes); HandleControlFrameHeadersStart(); EXPECT_FALSE(HandleControlFrameHeadersData(hbb.buffer())); } TEST_P(HpackDecoderAdapterTest, DecodeWithIncompleteData) { HandleControlFrameHeadersStart(); EXPECT_TRUE(HandleControlFrameHeadersData("\x82\x85\x82")); std::vector<std::pair<std::string, std::string>> expected_headers = { {":method", "GET"}, {":path", "/index.html"}, {":method", "GET"}}; quiche::HttpHeaderBlock expected_block1 = MakeHeaderBlock(expected_headers); EXPECT_EQ(expected_block1, decoded_block()); EXPECT_TRUE( HandleControlFrameHeadersData("\x40\x03goo" "\x03gar\xbe\x40\x04spam")); expected_headers.push_back({"goo", "gar"}); expected_headers.push_back({"goo", "gar"}); quiche::HttpHeaderBlock expected_block2 = MakeHeaderBlock(expected_headers); EXPECT_EQ(expected_block2, decoded_block()); EXPECT_TRUE(HandleControlFrameHeadersData("\x04gggs")); EXPECT_TRUE(HandleControlFrameHeadersComplete()); expected_headers.push_back({"spam", "gggs"}); quiche::HttpHeaderBlock expected_block3 = MakeHeaderBlock(expected_headers); EXPECT_EQ(expected_block3, decoded_block()); } TEST_P(HpackDecoderAdapterTest, HandleHeaderRepresentation) { HandleControlFrameHeadersStart(); HandleControlFrameHeadersData(""); decoder_peer_.HandleHeaderRepresentation("cookie", " part 1"); decoder_peer_.HandleHeaderRepresentation("cookie", "part 2 "); decoder_peer_.HandleHeaderRepresentation("cookie", "part3"); decoder_peer_.HandleHeaderRepresentation("passed-through", std::string("foo\0baz", 7)); decoder_peer_.HandleHeaderRepresentation("joined", "joined"); decoder_peer_.HandleHeaderRepresentation("joineD", "value 1"); decoder_peer_.HandleHeaderRepresentation("joineD", "value 2"); decoder_peer_.HandleHeaderRepresentation("empty", ""); decoder_peer_.HandleHeaderRepresentation("empty-joined", ""); decoder_peer_.HandleHeaderRepresentation("empty-joined", "foo"); decoder_peer_.HandleHeaderRepresentation("empty-joined", ""); decoder_peer_.HandleHeaderRepresentation("empty-joined", ""); decoder_peer_.HandleHeaderRepresentation("cookie", " fin!"); decoder_.HandleControlFrameHeadersComplete(); EXPECT_THAT( decoded_block(), ElementsAre( Pair("cookie", " part 1; part 2 ; part3; fin!"), Pair("passed-through", absl::string_view("foo\0baz", 7)), Pair("joined", absl::string_view("joined\0value 1\0value 2", 22)), Pair("empty", ""), Pair("empty-joined", absl::string_view("\0foo\0\0", 6)))); } TEST_P(HpackDecoderAdapterTest, IndexedHeaderStatic) { const quiche::HttpHeaderBlock& header_set1 = DecodeBlockExpectingSuccess("\x82\x85"); quiche::HttpHeaderBlock expected_header_set1; expected_header_set1[":method"] = "GET"; expected_header_set1[":path"] = "/index.html"; EXPECT_EQ(expected_header_set1, header_set1); const quiche::HttpHeaderBlock& header_set2 = DecodeBlockExpectingSuccess("\x82"); quiche::HttpHeaderBlock expected_header_set2; expected_header_set2[":method"] = "GET"; EXPECT_EQ(expected_header_set2, header_set2); } TEST_P(HpackDecoderAdapterTest, IndexedHeaderDynamic) { const quiche::HttpHeaderBlock& header_set1 = DecodeBlockExpectingSuccess( "\x40\x03" "foo" "\x03" "bar"); quiche::HttpHeaderBlock expected_header_set1; expected_header_set1["foo"] = "bar"; EXPECT_EQ(expected_header_set1, header_set1); const quiche::HttpHeaderBlock& header_set2 = DecodeBlockExpectingSuccess( "\xbe\x40\x04" "spam" "\x04" "eggs"); quiche::HttpHeaderBlock expected_header_set2; expected_header_set2["foo"] = "bar"; expected_header_set2["spam"] = "eggs"; EXPECT_EQ(expected_header_set2, header_set2); const quiche::HttpHeaderBlock& header_set3 = DecodeBlockExpectingSuccess("\xbe"); quiche::HttpHeaderBlock expected_header_set3; expected_header_set3["spam"] = "eggs"; EXPECT_EQ(expected_header_set3, header_set3); } TEST_P(HpackDecoderAdapterTest, InvalidIndexedHeader) { EXPECT_FALSE(DecodeHeaderBlock("\xbe")); } TEST_P(HpackDecoderAdapterTest, ContextUpdateMaximumSize) { EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(126); input = output_stream.TakeString(); EXPECT_TRUE(DecodeHeaderBlock(input)); EXPECT_EQ(126u, decoder_peer_.header_table_size_limit()); } { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(kDefaultHeaderTableSizeSetting); input = output_stream.TakeString(); EXPECT_TRUE(DecodeHeaderBlock(input)); EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); } { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(kDefaultHeaderTableSizeSetting + 1); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, TwoTableSizeUpdates) { std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(0); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(122); input = output_stream.TakeString(); EXPECT_TRUE(DecodeHeaderBlock(input)); EXPECT_EQ(122u, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, ThreeTableSizeUpdatesError) { std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(5); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(10); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(15); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(10u, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, TableSizeUpdateSecondError) { std::string input; { HpackOutputStream output_stream; output_stream.AppendBytes("\x82\x85"); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(123); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, TableSizeUpdateFirstThirdError) { std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(60); output_stream.AppendBytes("\x82\x85"); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(125); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(60u, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, LiteralHeaderNoIndexing) { const char input[] = "\x04\x0c/sample/path\x00\x06:path2\x0e/sample/path/2"; const quiche::HttpHeaderBlock& header_set = DecodeBlockExpectingSuccess( absl::string_view(input, ABSL_ARRAYSIZE(input) - 1)); quiche::HttpHeaderBlock expected_header_set; expected_header_set[":path"] = "/sample/path"; expected_header_set[":path2"] = "/sample/path/2"; EXPECT_EQ(expected_header_set, header_set); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderIncrementalIndexing) { const char input[] = "\x44\x0c/sample/path\x40\x06:path2\x0e/sample/path/2"; const quiche::HttpHeaderBlock& header_set = DecodeBlockExpectingSuccess( absl::string_view(input, ABSL_ARRAYSIZE(input) - 1)); quiche::HttpHeaderBlock expected_header_set; expected_header_set[":path"] = "/sample/path"; expected_header_set[":path2"] = "/sample/path/2"; EXPECT_EQ(expected_header_set, header_set); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderWithIndexingInvalidNameIndex) { decoder_.ApplyHeaderTableSizeSetting(0); EXPECT_TRUE(EncodeAndDecodeDynamicTableSizeUpdates(0, 0)); EXPECT_TRUE(DecodeHeaderBlock(absl::string_view("\x7d\x03ooo"))); EXPECT_FALSE(DecodeHeaderBlock(absl::string_view("\x7e\x03ooo"))); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderNoIndexingInvalidNameIndex) { EXPECT_TRUE(DecodeHeaderBlock(absl::string_view("\x0f\x2e\x03ooo"))); EXPECT_FALSE(DecodeHeaderBlock(absl::string_view("\x0f\x2f\x03ooo"))); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderNeverIndexedInvalidNameIndex) { EXPECT_TRUE(DecodeHeaderBlock(absl::string_view("\x1f\x2e\x03ooo"))); EXPECT_FALSE(DecodeHeaderBlock(absl::string_view("\x1f\x2f\x03ooo"))); } TEST_P(HpackDecoderAdapterTest, TruncatedIndex) { EXPECT_FALSE(DecodeHeaderBlock("\xff")); } TEST_P(HpackDecoderAdapterTest, TruncatedHuffmanLiteral) { std::string first; ASSERT_TRUE(absl::HexStringToBytes("418cf1e3c2e5f23a6ba0ab90f4ff", &first)); EXPECT_TRUE(DecodeHeaderBlock(first)); first.pop_back(); EXPECT_FALSE(DecodeHeaderBlock(first)); } TEST_P(HpackDecoderAdapterTest, HuffmanEOSError) { std::string first; ASSERT_TRUE(absl::HexStringToBytes("418cf1e3c2e5f23a6ba0ab90f4ff", &first)); EXPECT_TRUE(DecodeHeaderBlock(first)); ASSERT_TRUE(absl::HexStringToBytes("418df1e3c2e5f23a6ba0ab90f4ffff", &first)); EXPECT_FALSE(DecodeHeaderBlock(first)); } TEST_P(HpackDecoderAdapterTest, BasicC31) { HpackEncoder encoder; quiche::HttpHeaderBlock expected_header_set; expected_header_set[":method"] = "GET"; expected_header_set[":scheme"] = "http"; expected_header_set[":path"] = "/"; expected_header_set[":authority"] = "www.example.com"; std::string encoded_header_set = encoder.EncodeHeaderBlock(expected_header_set); EXPECT_TRUE(DecodeHeaderBlock(encoded_header_set)); EXPECT_EQ(expected_header_set, decoded_block()); } TEST_P(HpackDecoderAdapterTest, SectionC4RequestHuffmanExamples) { std::string first; ASSERT_TRUE( absl::HexStringToBytes("828684418cf1e3c2e5f23a6ba0ab90f4ff", &first)); const quiche::HttpHeaderBlock& first_header_set = DecodeBlockExpectingSuccess(first); EXPECT_THAT(first_header_set, ElementsAre( Pair(":method", "GET"), Pair(":scheme", "http"), Pair(":path", "/"), Pair(":authority", "www.example.com"))); expectEntry(62, 57, ":authority", "www.example.com"); EXPECT_EQ(57u, decoder_peer_.current_header_table_size()); std::string second; ASSERT_TRUE(absl::HexStringToBytes("828684be5886a8eb10649cbf", &second)); const quiche::HttpHeaderBlock& second_header_set = DecodeBlockExpectingSuccess(second); EXPECT_THAT(second_header_set, ElementsAre( Pair(":method", "GET"), Pair(":scheme", "http"), Pair(":path", "/"), Pair(":authority", "www.example.com"), Pair("cache-control", "no-cache"))); expectEntry(62, 53, "cache-control", "no-cache"); expectEntry(63, 57, ":authority", "www.example.com"); EXPECT_EQ(110u, decoder_peer_.current_header_table_size()); std::string third; ASSERT_TRUE(absl::HexStringToBytes( "828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf", &third)); const quiche::HttpHeaderBlock& third_header_set = DecodeBlockExpectingSuccess(third); EXPECT_THAT( third_header_set, ElementsAre( Pair(":method", "GET"), Pair(":scheme", "https"), Pair(":path", "/index.html"), Pair(":authority", "www.example.com"), Pair("custom-key", "custom-value"))); expectEntry(62, 54, "custom-key", "custom-value"); expectEntry(63, 53, "cache-control", "no-cache"); expectEntry(64, 57, ":authority", "www.example.com"); EXPECT_EQ(164u, decoder_peer_.current_header_table_size()); } TEST_P(HpackDecoderAdapterTest, SectionC6ResponseHuffmanExamples) { decoder_peer_.set_header_table_size_limit(256); std::string first; ASSERT_TRUE(absl::HexStringToBytes( "488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e" "919d29ad171863c78f0b97c8e9ae82ae43d3", &first)); const quiche::HttpHeaderBlock& first_header_set = DecodeBlockExpectingSuccess(first); EXPECT_THAT(first_header_set, ElementsAre( Pair(":status", "302"), Pair("cache-control", "private"), Pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), Pair("location", "https: expectEntry(62, 63, "location", "https: expectEntry(63, 65, "date", "Mon, 21 Oct 2013 20:13:21 GMT"); expectEntry(64, 52, "cache-control", "private"); expectEntry(65, 42, ":status", "302"); EXPECT_EQ(222u, decoder_peer_.current_header_table_size()); std::string second; ASSERT_TRUE(absl::HexStringToBytes("4883640effc1c0bf", &second)); const quiche::HttpHeaderBlock& second_header_set = DecodeBlockExpectingSuccess(second); EXPECT_THAT(second_header_set, ElementsAre( Pair(":status", "307"), Pair("cache-control", "private"), Pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), Pair("location", "https: expectEntry(62, 42, ":status", "307"); expectEntry(63, 63, "location", "https: expectEntry(64, 65, "date", "Mon, 21 Oct 2013 20:13:21 GMT"); expectEntry(65, 52, "cache-control", "private"); EXPECT_EQ(222u, decoder_peer_.current_header_table_size()); std::string third; ASSERT_TRUE(absl::HexStringToBytes( "88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7" "821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed" "4ee5b1063d5007", &third)); const quiche::HttpHeaderBlock& third_header_set = DecodeBlockExpectingSuccess(third); EXPECT_THAT(third_header_set, ElementsAre( Pair(":status", "200"), Pair("cache-control", "private"), Pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), Pair("location", "https: Pair("content-encoding", "gzip"), Pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU;" " max-age=3600; version=1"))); expectEntry(62, 98, "set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU;" " max-age=3600; version=1"); expectEntry(63, 52, "content-encoding", "gzip"); expectEntry(64, 65, "date", "Mon, 21 Oct 2013 20:13:22 GMT"); EXPECT_EQ(215u, decoder_peer_.current_header_table_size()); } TEST_P(HpackDecoderAdapterTest, ReuseNameOfEvictedEntry) { decoder_.ApplyHeaderTableSizeSetting(63); HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(0); hbb.AppendDynamicTableSizeUpdate(63); const absl::string_view name("some-name"); const absl::string_view value1("some-value"); const absl::string_view value2("another-value"); const absl::string_view value3("yet-another-value"); hbb.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, false, name, false, value1); hbb.AppendIndexedHeader(62); hbb.AppendNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 62, false, value2); hbb.AppendIndexedHeader(62); hbb.AppendNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 62, false, value3); hbb.AppendIndexedHeader(62); EXPECT_TRUE(DecodeHeaderBlock(hbb.buffer(), kNoCheckDecodedSize)); quiche::HttpHeaderBlock expected_header_set; expected_header_set.AppendValueOrAddHeader(name, value1); expected_header_set.AppendValueOrAddHeader(name, value1); expected_header_set.AppendValueOrAddHeader(name, value2); expected_header_set.AppendValueOrAddHeader(name, value2); expected_header_set.AppendValueOrAddHeader(name, value3); expected_header_set.AppendValueOrAddHeader(name, value3); std::string joined_values = expected_header_set[name].as_string(); EXPECT_EQ(joined_values.size(), 2 * value1.size() + 2 * value2.size() + 2 * value3.size() + 5); EXPECT_EQ(expected_header_set, decoded_block()); EXPECT_EQ(handler_.uncompressed_header_bytes(), 6 * name.size() + 2 * value1.size() + 2 * value2.size() + 2 * value3.size()); } TEST_P(HpackDecoderAdapterTest, Cookies) { quiche::HttpHeaderBlock expected_header_set; expected_header_set["cookie"] = "foo; bar"; std::string encoded_block; ASSERT_TRUE(absl::HexStringToBytes("608294e76003626172", &encoded_block)); EXPECT_TRUE(DecodeHeaderBlock(encoded_block)); EXPECT_EQ(expected_header_set, decoded_block()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_decoder_adapter.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_decoder_adapter_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
9cc88025-8857-47e4-adbf-2c50ad2316a5
cpp
google/quiche
hpack_entry
quiche/http2/hpack/hpack_entry.cc
quiche/http2/hpack/hpack_entry_test.cc
#include "quiche/http2/hpack/hpack_entry.h" #include <cstddef> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace spdy { HpackEntry::HpackEntry(std::string name, std::string value) : name_(std::move(name)), value_(std::move(value)) {} size_t HpackEntry::Size(absl::string_view name, absl::string_view value) { return name.size() + value.size() + kHpackEntrySizeOverhead; } size_t HpackEntry::Size() const { return Size(name(), value()); } std::string HpackEntry::GetDebugString() const { return absl::StrCat("{ name: \"", name_, "\", value: \"", value_, "\" }"); } }
#include "quiche/http2/hpack/hpack_entry.h" #include "absl/hash/hash.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace { TEST(HpackLookupEntryTest, EntryNamesDiffer) { HpackLookupEntry entry1{"header", "value"}; HpackLookupEntry entry2{"HEADER", "value"}; EXPECT_FALSE(entry1 == entry2); EXPECT_NE(absl::Hash<HpackLookupEntry>()(entry1), absl::Hash<HpackLookupEntry>()(entry2)); } TEST(HpackLookupEntryTest, EntryValuesDiffer) { HpackLookupEntry entry1{"header", "value"}; HpackLookupEntry entry2{"header", "VALUE"}; EXPECT_FALSE(entry1 == entry2); EXPECT_NE(absl::Hash<HpackLookupEntry>()(entry1), absl::Hash<HpackLookupEntry>()(entry2)); } TEST(HpackLookupEntryTest, EntriesEqual) { HpackLookupEntry entry1{"name", "value"}; HpackLookupEntry entry2{"name", "value"}; EXPECT_TRUE(entry1 == entry2); EXPECT_EQ(absl::Hash<HpackLookupEntry>()(entry1), absl::Hash<HpackLookupEntry>()(entry2)); } TEST(HpackEntryTest, BasicEntry) { HpackEntry entry("header-name", "header value"); EXPECT_EQ("header-name", entry.name()); EXPECT_EQ("header value", entry.value()); EXPECT_EQ(55u, entry.Size()); EXPECT_EQ(55u, HpackEntry::Size("header-name", "header value")); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_entry.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_entry_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
3e506691-0765-4cfa-bb60-211272e20c60
cpp
google/quiche
hpack_output_stream
quiche/http2/hpack/hpack_output_stream.cc
quiche/http2/hpack/hpack_output_stream_test.cc
#include "quiche/http2/hpack/hpack_output_stream.h" #include <cstddef> #include <cstdint> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { HpackOutputStream::HpackOutputStream() : bit_offset_(0) {} HpackOutputStream::~HpackOutputStream() = default; void HpackOutputStream::AppendBits(uint8_t bits, size_t bit_size) { QUICHE_DCHECK_GT(bit_size, 0u); QUICHE_DCHECK_LE(bit_size, 8u); QUICHE_DCHECK_EQ(bits >> bit_size, 0); size_t new_bit_offset = bit_offset_ + bit_size; if (bit_offset_ == 0) { QUICHE_DCHECK_LE(bit_size, 8u); buffer_.append(1, bits << (8 - bit_size)); } else if (new_bit_offset <= 8) { buffer_.back() |= bits << (8 - new_bit_offset); } else { buffer_.back() |= bits >> (new_bit_offset - 8); buffer_.append(1, bits << (16 - new_bit_offset)); } bit_offset_ = new_bit_offset % 8; } void HpackOutputStream::AppendPrefix(HpackPrefix prefix) { AppendBits(prefix.bits, prefix.bit_size); } void HpackOutputStream::AppendBytes(absl::string_view buffer) { QUICHE_DCHECK_EQ(bit_offset_, 0u); buffer_.append(buffer.data(), buffer.size()); } void HpackOutputStream::AppendUint32(uint32_t I) { size_t N = 8 - bit_offset_; uint8_t max_first_byte = static_cast<uint8_t>((1 << N) - 1); if (I < max_first_byte) { AppendBits(static_cast<uint8_t>(I), N); } else { AppendBits(max_first_byte, N); I -= max_first_byte; while ((I & ~0x7f) != 0) { buffer_.append(1, (I & 0x7f) | 0x80); I >>= 7; } AppendBits(static_cast<uint8_t>(I), 8); } QUICHE_DCHECK_EQ(bit_offset_, 0u); } std::string* HpackOutputStream::MutableString() { QUICHE_DCHECK_EQ(bit_offset_, 0u); return &buffer_; } std::string HpackOutputStream::TakeString() { QUICHE_DCHECK_EQ(bit_offset_, 0u); std::string out = std::move(buffer_); buffer_ = {}; bit_offset_ = 0; return out; } std::string HpackOutputStream::BoundedTakeString(size_t max_size) { if (buffer_.size() > max_size) { std::string overflow = buffer_.substr(max_size); buffer_.resize(max_size); std::string out = std::move(buffer_); buffer_ = std::move(overflow); return out; } else { return TakeString(); } } }
#include "quiche/http2/hpack/hpack_output_stream.h" #include <cstdint> #include <string> #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace { TEST(HpackOutputStreamTest, AppendBits) { HpackOutputStream output_stream; std::string expected_str; output_stream.AppendBits(0x1, 1); expected_str.append(1, 0x00); expected_str.back() |= (0x1 << 7); output_stream.AppendBits(0x0, 1); output_stream.AppendBits(0x3, 2); *expected_str.rbegin() |= (0x3 << 4); output_stream.AppendBits(0x0, 2); output_stream.AppendBits(0x7, 3); *expected_str.rbegin() |= (0x7 >> 1); expected_str.append(1, 0x00); expected_str.back() |= (0x7 << 7); output_stream.AppendBits(0x0, 7); std::string str = output_stream.TakeString(); EXPECT_EQ(expected_str, str); } std::string EncodeUint32(uint8_t N, uint32_t I) { HpackOutputStream output_stream; if (N < 8) { output_stream.AppendBits(0x00, 8 - N); } output_stream.AppendUint32(I); std::string str = output_stream.TakeString(); return str; } TEST(HpackOutputStreamTest, OneByteIntegersEightBitPrefix) { EXPECT_EQ(std::string("\x00", 1), EncodeUint32(8, 0x00)); EXPECT_EQ("\x7f", EncodeUint32(8, 0x7f)); EXPECT_EQ("\xfe", EncodeUint32(8, 0xfe)); } TEST(HpackOutputStreamTest, TwoByteIntegersEightBitPrefix) { EXPECT_EQ(std::string("\xff\x00", 2), EncodeUint32(8, 0xff)); EXPECT_EQ("\xff\x01", EncodeUint32(8, 0x0100)); EXPECT_EQ("\xff\x7f", EncodeUint32(8, 0x017e)); } TEST(HpackOutputStreamTest, ThreeByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x01", EncodeUint32(8, 0x017f)); EXPECT_EQ("\xff\x80\x1e", EncodeUint32(8, 0x0fff)); EXPECT_EQ("\xff\xff\x7f", EncodeUint32(8, 0x40fe)); } TEST(HpackOutputStreamTest, FourByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x80\x01", EncodeUint32(8, 0x40ff)); EXPECT_EQ("\xff\x80\xfe\x03", EncodeUint32(8, 0xffff)); EXPECT_EQ("\xff\xff\xff\x7f", EncodeUint32(8, 0x002000fe)); } TEST(HpackOutputStreamTest, FiveByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x80\x80\x01", EncodeUint32(8, 0x002000ff)); EXPECT_EQ("\xff\x80\xfe\xff\x07", EncodeUint32(8, 0x00ffffff)); EXPECT_EQ("\xff\xff\xff\xff\x7f", EncodeUint32(8, 0x100000fe)); } TEST(HpackOutputStreamTest, SixByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x80\x80\x80\x01", EncodeUint32(8, 0x100000ff)); EXPECT_EQ("\xff\x80\xfe\xff\xff\x0f", EncodeUint32(8, 0xffffffff)); } TEST(HpackOutputStreamTest, OneByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ(std::string("\x00", 1), EncodeUint32(7, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(6, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(5, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(4, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(3, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(2, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(1, 0x00)); EXPECT_EQ("\x7e", EncodeUint32(7, 0x7e)); EXPECT_EQ("\x3e", EncodeUint32(6, 0x3e)); EXPECT_EQ("\x1e", EncodeUint32(5, 0x1e)); EXPECT_EQ("\x0e", EncodeUint32(4, 0x0e)); EXPECT_EQ("\x06", EncodeUint32(3, 0x06)); EXPECT_EQ("\x02", EncodeUint32(2, 0x02)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(1, 0x00)); } TEST(HpackOutputStreamTest, TwoByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ(std::string("\x7f\x00", 2), EncodeUint32(7, 0x7f)); EXPECT_EQ(std::string("\x3f\x00", 2), EncodeUint32(6, 0x3f)); EXPECT_EQ(std::string("\x1f\x00", 2), EncodeUint32(5, 0x1f)); EXPECT_EQ(std::string("\x0f\x00", 2), EncodeUint32(4, 0x0f)); EXPECT_EQ(std::string("\x07\x00", 2), EncodeUint32(3, 0x07)); EXPECT_EQ(std::string("\x03\x00", 2), EncodeUint32(2, 0x03)); EXPECT_EQ(std::string("\x01\x00", 2), EncodeUint32(1, 0x01)); EXPECT_EQ("\x7f\x7f", EncodeUint32(7, 0xfe)); EXPECT_EQ("\x3f\x7f", EncodeUint32(6, 0xbe)); EXPECT_EQ("\x1f\x7f", EncodeUint32(5, 0x9e)); EXPECT_EQ("\x0f\x7f", EncodeUint32(4, 0x8e)); EXPECT_EQ("\x07\x7f", EncodeUint32(3, 0x86)); EXPECT_EQ("\x03\x7f", EncodeUint32(2, 0x82)); EXPECT_EQ("\x01\x7f", EncodeUint32(1, 0x80)); } TEST(HpackOutputStreamTest, ThreeByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x01", EncodeUint32(7, 0xff)); EXPECT_EQ("\x3f\x80\x01", EncodeUint32(6, 0xbf)); EXPECT_EQ("\x1f\x80\x01", EncodeUint32(5, 0x9f)); EXPECT_EQ("\x0f\x80\x01", EncodeUint32(4, 0x8f)); EXPECT_EQ("\x07\x80\x01", EncodeUint32(3, 0x87)); EXPECT_EQ("\x03\x80\x01", EncodeUint32(2, 0x83)); EXPECT_EQ("\x01\x80\x01", EncodeUint32(1, 0x81)); EXPECT_EQ("\x7f\xff\x7f", EncodeUint32(7, 0x407e)); EXPECT_EQ("\x3f\xff\x7f", EncodeUint32(6, 0x403e)); EXPECT_EQ("\x1f\xff\x7f", EncodeUint32(5, 0x401e)); EXPECT_EQ("\x0f\xff\x7f", EncodeUint32(4, 0x400e)); EXPECT_EQ("\x07\xff\x7f", EncodeUint32(3, 0x4006)); EXPECT_EQ("\x03\xff\x7f", EncodeUint32(2, 0x4002)); EXPECT_EQ("\x01\xff\x7f", EncodeUint32(1, 0x4000)); } TEST(HpackOutputStreamTest, FourByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x80\x01", EncodeUint32(7, 0x407f)); EXPECT_EQ("\x3f\x80\x80\x01", EncodeUint32(6, 0x403f)); EXPECT_EQ("\x1f\x80\x80\x01", EncodeUint32(5, 0x401f)); EXPECT_EQ("\x0f\x80\x80\x01", EncodeUint32(4, 0x400f)); EXPECT_EQ("\x07\x80\x80\x01", EncodeUint32(3, 0x4007)); EXPECT_EQ("\x03\x80\x80\x01", EncodeUint32(2, 0x4003)); EXPECT_EQ("\x01\x80\x80\x01", EncodeUint32(1, 0x4001)); EXPECT_EQ("\x7f\xff\xff\x7f", EncodeUint32(7, 0x20007e)); EXPECT_EQ("\x3f\xff\xff\x7f", EncodeUint32(6, 0x20003e)); EXPECT_EQ("\x1f\xff\xff\x7f", EncodeUint32(5, 0x20001e)); EXPECT_EQ("\x0f\xff\xff\x7f", EncodeUint32(4, 0x20000e)); EXPECT_EQ("\x07\xff\xff\x7f", EncodeUint32(3, 0x200006)); EXPECT_EQ("\x03\xff\xff\x7f", EncodeUint32(2, 0x200002)); EXPECT_EQ("\x01\xff\xff\x7f", EncodeUint32(1, 0x200000)); } TEST(HpackOutputStreamTest, FiveByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x80\x80\x01", EncodeUint32(7, 0x20007f)); EXPECT_EQ("\x3f\x80\x80\x80\x01", EncodeUint32(6, 0x20003f)); EXPECT_EQ("\x1f\x80\x80\x80\x01", EncodeUint32(5, 0x20001f)); EXPECT_EQ("\x0f\x80\x80\x80\x01", EncodeUint32(4, 0x20000f)); EXPECT_EQ("\x07\x80\x80\x80\x01", EncodeUint32(3, 0x200007)); EXPECT_EQ("\x03\x80\x80\x80\x01", EncodeUint32(2, 0x200003)); EXPECT_EQ("\x01\x80\x80\x80\x01", EncodeUint32(1, 0x200001)); EXPECT_EQ("\x7f\xff\xff\xff\x7f", EncodeUint32(7, 0x1000007e)); EXPECT_EQ("\x3f\xff\xff\xff\x7f", EncodeUint32(6, 0x1000003e)); EXPECT_EQ("\x1f\xff\xff\xff\x7f", EncodeUint32(5, 0x1000001e)); EXPECT_EQ("\x0f\xff\xff\xff\x7f", EncodeUint32(4, 0x1000000e)); EXPECT_EQ("\x07\xff\xff\xff\x7f", EncodeUint32(3, 0x10000006)); EXPECT_EQ("\x03\xff\xff\xff\x7f", EncodeUint32(2, 0x10000002)); EXPECT_EQ("\x01\xff\xff\xff\x7f", EncodeUint32(1, 0x10000000)); } TEST(HpackOutputStreamTest, SixByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x80\x80\x80\x01", EncodeUint32(7, 0x1000007f)); EXPECT_EQ("\x3f\x80\x80\x80\x80\x01", EncodeUint32(6, 0x1000003f)); EXPECT_EQ("\x1f\x80\x80\x80\x80\x01", EncodeUint32(5, 0x1000001f)); EXPECT_EQ("\x0f\x80\x80\x80\x80\x01", EncodeUint32(4, 0x1000000f)); EXPECT_EQ("\x07\x80\x80\x80\x80\x01", EncodeUint32(3, 0x10000007)); EXPECT_EQ("\x03\x80\x80\x80\x80\x01", EncodeUint32(2, 0x10000003)); EXPECT_EQ("\x01\x80\x80\x80\x80\x01", EncodeUint32(1, 0x10000001)); EXPECT_EQ("\x7f\x80\xff\xff\xff\x0f", EncodeUint32(7, 0xffffffff)); EXPECT_EQ("\x3f\xc0\xff\xff\xff\x0f", EncodeUint32(6, 0xffffffff)); EXPECT_EQ("\x1f\xe0\xff\xff\xff\x0f", EncodeUint32(5, 0xffffffff)); EXPECT_EQ("\x0f\xf0\xff\xff\xff\x0f", EncodeUint32(4, 0xffffffff)); EXPECT_EQ("\x07\xf8\xff\xff\xff\x0f", EncodeUint32(3, 0xffffffff)); EXPECT_EQ("\x03\xfc\xff\xff\xff\x0f", EncodeUint32(2, 0xffffffff)); EXPECT_EQ("\x01\xfe\xff\xff\xff\x0f", EncodeUint32(1, 0xffffffff)); } TEST(HpackOutputStreamTest, AppendUint32PreservesUpperBits) { HpackOutputStream output_stream; output_stream.AppendBits(0x7f, 7); output_stream.AppendUint32(0x01); std::string str = output_stream.TakeString(); EXPECT_EQ(std::string("\xff\x00", 2), str); } TEST(HpackOutputStreamTest, AppendBytes) { HpackOutputStream output_stream; output_stream.AppendBytes("buffer1"); output_stream.AppendBytes("buffer2"); std::string str = output_stream.TakeString(); EXPECT_EQ("buffer1buffer2", str); } TEST(HpackOutputStreamTest, BoundedTakeString) { HpackOutputStream output_stream; output_stream.AppendBytes("buffer12"); output_stream.AppendBytes("buffer456"); std::string str = output_stream.BoundedTakeString(9); EXPECT_EQ("buffer12b", str); output_stream.AppendBits(0x7f, 7); output_stream.AppendUint32(0x11); str = output_stream.BoundedTakeString(9); EXPECT_EQ("uffer456\xff", str); str = output_stream.BoundedTakeString(9); EXPECT_EQ("\x10", str); } TEST(HpackOutputStreamTest, MutableString) { HpackOutputStream output_stream; output_stream.AppendBytes("1"); output_stream.MutableString()->append("2"); output_stream.AppendBytes("foo"); output_stream.MutableString()->append("bar"); std::string str = output_stream.TakeString(); EXPECT_EQ("12foobar", str); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_output_stream.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_output_stream_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
667b7068-9c5a-4cc9-947b-cf89d916aa11
cpp
google/quiche
hpack_header_table
quiche/http2/hpack/hpack_header_table.cc
quiche/http2/hpack/hpack_header_table_test.cc
#include "quiche/http2/hpack/hpack_header_table.h" #include <algorithm> #include <cstddef> #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_entry.h" #include "quiche/http2/hpack/hpack_static_table.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { HpackHeaderTable::HpackHeaderTable() : static_entries_(ObtainHpackStaticTable().GetStaticEntries()), static_index_(ObtainHpackStaticTable().GetStaticIndex()), static_name_index_(ObtainHpackStaticTable().GetStaticNameIndex()), settings_size_bound_(kDefaultHeaderTableSizeSetting), size_(0), max_size_(kDefaultHeaderTableSizeSetting), dynamic_table_insertions_(0) {} HpackHeaderTable::~HpackHeaderTable() = default; size_t HpackHeaderTable::GetByName(absl::string_view name) { { auto it = static_name_index_.find(name); if (it != static_name_index_.end()) { return 1 + it->second; } } { NameToEntryMap::const_iterator it = dynamic_name_index_.find(name); if (it != dynamic_name_index_.end()) { return dynamic_table_insertions_ - it->second + kStaticTableSize; } } return kHpackEntryNotFound; } size_t HpackHeaderTable::GetByNameAndValue(absl::string_view name, absl::string_view value) { HpackLookupEntry query{name, value}; { auto it = static_index_.find(query); if (it != static_index_.end()) { return 1 + it->second; } } { auto it = dynamic_index_.find(query); if (it != dynamic_index_.end()) { return dynamic_table_insertions_ - it->second + kStaticTableSize; } } return kHpackEntryNotFound; } void HpackHeaderTable::SetMaxSize(size_t max_size) { QUICHE_CHECK_LE(max_size, settings_size_bound_); max_size_ = max_size; if (size_ > max_size_) { Evict(EvictionCountToReclaim(size_ - max_size_)); QUICHE_CHECK_LE(size_, max_size_); } } void HpackHeaderTable::SetSettingsHeaderTableSize(size_t settings_size) { settings_size_bound_ = settings_size; SetMaxSize(settings_size_bound_); } void HpackHeaderTable::EvictionSet(absl::string_view name, absl::string_view value, DynamicEntryTable::iterator* begin_out, DynamicEntryTable::iterator* end_out) { size_t eviction_count = EvictionCountForEntry(name, value); *begin_out = dynamic_entries_.end() - eviction_count; *end_out = dynamic_entries_.end(); } size_t HpackHeaderTable::EvictionCountForEntry(absl::string_view name, absl::string_view value) const { size_t available_size = max_size_ - size_; size_t entry_size = HpackEntry::Size(name, value); if (entry_size <= available_size) { return 0; } return EvictionCountToReclaim(entry_size - available_size); } size_t HpackHeaderTable::EvictionCountToReclaim(size_t reclaim_size) const { size_t count = 0; for (auto it = dynamic_entries_.rbegin(); it != dynamic_entries_.rend() && reclaim_size != 0; ++it, ++count) { reclaim_size -= std::min(reclaim_size, (*it)->Size()); } return count; } void HpackHeaderTable::Evict(size_t count) { for (size_t i = 0; i != count; ++i) { QUICHE_CHECK(!dynamic_entries_.empty()); HpackEntry* entry = dynamic_entries_.back().get(); const size_t index = dynamic_table_insertions_ - dynamic_entries_.size(); size_ -= entry->Size(); auto it = dynamic_index_.find({entry->name(), entry->value()}); QUICHE_DCHECK(it != dynamic_index_.end()); if (it->second == index) { dynamic_index_.erase(it); } auto name_it = dynamic_name_index_.find(entry->name()); QUICHE_DCHECK(name_it != dynamic_name_index_.end()); if (name_it->second == index) { dynamic_name_index_.erase(name_it); } dynamic_entries_.pop_back(); } } const HpackEntry* HpackHeaderTable::TryAddEntry(absl::string_view name, absl::string_view value) { Evict(EvictionCountForEntry(name, value)); size_t entry_size = HpackEntry::Size(name, value); if (entry_size > (max_size_ - size_)) { QUICHE_DCHECK(dynamic_entries_.empty()); QUICHE_DCHECK_EQ(0u, size_); return nullptr; } const size_t index = dynamic_table_insertions_; dynamic_entries_.push_front( std::make_unique<HpackEntry>(std::string(name), std::string(value))); HpackEntry* new_entry = dynamic_entries_.front().get(); auto index_result = dynamic_index_.insert(std::make_pair( HpackLookupEntry{new_entry->name(), new_entry->value()}, index)); if (!index_result.second) { QUICHE_DVLOG(1) << "Found existing entry at: " << index_result.first->second << " replacing with: " << new_entry->GetDebugString() << " at: " << index; QUICHE_DCHECK_GT(index, index_result.first->second); dynamic_index_.erase(index_result.first); auto insert_result = dynamic_index_.insert(std::make_pair( HpackLookupEntry{new_entry->name(), new_entry->value()}, index)); QUICHE_CHECK(insert_result.second); } auto name_result = dynamic_name_index_.insert(std::make_pair(new_entry->name(), index)); if (!name_result.second) { QUICHE_DVLOG(1) << "Found existing entry at: " << name_result.first->second << " replacing with: " << new_entry->GetDebugString() << " at: " << index; QUICHE_DCHECK_GT(index, name_result.first->second); dynamic_name_index_.erase(name_result.first); auto insert_result = dynamic_name_index_.insert(std::make_pair(new_entry->name(), index)); QUICHE_CHECK(insert_result.second); } size_ += entry_size; ++dynamic_table_insertions_; return dynamic_entries_.front().get(); } }
#include "quiche/http2/hpack/hpack_header_table.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_entry.h" #include "quiche/http2/hpack/hpack_static_table.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { using std::distance; namespace test { class HpackHeaderTablePeer { public: explicit HpackHeaderTablePeer(HpackHeaderTable* table) : table_(table) {} const HpackHeaderTable::DynamicEntryTable& dynamic_entries() { return table_->dynamic_entries_; } const HpackHeaderTable::StaticEntryTable& static_entries() { return table_->static_entries_; } const HpackEntry* GetFirstStaticEntry() { return &table_->static_entries_.front(); } const HpackEntry* GetLastStaticEntry() { return &table_->static_entries_.back(); } std::vector<HpackEntry*> EvictionSet(absl::string_view name, absl::string_view value) { HpackHeaderTable::DynamicEntryTable::iterator begin, end; table_->EvictionSet(name, value, &begin, &end); std::vector<HpackEntry*> result; for (; begin != end; ++begin) { result.push_back(begin->get()); } return result; } size_t dynamic_table_insertions() { return table_->dynamic_table_insertions_; } size_t EvictionCountForEntry(absl::string_view name, absl::string_view value) { return table_->EvictionCountForEntry(name, value); } size_t EvictionCountToReclaim(size_t reclaim_size) { return table_->EvictionCountToReclaim(reclaim_size); } void Evict(size_t count) { return table_->Evict(count); } private: HpackHeaderTable* table_; }; } namespace { class HpackHeaderTableTest : public quiche::test::QuicheTest { protected: typedef std::vector<HpackEntry> HpackEntryVector; HpackHeaderTableTest() : table_(), peer_(&table_) {} static HpackEntry MakeEntryOfSize(uint32_t size) { EXPECT_GE(size, kHpackEntrySizeOverhead); std::string name((size - kHpackEntrySizeOverhead) / 2, 'n'); std::string value(size - kHpackEntrySizeOverhead - name.size(), 'v'); HpackEntry entry(name, value); EXPECT_EQ(size, entry.Size()); return entry; } static HpackEntryVector MakeEntriesOfTotalSize(uint32_t total_size) { EXPECT_GE(total_size, kHpackEntrySizeOverhead); uint32_t entry_size = kHpackEntrySizeOverhead; uint32_t remaining_size = total_size; HpackEntryVector entries; while (remaining_size > 0) { EXPECT_LE(entry_size, remaining_size); entries.push_back(MakeEntryOfSize(entry_size)); remaining_size -= entry_size; entry_size = std::min(remaining_size, entry_size + 32); } return entries; } void AddEntriesExpectNoEviction(const HpackEntryVector& entries) { for (auto it = entries.begin(); it != entries.end(); ++it) { HpackHeaderTable::DynamicEntryTable::iterator begin, end; table_.EvictionSet(it->name(), it->value(), &begin, &end); EXPECT_EQ(0, distance(begin, end)); const HpackEntry* entry = table_.TryAddEntry(it->name(), it->value()); EXPECT_NE(entry, static_cast<HpackEntry*>(nullptr)); } } HpackHeaderTable table_; test::HpackHeaderTablePeer peer_; }; TEST_F(HpackHeaderTableTest, StaticTableInitialization) { EXPECT_EQ(0u, table_.size()); EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.max_size()); EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.settings_size_bound()); EXPECT_EQ(0u, peer_.dynamic_entries().size()); EXPECT_EQ(0u, peer_.dynamic_table_insertions()); const HpackHeaderTable::StaticEntryTable& static_entries = peer_.static_entries(); EXPECT_EQ(kStaticTableSize, static_entries.size()); size_t index = 1; for (const HpackEntry& entry : static_entries) { EXPECT_EQ(index, table_.GetByNameAndValue(entry.name(), entry.value())); index++; } } TEST_F(HpackHeaderTableTest, BasicDynamicEntryInsertionAndEviction) { EXPECT_EQ(kStaticTableSize, peer_.static_entries().size()); const HpackEntry* first_static_entry = peer_.GetFirstStaticEntry(); const HpackEntry* last_static_entry = peer_.GetLastStaticEntry(); const HpackEntry* entry = table_.TryAddEntry("header-key", "Header Value"); EXPECT_EQ("header-key", entry->name()); EXPECT_EQ("Header Value", entry->value()); EXPECT_EQ(entry->Size(), table_.size()); EXPECT_EQ(1u, peer_.dynamic_entries().size()); EXPECT_EQ(kStaticTableSize, peer_.static_entries().size()); EXPECT_EQ(62u, table_.GetByNameAndValue("header-key", "Header Value")); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); peer_.Evict(1); EXPECT_EQ(0u, table_.size()); EXPECT_EQ(0u, peer_.dynamic_entries().size()); EXPECT_EQ(kStaticTableSize, peer_.static_entries().size()); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); } TEST_F(HpackHeaderTableTest, EntryIndexing) { const HpackEntry* first_static_entry = peer_.GetFirstStaticEntry(); const HpackEntry* last_static_entry = peer_.GetLastStaticEntry(); EXPECT_EQ(1u, table_.GetByName(first_static_entry->name())); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); table_.TryAddEntry(first_static_entry->name(), first_static_entry->value()); table_.TryAddEntry(first_static_entry->name(), "Value Four"); table_.TryAddEntry("key-1", "Value One"); table_.TryAddEntry("key-2", "Value Three"); table_.TryAddEntry("key-1", "Value Two"); table_.TryAddEntry("key-2", "Value Three"); table_.TryAddEntry("key-2", "Value Four"); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); EXPECT_EQ(67u, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); EXPECT_EQ(66u, table_.GetByNameAndValue("key-1", "Value One")); EXPECT_EQ(64u, table_.GetByNameAndValue("key-1", "Value Two")); EXPECT_EQ(63u, table_.GetByNameAndValue("key-2", "Value Three")); EXPECT_EQ(62u, table_.GetByNameAndValue("key-2", "Value Four")); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); EXPECT_EQ(64u, table_.GetByName("key-1")); EXPECT_EQ(62u, table_.GetByName("key-2")); EXPECT_EQ(1u, table_.GetByName(first_static_entry->name())); EXPECT_EQ(kHpackEntryNotFound, table_.GetByName("not-present")); EXPECT_EQ(66u, table_.GetByNameAndValue("key-1", "Value One")); EXPECT_EQ(64u, table_.GetByNameAndValue("key-1", "Value Two")); EXPECT_EQ(63u, table_.GetByNameAndValue("key-2", "Value Three")); EXPECT_EQ(62u, table_.GetByNameAndValue("key-2", "Value Four")); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); EXPECT_EQ(67u, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); EXPECT_EQ(kHpackEntryNotFound, table_.GetByNameAndValue("key-1", "Not Present")); EXPECT_EQ(kHpackEntryNotFound, table_.GetByNameAndValue("not-present", "Value One")); peer_.Evict(1); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); EXPECT_EQ(67u, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); peer_.Evict(1); EXPECT_EQ(kHpackEntryNotFound, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); } TEST_F(HpackHeaderTableTest, SetSizes) { std::string key = "key", value = "value"; const HpackEntry* entry1 = table_.TryAddEntry(key, value); const HpackEntry* entry2 = table_.TryAddEntry(key, value); const HpackEntry* entry3 = table_.TryAddEntry(key, value); size_t max_size = entry1->Size() + entry2->Size() + entry3->Size(); table_.SetMaxSize(max_size); EXPECT_EQ(3u, peer_.dynamic_entries().size()); max_size = entry1->Size() + entry2->Size() + entry3->Size() - 1; table_.SetMaxSize(max_size); EXPECT_EQ(2u, peer_.dynamic_entries().size()); EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.settings_size_bound()); table_.SetSettingsHeaderTableSize(kDefaultHeaderTableSizeSetting * 3 + 1); EXPECT_EQ(kDefaultHeaderTableSizeSetting * 3 + 1, table_.max_size()); max_size = entry3->Size() - 1; table_.SetSettingsHeaderTableSize(max_size); EXPECT_EQ(max_size, table_.max_size()); EXPECT_EQ(max_size, table_.settings_size_bound()); EXPECT_EQ(0u, peer_.dynamic_entries().size()); } TEST_F(HpackHeaderTableTest, EvictionCountForEntry) { std::string key = "key", value = "value"; const HpackEntry* entry1 = table_.TryAddEntry(key, value); const HpackEntry* entry2 = table_.TryAddEntry(key, value); size_t entry3_size = HpackEntry::Size(key, value); table_.SetMaxSize(entry1->Size() + entry2->Size() + entry3_size); EXPECT_EQ(0u, peer_.EvictionCountForEntry(key, value)); EXPECT_EQ(1u, peer_.EvictionCountForEntry(key, value + "x")); table_.SetMaxSize(entry1->Size() + entry2->Size()); EXPECT_EQ(1u, peer_.EvictionCountForEntry(key, value)); EXPECT_EQ(2u, peer_.EvictionCountForEntry(key, value + "x")); } TEST_F(HpackHeaderTableTest, EvictionCountToReclaim) { std::string key = "key", value = "value"; const HpackEntry* entry1 = table_.TryAddEntry(key, value); const HpackEntry* entry2 = table_.TryAddEntry(key, value); EXPECT_EQ(1u, peer_.EvictionCountToReclaim(1)); EXPECT_EQ(1u, peer_.EvictionCountToReclaim(entry1->Size())); EXPECT_EQ(2u, peer_.EvictionCountToReclaim(entry1->Size() + 1)); EXPECT_EQ(2u, peer_.EvictionCountToReclaim(entry1->Size() + entry2->Size())); } TEST_F(HpackHeaderTableTest, TryAddEntryBasic) { EXPECT_EQ(0u, table_.size()); EXPECT_EQ(table_.settings_size_bound(), table_.max_size()); HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size()); AddEntriesExpectNoEviction(entries); EXPECT_EQ(table_.max_size(), table_.size()); EXPECT_EQ(table_.settings_size_bound(), table_.size()); } TEST_F(HpackHeaderTableTest, SetMaxSize) { HpackEntryVector entries = MakeEntriesOfTotalSize(kDefaultHeaderTableSizeSetting / 2); AddEntriesExpectNoEviction(entries); for (auto it = entries.begin(); it != entries.end(); ++it) { size_t expected_count = distance(it, entries.end()); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); table_.SetMaxSize(table_.size() + 1); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); table_.SetMaxSize(table_.size()); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); --expected_count; table_.SetMaxSize(table_.size() - 1); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); } EXPECT_EQ(0u, table_.size()); } TEST_F(HpackHeaderTableTest, TryAddEntryEviction) { HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size()); AddEntriesExpectNoEviction(entries); const HpackEntry* survivor_entry = peer_.dynamic_entries().front().get(); HpackEntry long_entry = MakeEntryOfSize(table_.max_size() - survivor_entry->Size()); EXPECT_EQ(peer_.dynamic_entries().size() - 1, peer_.EvictionSet(long_entry.name(), long_entry.value()).size()); table_.TryAddEntry(long_entry.name(), long_entry.value()); EXPECT_EQ(2u, peer_.dynamic_entries().size()); EXPECT_EQ(63u, table_.GetByNameAndValue(survivor_entry->name(), survivor_entry->value())); EXPECT_EQ(62u, table_.GetByNameAndValue(long_entry.name(), long_entry.value())); } TEST_F(HpackHeaderTableTest, TryAddTooLargeEntry) { HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size()); AddEntriesExpectNoEviction(entries); const HpackEntry long_entry = MakeEntryOfSize(table_.max_size() + 1); EXPECT_EQ(peer_.dynamic_entries().size(), peer_.EvictionSet(long_entry.name(), long_entry.value()).size()); const HpackEntry* new_entry = table_.TryAddEntry(long_entry.name(), long_entry.value()); EXPECT_EQ(new_entry, static_cast<HpackEntry*>(nullptr)); EXPECT_EQ(0u, peer_.dynamic_entries().size()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_header_table.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_header_table_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
740270e8-8ef5-4337-9da2-121238a9b2cd
cpp
google/quiche
hpack_encoder
quiche/http2/hpack/hpack_encoder.cc
quiche/http2/hpack/hpack_encoder_test.cc
#include "quiche/http2/hpack/hpack_encoder.h" #include <algorithm> #include <cstddef> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_header_table.h" #include "quiche/http2/hpack/hpack_output_stream.h" #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { class HpackEncoder::RepresentationIterator { public: RepresentationIterator(const Representations& pseudo_headers, const Representations& regular_headers) : pseudo_begin_(pseudo_headers.begin()), pseudo_end_(pseudo_headers.end()), regular_begin_(regular_headers.begin()), regular_end_(regular_headers.end()) {} explicit RepresentationIterator(const Representations& headers) : pseudo_begin_(headers.begin()), pseudo_end_(headers.end()), regular_begin_(headers.end()), regular_end_(headers.end()) {} bool HasNext() { return pseudo_begin_ != pseudo_end_ || regular_begin_ != regular_end_; } const Representation Next() { if (pseudo_begin_ != pseudo_end_) { return *pseudo_begin_++; } else { return *regular_begin_++; } } private: Representations::const_iterator pseudo_begin_; Representations::const_iterator pseudo_end_; Representations::const_iterator regular_begin_; Representations::const_iterator regular_end_; }; namespace { void NoOpListener(absl::string_view , absl::string_view ) {} bool DefaultPolicy(absl::string_view name, absl::string_view ) { if (name.empty()) { return false; } if (name[0] == kPseudoHeaderPrefix) { return name == ":authority"; } return true; } } HpackEncoder::HpackEncoder() : output_stream_(), min_table_size_setting_received_(std::numeric_limits<size_t>::max()), listener_(NoOpListener), should_index_(DefaultPolicy), enable_compression_(true), should_emit_table_size_(false), crumble_cookies_(true) {} HpackEncoder::~HpackEncoder() = default; std::string HpackEncoder::EncodeHeaderBlock( const quiche::HttpHeaderBlock& header_set) { Representations pseudo_headers; Representations regular_headers; bool found_cookie = false; for (const auto& header : header_set) { if (!found_cookie && header.first == "cookie") { found_cookie = true; if (crumble_cookies_) { CookieToCrumbs(header, &regular_headers); } else { DecomposeRepresentation(header, &regular_headers); } } else if (!header.first.empty() && header.first[0] == kPseudoHeaderPrefix) { DecomposeRepresentation(header, &pseudo_headers); } else { DecomposeRepresentation(header, &regular_headers); } } RepresentationIterator iter(pseudo_headers, regular_headers); return EncodeRepresentations(&iter); } void HpackEncoder::ApplyHeaderTableSizeSetting(size_t size_setting) { if (size_setting == header_table_.settings_size_bound()) { return; } if (size_setting < header_table_.settings_size_bound()) { min_table_size_setting_received_ = std::min(size_setting, min_table_size_setting_received_); } header_table_.SetSettingsHeaderTableSize(size_setting); should_emit_table_size_ = true; } std::string HpackEncoder::EncodeRepresentations(RepresentationIterator* iter) { MaybeEmitTableSize(); while (iter->HasNext()) { const auto header = iter->Next(); listener_(header.first, header.second); if (enable_compression_) { size_t index = header_table_.GetByNameAndValue(header.first, header.second); if (index != kHpackEntryNotFound) { EmitIndex(index); } else if (should_index_(header.first, header.second)) { EmitIndexedLiteral(header); } else { EmitNonIndexedLiteral(header, enable_compression_); } } else { EmitNonIndexedLiteral(header, enable_compression_); } } return output_stream_.TakeString(); } void HpackEncoder::EmitIndex(size_t index) { QUICHE_DVLOG(2) << "Emitting index " << index; output_stream_.AppendPrefix(kIndexedOpcode); output_stream_.AppendUint32(index); } void HpackEncoder::EmitIndexedLiteral(const Representation& representation) { QUICHE_DVLOG(2) << "Emitting indexed literal: (" << representation.first << ", " << representation.second << ")"; output_stream_.AppendPrefix(kLiteralIncrementalIndexOpcode); EmitLiteral(representation); header_table_.TryAddEntry(representation.first, representation.second); } void HpackEncoder::EmitNonIndexedLiteral(const Representation& representation, bool enable_compression) { QUICHE_DVLOG(2) << "Emitting nonindexed literal: (" << representation.first << ", " << representation.second << ")"; output_stream_.AppendPrefix(kLiteralNoIndexOpcode); size_t name_index = header_table_.GetByName(representation.first); if (enable_compression && name_index != kHpackEntryNotFound) { output_stream_.AppendUint32(name_index); } else { output_stream_.AppendUint32(0); EmitString(representation.first); } EmitString(representation.second); } void HpackEncoder::EmitLiteral(const Representation& representation) { size_t name_index = header_table_.GetByName(representation.first); if (name_index != kHpackEntryNotFound) { output_stream_.AppendUint32(name_index); } else { output_stream_.AppendUint32(0); EmitString(representation.first); } EmitString(representation.second); } void HpackEncoder::EmitString(absl::string_view str) { size_t encoded_size = enable_compression_ ? http2::HuffmanSize(str) : str.size(); if (encoded_size < str.size()) { QUICHE_DVLOG(2) << "Emitted Huffman-encoded string of length " << encoded_size; output_stream_.AppendPrefix(kStringLiteralHuffmanEncoded); output_stream_.AppendUint32(encoded_size); http2::HuffmanEncode(str, encoded_size, output_stream_.MutableString()); } else { QUICHE_DVLOG(2) << "Emitted literal string of length " << str.size(); output_stream_.AppendPrefix(kStringLiteralIdentityEncoded); output_stream_.AppendUint32(str.size()); output_stream_.AppendBytes(str); } } void HpackEncoder::MaybeEmitTableSize() { if (!should_emit_table_size_) { return; } const size_t current_size = CurrentHeaderTableSizeSetting(); QUICHE_DVLOG(1) << "MaybeEmitTableSize current_size=" << current_size; QUICHE_DVLOG(1) << "MaybeEmitTableSize min_table_size_setting_received_=" << min_table_size_setting_received_; if (min_table_size_setting_received_ < current_size) { output_stream_.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream_.AppendUint32(min_table_size_setting_received_); } output_stream_.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream_.AppendUint32(current_size); min_table_size_setting_received_ = std::numeric_limits<size_t>::max(); should_emit_table_size_ = false; } void HpackEncoder::CookieToCrumbs(const Representation& cookie, Representations* out) { absl::string_view cookie_value = cookie.second; absl::string_view::size_type first = cookie_value.find_first_not_of(" \t"); absl::string_view::size_type last = cookie_value.find_last_not_of(" \t"); if (first == absl::string_view::npos) { cookie_value = absl::string_view(); } else { cookie_value = cookie_value.substr(first, (last - first) + 1); } for (size_t pos = 0;;) { size_t end = cookie_value.find(';', pos); if (end == absl::string_view::npos) { out->push_back(std::make_pair(cookie.first, cookie_value.substr(pos))); break; } out->push_back( std::make_pair(cookie.first, cookie_value.substr(pos, end - pos))); pos = end + 1; if (pos != cookie_value.size() && cookie_value[pos] == ' ') { pos++; } } } void HpackEncoder::DecomposeRepresentation(const Representation& header_field, Representations* out) { std::vector<absl::string_view> pieces = absl::StrSplit(header_field.second, '\0'); out->reserve(pieces.size()); for (absl::string_view piece : pieces) { out->push_back(std::make_pair(header_field.first, piece)); } } class HpackEncoder::Encoderator : public ProgressiveEncoder { public: Encoderator(const quiche::HttpHeaderBlock& header_set, HpackEncoder* encoder); Encoderator(const Representations& representations, HpackEncoder* encoder); Encoderator(const Encoderator&) = delete; Encoderator& operator=(const Encoderator&) = delete; bool HasNext() const override { return has_next_; } std::string Next(size_t max_encoded_bytes) override; private: HpackEncoder* encoder_; std::unique_ptr<RepresentationIterator> header_it_; Representations pseudo_headers_; Representations regular_headers_; bool has_next_; }; HpackEncoder::Encoderator::Encoderator( const quiche::HttpHeaderBlock& header_set, HpackEncoder* encoder) : encoder_(encoder), has_next_(true) { bool found_cookie = false; for (const auto& header : header_set) { if (!found_cookie && header.first == "cookie") { found_cookie = true; if (encoder_->crumble_cookies_) { CookieToCrumbs(header, &regular_headers_); } else { DecomposeRepresentation(header, &regular_headers_); } } else if (!header.first.empty() && header.first[0] == kPseudoHeaderPrefix) { DecomposeRepresentation(header, &pseudo_headers_); } else { DecomposeRepresentation(header, &regular_headers_); } } header_it_ = std::make_unique<RepresentationIterator>(pseudo_headers_, regular_headers_); encoder_->MaybeEmitTableSize(); } HpackEncoder::Encoderator::Encoderator(const Representations& representations, HpackEncoder* encoder) : encoder_(encoder), has_next_(true) { for (const auto& header : representations) { if (header.first == "cookie") { if (encoder_->crumble_cookies_) { CookieToCrumbs(header, &regular_headers_); } else { DecomposeRepresentation(header, &regular_headers_); } } else if (!header.first.empty() && header.first[0] == kPseudoHeaderPrefix) { pseudo_headers_.push_back(header); } else { regular_headers_.push_back(header); } } header_it_ = std::make_unique<RepresentationIterator>(pseudo_headers_, regular_headers_); encoder_->MaybeEmitTableSize(); } std::string HpackEncoder::Encoderator::Next(size_t max_encoded_bytes) { QUICHE_BUG_IF(spdy_bug_61_1, !has_next_) << "Encoderator::Next called with nothing left to encode."; const bool enable_compression = encoder_->enable_compression_; while (header_it_->HasNext() && encoder_->output_stream_.size() <= max_encoded_bytes) { const Representation header = header_it_->Next(); encoder_->listener_(header.first, header.second); if (enable_compression) { size_t index = encoder_->header_table_.GetByNameAndValue(header.first, header.second); if (index != kHpackEntryNotFound) { encoder_->EmitIndex(index); } else if (encoder_->should_index_(header.first, header.second)) { encoder_->EmitIndexedLiteral(header); } else { encoder_->EmitNonIndexedLiteral(header, enable_compression); } } else { encoder_->EmitNonIndexedLiteral(header, enable_compression); } } has_next_ = encoder_->output_stream_.size() > max_encoded_bytes; return encoder_->output_stream_.BoundedTakeString(max_encoded_bytes); } std::unique_ptr<HpackEncoder::ProgressiveEncoder> HpackEncoder::EncodeHeaderSet( const quiche::HttpHeaderBlock& header_set) { return std::make_unique<Encoderator>(header_set, this); } std::unique_ptr<HpackEncoder::ProgressiveEncoder> HpackEncoder::EncodeRepresentations(const Representations& representations) { return std::make_unique<Encoderator>(representations, this); } }
#include "quiche/http2/hpack/hpack_encoder.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/hpack_constants.h" #include "quiche/http2/hpack/hpack_entry.h" #include "quiche/http2/hpack/hpack_header_table.h" #include "quiche/http2/hpack/hpack_output_stream.h" #include "quiche/http2/hpack/hpack_static_table.h" #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_simple_arena.h" namespace spdy { namespace test { class HpackHeaderTablePeer { public: explicit HpackHeaderTablePeer(HpackHeaderTable* table) : table_(table) {} const HpackEntry* GetFirstStaticEntry() const { return &table_->static_entries_.front(); } HpackHeaderTable::DynamicEntryTable* dynamic_entries() { return &table_->dynamic_entries_; } private: HpackHeaderTable* table_; }; class HpackEncoderPeer { public: typedef HpackEncoder::Representation Representation; typedef HpackEncoder::Representations Representations; explicit HpackEncoderPeer(HpackEncoder* encoder) : encoder_(encoder) {} bool compression_enabled() const { return encoder_->enable_compression_; } HpackHeaderTable* table() { return &encoder_->header_table_; } HpackHeaderTablePeer table_peer() { return HpackHeaderTablePeer(table()); } void EmitString(absl::string_view str) { encoder_->EmitString(str); } void TakeString(std::string* out) { *out = encoder_->output_stream_.TakeString(); } static void CookieToCrumbs(absl::string_view cookie, std::vector<absl::string_view>* out) { Representations tmp; HpackEncoder::CookieToCrumbs(std::make_pair("", cookie), &tmp); out->clear(); for (size_t i = 0; i != tmp.size(); ++i) { out->push_back(tmp[i].second); } } static void DecomposeRepresentation(absl::string_view value, std::vector<absl::string_view>* out) { Representations tmp; HpackEncoder::DecomposeRepresentation(std::make_pair("foobar", value), &tmp); out->clear(); for (size_t i = 0; i != tmp.size(); ++i) { out->push_back(tmp[i].second); } } static std::string EncodeHeaderBlock( HpackEncoder* encoder, const quiche::HttpHeaderBlock& header_set) { return encoder->EncodeHeaderBlock(header_set); } static bool EncodeIncremental(HpackEncoder* encoder, const quiche::HttpHeaderBlock& header_set, std::string* output) { std::unique_ptr<HpackEncoder::ProgressiveEncoder> encoderator = encoder->EncodeHeaderSet(header_set); http2::test::Http2Random random; std::string output_buffer = encoderator->Next(random.UniformInRange(0, 16)); while (encoderator->HasNext()) { std::string second_buffer = encoderator->Next(random.UniformInRange(0, 16)); output_buffer.append(second_buffer); } *output = std::move(output_buffer); return true; } static bool EncodeRepresentations(HpackEncoder* encoder, const Representations& representations, std::string* output) { std::unique_ptr<HpackEncoder::ProgressiveEncoder> encoderator = encoder->EncodeRepresentations(representations); http2::test::Http2Random random; std::string output_buffer = encoderator->Next(random.UniformInRange(0, 16)); while (encoderator->HasNext()) { std::string second_buffer = encoderator->Next(random.UniformInRange(0, 16)); output_buffer.append(second_buffer); } *output = std::move(output_buffer); return true; } private: HpackEncoder* encoder_; }; } namespace { using testing::ElementsAre; using testing::Pair; const size_t kStaticEntryIndex = 1; enum EncodeStrategy { kDefault, kIncremental, kRepresentations, }; class HpackEncoderTest : public quiche::test::QuicheTestWithParam<EncodeStrategy> { protected: typedef test::HpackEncoderPeer::Representations Representations; HpackEncoderTest() : peer_(&encoder_), static_(peer_.table_peer().GetFirstStaticEntry()), dynamic_table_insertions_(0), headers_storage_(1024 ), strategy_(GetParam()) {} void SetUp() override { key_1_ = peer_.table()->TryAddEntry("key1", "value1"); key_1_index_ = dynamic_table_insertions_++; key_2_ = peer_.table()->TryAddEntry("key2", "value2"); key_2_index_ = dynamic_table_insertions_++; cookie_a_ = peer_.table()->TryAddEntry("cookie", "a=bb"); cookie_a_index_ = dynamic_table_insertions_++; cookie_c_ = peer_.table()->TryAddEntry("cookie", "c=dd"); cookie_c_index_ = dynamic_table_insertions_++; peer_.table()->SetMaxSize(peer_.table()->size()); QUICHE_CHECK_EQ(kInitialDynamicTableSize, peer_.table()->size()); } void SaveHeaders(absl::string_view name, absl::string_view value) { absl::string_view n(headers_storage_.Memdup(name.data(), name.size()), name.size()); absl::string_view v(headers_storage_.Memdup(value.data(), value.size()), value.size()); headers_observed_.push_back(std::make_pair(n, v)); } void ExpectIndex(size_t index) { expected_.AppendPrefix(kIndexedOpcode); expected_.AppendUint32(index); } void ExpectIndexedLiteral(size_t key_index, absl::string_view value) { expected_.AppendPrefix(kLiteralIncrementalIndexOpcode); expected_.AppendUint32(key_index); ExpectString(&expected_, value); } void ExpectIndexedLiteral(absl::string_view name, absl::string_view value) { expected_.AppendPrefix(kLiteralIncrementalIndexOpcode); expected_.AppendUint32(0); ExpectString(&expected_, name); ExpectString(&expected_, value); } void ExpectNonIndexedLiteral(absl::string_view name, absl::string_view value) { expected_.AppendPrefix(kLiteralNoIndexOpcode); expected_.AppendUint32(0); ExpectString(&expected_, name); ExpectString(&expected_, value); } void ExpectNonIndexedLiteralWithNameIndex(size_t key_index, absl::string_view value) { expected_.AppendPrefix(kLiteralNoIndexOpcode); expected_.AppendUint32(key_index); ExpectString(&expected_, value); } void ExpectString(HpackOutputStream* stream, absl::string_view str) { size_t encoded_size = peer_.compression_enabled() ? http2::HuffmanSize(str) : str.size(); if (encoded_size < str.size()) { expected_.AppendPrefix(kStringLiteralHuffmanEncoded); expected_.AppendUint32(encoded_size); http2::HuffmanEncode(str, encoded_size, stream->MutableString()); } else { expected_.AppendPrefix(kStringLiteralIdentityEncoded); expected_.AppendUint32(str.size()); expected_.AppendBytes(str); } } void ExpectHeaderTableSizeUpdate(uint32_t size) { expected_.AppendPrefix(kHeaderTableSizeUpdateOpcode); expected_.AppendUint32(size); } Representations MakeRepresentations( const quiche::HttpHeaderBlock& header_set) { Representations r; for (const auto& header : header_set) { r.push_back(header); } return r; } void CompareWithExpectedEncoding(const quiche::HttpHeaderBlock& header_set) { std::string actual_out; std::string expected_out = expected_.TakeString(); switch (strategy_) { case kDefault: actual_out = test::HpackEncoderPeer::EncodeHeaderBlock(&encoder_, header_set); break; case kIncremental: EXPECT_TRUE(test::HpackEncoderPeer::EncodeIncremental( &encoder_, header_set, &actual_out)); break; case kRepresentations: EXPECT_TRUE(test::HpackEncoderPeer::EncodeRepresentations( &encoder_, MakeRepresentations(header_set), &actual_out)); break; } EXPECT_EQ(expected_out, actual_out); } void CompareWithExpectedEncoding(const Representations& representations) { std::string actual_out; std::string expected_out = expected_.TakeString(); EXPECT_TRUE(test::HpackEncoderPeer::EncodeRepresentations( &encoder_, representations, &actual_out)); EXPECT_EQ(expected_out, actual_out); } size_t DynamicIndexToWireIndex(size_t index) { return dynamic_table_insertions_ - index + kStaticTableSize; } HpackEncoder encoder_; test::HpackEncoderPeer peer_; const size_t kInitialDynamicTableSize = 4 * (10 + 32); const HpackEntry* static_; const HpackEntry* key_1_; const HpackEntry* key_2_; const HpackEntry* cookie_a_; const HpackEntry* cookie_c_; size_t key_1_index_; size_t key_2_index_; size_t cookie_a_index_; size_t cookie_c_index_; size_t dynamic_table_insertions_; quiche::QuicheSimpleArena headers_storage_; std::vector<std::pair<absl::string_view, absl::string_view>> headers_observed_; HpackOutputStream expected_; const EncodeStrategy strategy_; }; using HpackEncoderTestWithDefaultStrategy = HpackEncoderTest; INSTANTIATE_TEST_SUITE_P(HpackEncoderTests, HpackEncoderTestWithDefaultStrategy, ::testing::Values(kDefault)); TEST_P(HpackEncoderTestWithDefaultStrategy, EncodeRepresentations) { EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); const std::vector<std::pair<absl::string_view, absl::string_view>> header_list = {{"cookie", "val1; val2;val3"}, {":path", "/home"}, {"accept", "text/html, text/plain,application/xml"}, {"cookie", "val4"}, {"withnul", absl::string_view("one\0two", 7)}}; ExpectNonIndexedLiteralWithNameIndex(peer_.table()->GetByName(":path"), "/home"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val1"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val2"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val3"); ExpectIndexedLiteral(peer_.table()->GetByName("accept"), "text/html, text/plain,application/xml"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val4"); ExpectIndexedLiteral("withnul", absl::string_view("one\0two", 7)); CompareWithExpectedEncoding(header_list); EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/home"), Pair("cookie", "val1"), Pair("cookie", "val2"), Pair("cookie", "val3"), Pair("accept", "text/html, text/plain,application/xml"), Pair("cookie", "val4"), Pair("withnul", absl::string_view("one\0two", 7)))); EXPECT_GE(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); } TEST_P(HpackEncoderTestWithDefaultStrategy, WithoutCookieCrumbling) { EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); encoder_.DisableCookieCrumbling(); const std::vector<std::pair<absl::string_view, absl::string_view>> header_list = {{"cookie", "val1; val2;val3"}, {":path", "/home"}, {"accept", "text/html, text/plain,application/xml"}, {"cookie", "val4"}, {"withnul", absl::string_view("one\0two", 7)}}; ExpectNonIndexedLiteralWithNameIndex(peer_.table()->GetByName(":path"), "/home"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val1; val2;val3"); ExpectIndexedLiteral(peer_.table()->GetByName("accept"), "text/html, text/plain,application/xml"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val4"); ExpectIndexedLiteral("withnul", absl::string_view("one\0two", 7)); CompareWithExpectedEncoding(header_list); EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/home"), Pair("cookie", "val1; val2;val3"), Pair("accept", "text/html, text/plain,application/xml"), Pair("cookie", "val4"), Pair("withnul", absl::string_view("one\0two", 7)))); EXPECT_GE(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); } TEST_P(HpackEncoderTestWithDefaultStrategy, DynamicTableGrows) { EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); peer_.table()->SetMaxSize(4096); encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); const std::vector<std::pair<absl::string_view, absl::string_view>> header_list = {{"cookie", "val1; val2;val3"}, {":path", "/home"}, {"accept", "text/html, text/plain,application/xml"}, {"cookie", "val4"}, {"withnul", absl::string_view("one\0two", 7)}}; std::string out; EXPECT_TRUE(test::HpackEncoderPeer::EncodeRepresentations(&encoder_, header_list, &out)); EXPECT_FALSE(out.empty()); EXPECT_GT(encoder_.GetDynamicTableSize(), kInitialDynamicTableSize); } INSTANTIATE_TEST_SUITE_P(HpackEncoderTests, HpackEncoderTest, ::testing::Values(kDefault, kIncremental, kRepresentations)); TEST_P(HpackEncoderTest, SingleDynamicIndex) { encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); ExpectIndex(DynamicIndexToWireIndex(key_2_index_)); quiche::HttpHeaderBlock headers; headers[key_2_->name()] = key_2_->value(); CompareWithExpectedEncoding(headers); EXPECT_THAT(headers_observed_, ElementsAre(Pair(key_2_->name(), key_2_->value()))); } TEST_P(HpackEncoderTest, SingleStaticIndex) { ExpectIndex(kStaticEntryIndex); quiche::HttpHeaderBlock headers; headers[static_->name()] = static_->value(); CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, SingleStaticIndexTooLarge) { peer_.table()->SetMaxSize(1); ExpectIndex(kStaticEntryIndex); quiche::HttpHeaderBlock headers; headers[static_->name()] = static_->value(); CompareWithExpectedEncoding(headers); EXPECT_EQ(0u, peer_.table_peer().dynamic_entries()->size()); } TEST_P(HpackEncoderTest, SingleLiteralWithIndexName) { ExpectIndexedLiteral(DynamicIndexToWireIndex(key_2_index_), "value3"); quiche::HttpHeaderBlock headers; headers[key_2_->name()] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), key_2_->name()); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, SingleLiteralWithLiteralName) { ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, SingleLiteralTooLarge) { peer_.table()->SetMaxSize(1); ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); EXPECT_EQ(0u, peer_.table_peer().dynamic_entries()->size()); } TEST_P(HpackEncoderTest, EmitThanEvict) { ExpectIndex(DynamicIndexToWireIndex(key_1_index_)); ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers[key_1_->name()] = key_1_->value(); headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, CookieHeaderIsCrumbled) { ExpectIndex(DynamicIndexToWireIndex(cookie_a_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_c_index_)); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "e=ff"); quiche::HttpHeaderBlock headers; headers["cookie"] = "a=bb; c=dd; e=ff"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, CookieHeaderIsNotCrumbled) { encoder_.DisableCookieCrumbling(); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "a=bb; c=dd; e=ff"); quiche::HttpHeaderBlock headers; headers["cookie"] = "a=bb; c=dd; e=ff"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, MultiValuedHeadersNotCrumbled) { ExpectIndexedLiteral("foo", "bar, baz"); quiche::HttpHeaderBlock headers; headers["foo"] = "bar, baz"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, StringsDynamicallySelectHuffmanCoding) { peer_.EmitString("feedbeef"); expected_.AppendPrefix(kStringLiteralHuffmanEncoded); expected_.AppendUint32(6); expected_.AppendBytes("\x94\xA5\x92\x32\x96_"); peer_.EmitString("@@@@@@"); expected_.AppendPrefix(kStringLiteralIdentityEncoded); expected_.AppendUint32(6); expected_.AppendBytes("@@@@@@"); std::string actual_out; std::string expected_out = expected_.TakeString(); peer_.TakeString(&actual_out); EXPECT_EQ(expected_out, actual_out); } TEST_P(HpackEncoderTest, EncodingWithoutCompression) { encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); encoder_.DisableCompression(); ExpectNonIndexedLiteral(":path", "/index.html"); ExpectNonIndexedLiteral("cookie", "foo=bar"); ExpectNonIndexedLiteral("cookie", "baz=bing"); if (strategy_ == kRepresentations) { ExpectNonIndexedLiteral("hello", std::string("goodbye\0aloha", 13)); } else { ExpectNonIndexedLiteral("hello", "goodbye"); ExpectNonIndexedLiteral("hello", "aloha"); } ExpectNonIndexedLiteral("multivalue", "value1, value2"); quiche::HttpHeaderBlock headers; headers[":path"] = "/index.html"; headers["cookie"] = "foo=bar; baz=bing"; headers["hello"] = "goodbye"; headers.AppendValueOrAddHeader("hello", "aloha"); headers["multivalue"] = "value1, value2"; CompareWithExpectedEncoding(headers); if (strategy_ == kRepresentations) { EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/index.html"), Pair("cookie", "foo=bar"), Pair("cookie", "baz=bing"), Pair("hello", absl::string_view("goodbye\0aloha", 13)), Pair("multivalue", "value1, value2"))); } else { EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/index.html"), Pair("cookie", "foo=bar"), Pair("cookie", "baz=bing"), Pair("hello", "goodbye"), Pair("hello", "aloha"), Pair("multivalue", "value1, value2"))); } EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); } TEST_P(HpackEncoderTest, MultipleEncodingPasses) { encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); { quiche::HttpHeaderBlock headers; headers["key1"] = "value1"; headers["cookie"] = "a=bb"; ExpectIndex(DynamicIndexToWireIndex(key_1_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_a_index_)); CompareWithExpectedEncoding(headers); } { quiche::HttpHeaderBlock headers; headers["key2"] = "value2"; headers["cookie"] = "c=dd; e=ff"; ExpectIndex(DynamicIndexToWireIndex(key_2_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_c_index_)); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "e=ff"); dynamic_table_insertions_++; CompareWithExpectedEncoding(headers); } { quiche::HttpHeaderBlock headers; headers["key2"] = "value2"; headers["cookie"] = "a=bb; b=cc; c=dd"; EXPECT_EQ(65u, DynamicIndexToWireIndex(key_2_index_)); ExpectIndex(DynamicIndexToWireIndex(key_2_index_)); EXPECT_EQ(64u, DynamicIndexToWireIndex(cookie_a_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_a_index_)); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "b=cc"); dynamic_table_insertions_++; ExpectIndex(DynamicIndexToWireIndex(cookie_c_index_)); CompareWithExpectedEncoding(headers); } EXPECT_THAT(headers_observed_, ElementsAre(Pair("key1", "value1"), Pair("cookie", "a=bb"), Pair("key2", "value2"), Pair("cookie", "c=dd"), Pair("cookie", "e=ff"), Pair("key2", "value2"), Pair("cookie", "a=bb"), Pair("cookie", "b=cc"), Pair("cookie", "c=dd"))); } TEST_P(HpackEncoderTest, PseudoHeadersFirst) { quiche::HttpHeaderBlock headers; headers[":path"] = "/spam/eggs.html"; headers[":authority"] = "www.example.com"; headers["-foo"] = "bar"; headers["foo"] = "bar"; headers["cookie"] = "c=dd"; ExpectNonIndexedLiteralWithNameIndex(peer_.table()->GetByName(":path"), "/spam/eggs.html"); ExpectIndexedLiteral(peer_.table()->GetByName(":authority"), "www.example.com"); ExpectIndexedLiteral("-foo", "bar"); ExpectIndexedLiteral("foo", "bar"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "c=dd"); CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, CookieToCrumbs) { test::HpackEncoderPeer peer(nullptr); std::vector<absl::string_view> out; peer.CookieToCrumbs(" foo=1;bar=2 ; bar=3; bing=4; ", &out); EXPECT_THAT(out, ElementsAre("foo=1", "bar=2 ", "bar=3", " bing=4", "")); peer.CookieToCrumbs(";;foo = bar ;; ;baz =bing", &out); EXPECT_THAT(out, ElementsAre("", "", "foo = bar ", "", "", "baz =bing")); peer.CookieToCrumbs("baz=bing; foo=bar; baz=bing", &out); EXPECT_THAT(out, ElementsAre("baz=bing", "foo=bar", "baz=bing")); peer.CookieToCrumbs("baz=bing", &out); EXPECT_THAT(out, ElementsAre("baz=bing")); peer.CookieToCrumbs("", &out); EXPECT_THAT(out, ElementsAre("")); peer.CookieToCrumbs("foo;bar; baz;baz;bing;", &out); EXPECT_THAT(out, ElementsAre("foo", "bar", "baz", "baz", "bing", "")); peer.CookieToCrumbs(" \t foo=1;bar=2 ; bar=3;\t ", &out); EXPECT_THAT(out, ElementsAre("foo=1", "bar=2 ", "bar=3", "")); peer.CookieToCrumbs(" \t foo=1;bar=2 ; bar=3 \t ", &out); EXPECT_THAT(out, ElementsAre("foo=1", "bar=2 ", "bar=3")); } TEST_P(HpackEncoderTest, DecomposeRepresentation) { test::HpackEncoderPeer peer(nullptr); std::vector<absl::string_view> out; peer.DecomposeRepresentation("", &out); EXPECT_THAT(out, ElementsAre("")); peer.DecomposeRepresentation("foobar", &out); EXPECT_THAT(out, ElementsAre("foobar")); peer.DecomposeRepresentation(absl::string_view("foo\0bar", 7), &out); EXPECT_THAT(out, ElementsAre("foo", "bar")); peer.DecomposeRepresentation(absl::string_view("\0foo\0bar", 8), &out); EXPECT_THAT(out, ElementsAre("", "foo", "bar")); peer.DecomposeRepresentation(absl::string_view("foo\0bar\0", 8), &out); EXPECT_THAT(out, ElementsAre("foo", "bar", "")); peer.DecomposeRepresentation(absl::string_view("\0foo\0bar\0", 9), &out); EXPECT_THAT(out, ElementsAre("", "foo", "bar", "")); } TEST_P(HpackEncoderTest, CrumbleNullByteDelimitedValue) { if (strategy_ == kRepresentations) { return; } quiche::HttpHeaderBlock headers; headers["spam"] = std::string("foo\0bar", 7); ExpectIndexedLiteral("spam", "foo"); expected_.AppendPrefix(kLiteralIncrementalIndexOpcode); expected_.AppendUint32(62); expected_.AppendPrefix(kStringLiteralIdentityEncoded); expected_.AppendUint32(3); expected_.AppendBytes("bar"); CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdate) { encoder_.ApplyHeaderTableSizeSetting(1024); ExpectHeaderTableSizeUpdate(1024); ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdateWithMin) { const size_t starting_size = peer_.table()->settings_size_bound(); encoder_.ApplyHeaderTableSizeSetting(starting_size - 2); encoder_.ApplyHeaderTableSizeSetting(starting_size - 1); ExpectHeaderTableSizeUpdate(starting_size - 2); ExpectHeaderTableSizeUpdate(starting_size - 1); ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdateWithExistingSize) { encoder_.ApplyHeaderTableSizeSetting(peer_.table()->settings_size_bound()); ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdatesWithGreaterSize) { const size_t starting_size = peer_.table()->settings_size_bound(); encoder_.ApplyHeaderTableSizeSetting(starting_size + 1); encoder_.ApplyHeaderTableSizeSetting(starting_size + 2); ExpectHeaderTableSizeUpdate(starting_size + 2); ExpectIndexedLiteral("key3", "value3"); quiche::HttpHeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_encoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/hpack_encoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2007a2bf-7f3f-423a-b1e9-e55eef2b0485
cpp
google/quiche
hpack_varint_encoder
quiche/http2/hpack/varint/hpack_varint_encoder.cc
quiche/http2/hpack/varint/hpack_varint_encoder_test.cc
#include "quiche/http2/hpack/varint/hpack_varint_encoder.h" #include <limits> #include <string> #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { void HpackVarintEncoder::Encode(uint8_t high_bits, uint8_t prefix_length, uint64_t varint, std::string* output) { QUICHE_DCHECK_LE(1u, prefix_length); QUICHE_DCHECK_LE(prefix_length, 8u); const uint8_t prefix_mask = (1 << prefix_length) - 1; QUICHE_DCHECK_EQ(0, high_bits & prefix_mask); if (varint < prefix_mask) { unsigned char first_byte = high_bits | static_cast<unsigned char>(varint); output->push_back(first_byte); return; } unsigned char first_byte = high_bits | prefix_mask; output->push_back(first_byte); varint -= prefix_mask; while (varint >= 128) { output->push_back(0b10000000 | (varint % 128)); varint >>= 7; } output->push_back(varint); } }
#include "quiche/http2/hpack/varint/hpack_varint_encoder.h" #include <cstddef> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { struct { uint8_t high_bits; uint8_t prefix_length; uint64_t value; uint8_t expected_encoding; } kShortTestData[] = {{0b10110010, 1, 0, 0b10110010}, {0b10101100, 2, 2, 0b10101110}, {0b10100000, 3, 6, 0b10100110}, {0b10110000, 4, 13, 0b10111101}, {0b10100000, 5, 8, 0b10101000}, {0b11000000, 6, 48, 0b11110000}, {0b10000000, 7, 99, 0b11100011}, {0b00000000, 5, 10, 0b00001010}}; TEST(HpackVarintEncoderTest, Short) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kShortTestData); ++i) { std::string output; HpackVarintEncoder::Encode(kShortTestData[i].high_bits, kShortTestData[i].prefix_length, kShortTestData[i].value, &output); ASSERT_EQ(1u, output.size()); EXPECT_EQ(kShortTestData[i].expected_encoding, static_cast<uint8_t>(output[0])); } } struct { uint8_t high_bits; uint8_t prefix_length; uint64_t value; const char* expected_encoding; } kLongTestData[] = { {0b10011000, 3, 103, "9f60"}, {0b10010000, 4, 57, "9f2a"}, {0b11000000, 5, 158, "df7f"}, {0b01000000, 6, 65, "7f02"}, {0b00000000, 7, 200, "7f49"}, {0b10011000, 3, 12345, "9fb260"}, {0b10010000, 4, 5401, "9f8a2a"}, {0b11000000, 5, 16327, "dfa87f"}, {0b01000000, 6, 399, "7fd002"}, {0b00000000, 7, 9598, "7fff49"}, {0b10011000, 3, 1579281, "9f8ab260"}, {0b10010000, 4, 689488, "9fc18a2a"}, {0b11000000, 5, 2085964, "dfada87f"}, {0b01000000, 6, 43103, "7fa0d002"}, {0b00000000, 7, 1212541, "7ffeff49"}, {0b10011000, 3, 202147110, "9f9f8ab260"}, {0b10010000, 4, 88252593, "9fa2c18a2a"}, {0b11000000, 5, 266999535, "dfd0ada87f"}, {0b01000000, 6, 5509304, "7ff9a0d002"}, {0b00000000, 7, 155189149, "7f9efeff49"}, {0b10011000, 3, 3311978140938, "9f83aa9f8ab260"}, {0b10010000, 4, 1445930244223, "9ff0b0a2c18a2a"}, {0b11000000, 5, 4374519874169, "dfda84d0ada87f"}, {0b01000000, 6, 90263420404, "7fb5fbf9a0d002"}, {0b00000000, 7, 2542616951118, "7fcff19efeff49"}, {0b10011000, 3, 54263449861016696, "9ff19883aa9f8ab260"}, {0b10010000, 4, 23690121121119891, "9f84fdf0b0a2c18a2a"}, {0b11000000, 5, 71672133617889215, "dfa0dfda84d0ada87f"}, {0b01000000, 6, 1478875878881374, "7f9ff0b5fbf9a0d002"}, {0b00000000, 7, 41658236125045114, "7ffbc1cff19efeff49"}, {0b10011000, 3, 12832019021693745307u, "9f94f1f19883aa9f8ab201"}, {0b10010000, 4, 9980690937382242223u, "9fa08f84fdf0b0a2c18a01"}, {0b11000000, 5, 12131360551794650846u, "dfbfdda0dfda84d0ada801"}, {0b01000000, 6, 15006530362736632796u, "7f9dc79ff0b5fbf9a0d001"}, {0b00000000, 7, 18445754019193211014u, "7f8790fbc1cff19efeff01"}, {0b10011000, 3, 18446744073709551615u, "9ff8ffffffffffffffff01"}, {0b10010000, 4, 18446744073709551615u, "9ff0ffffffffffffffff01"}, {0b11000000, 5, 18446744073709551615u, "dfe0ffffffffffffffff01"}, {0b01000000, 6, 18446744073709551615u, "7fc0ffffffffffffffff01"}, {0b00000000, 7, 18446744073709551615u, "7f80ffffffffffffffff01"}, {0b00000000, 5, 1337, "1f9a0a"}, }; TEST(HpackVarintEncoderTest, Long) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kLongTestData); ++i) { std::string expected_encoding; ASSERT_TRUE(absl::HexStringToBytes(kLongTestData[i].expected_encoding, &expected_encoding)); std::string output; HpackVarintEncoder::Encode(kLongTestData[i].high_bits, kLongTestData[i].prefix_length, kLongTestData[i].value, &output); EXPECT_EQ(expected_encoding, output); } } struct { uint8_t high_bits; uint8_t prefix_length; uint64_t value; uint8_t expected_encoding_first_byte; } kLastByteIsZeroTestData[] = { {0b10110010, 1, 1, 0b10110011}, {0b10101100, 2, 3, 0b10101111}, {0b10101000, 3, 7, 0b10101111}, {0b10110000, 4, 15, 0b10111111}, {0b10100000, 5, 31, 0b10111111}, {0b11000000, 6, 63, 0b11111111}, {0b10000000, 7, 127, 0b11111111}, {0b00000000, 8, 255, 0b11111111}}; TEST(HpackVarintEncoderTest, LastByteIsZero) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kLastByteIsZeroTestData); ++i) { std::string output; HpackVarintEncoder::Encode(kLastByteIsZeroTestData[i].high_bits, kLastByteIsZeroTestData[i].prefix_length, kLastByteIsZeroTestData[i].value, &output); ASSERT_EQ(2u, output.size()); EXPECT_EQ(kLastByteIsZeroTestData[i].expected_encoding_first_byte, static_cast<uint8_t>(output[0])); EXPECT_EQ(0b00000000, output[1]); } } TEST(HpackVarintEncoderTest, Append) { std::string output("foo"); std::string expected_encoding; ASSERT_TRUE(absl::HexStringToBytes("666f6f", &expected_encoding)); EXPECT_EQ(expected_encoding, output); HpackVarintEncoder::Encode(0b10011000, 3, 103, &output); ASSERT_TRUE(absl::HexStringToBytes("666f6f9f60", &expected_encoding)); EXPECT_EQ(expected_encoding, output); HpackVarintEncoder::Encode(0b10100000, 5, 8, &output); ASSERT_TRUE(absl::HexStringToBytes("666f6f9f60a8", &expected_encoding)); EXPECT_EQ(expected_encoding, output); HpackVarintEncoder::Encode(0b10011000, 3, 202147110, &output); ASSERT_TRUE( absl::HexStringToBytes("666f6f9f60a89f9f8ab260", &expected_encoding)); EXPECT_EQ(expected_encoding, output); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/varint/hpack_varint_encoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/varint/hpack_varint_encoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e281052a-c5ac-4c16-a801-e69a8838f43e
cpp
google/quiche
hpack_varint_decoder
quiche/http2/hpack/varint/hpack_varint_decoder.cc
quiche/http2/hpack/varint/hpack_varint_decoder_test.cc
#include "quiche/http2/hpack/varint/hpack_varint_decoder.h" #include <limits> #include <string> #include "absl/strings/str_cat.h" namespace http2 { DecodeStatus HpackVarintDecoder::Start(uint8_t prefix_value, uint8_t prefix_length, DecodeBuffer* db) { QUICHE_DCHECK_LE(3u, prefix_length); QUICHE_DCHECK_LE(prefix_length, 8u); const uint8_t prefix_mask = (1 << prefix_length) - 1; value_ = prefix_value & prefix_mask; if (value_ < prefix_mask) { MarkDone(); return DecodeStatus::kDecodeDone; } offset_ = 0; return Resume(db); } DecodeStatus HpackVarintDecoder::StartExtended(uint8_t prefix_length, DecodeBuffer* db) { QUICHE_DCHECK_LE(3u, prefix_length); QUICHE_DCHECK_LE(prefix_length, 8u); value_ = (1 << prefix_length) - 1; offset_ = 0; return Resume(db); } DecodeStatus HpackVarintDecoder::Resume(DecodeBuffer* db) { const uint8_t kMaxOffset = 63; CheckNotDone(); while (offset_ < kMaxOffset) { if (db->Empty()) { return DecodeStatus::kDecodeInProgress; } uint8_t byte = db->DecodeUInt8(); uint64_t summand = byte & 0x7f; QUICHE_DCHECK_LE(offset_, 56); QUICHE_DCHECK_LE(summand, std::numeric_limits<uint64_t>::max() >> offset_); summand <<= offset_; QUICHE_DCHECK_LE(value_, std::numeric_limits<uint64_t>::max() - summand); value_ += summand; if ((byte & 0x80) == 0) { MarkDone(); return DecodeStatus::kDecodeDone; } offset_ += 7; } if (db->Empty()) { return DecodeStatus::kDecodeInProgress; } QUICHE_DCHECK_EQ(kMaxOffset, offset_); uint8_t byte = db->DecodeUInt8(); if ((byte & 0x80) == 0) { uint64_t summand = byte & 0x7f; if (summand <= std::numeric_limits<uint64_t>::max() >> offset_) { summand <<= offset_; if (value_ <= std::numeric_limits<uint64_t>::max() - summand) { value_ += summand; MarkDone(); return DecodeStatus::kDecodeDone; } } } QUICHE_DLOG(WARNING) << "Variable length int encoding is too large or too long. " << DebugString(); MarkDone(); return DecodeStatus::kDecodeError; } uint64_t HpackVarintDecoder::value() const { CheckDone(); return value_; } void HpackVarintDecoder::set_value(uint64_t v) { MarkDone(); value_ = v; } std::string HpackVarintDecoder::DebugString() const { return absl::StrCat("HpackVarintDecoder(value=", value_, ", offset=", offset_, ")"); } DecodeStatus HpackVarintDecoder::StartForTest(uint8_t prefix_value, uint8_t prefix_length, DecodeBuffer* db) { return Start(prefix_value, prefix_length, db); } DecodeStatus HpackVarintDecoder::StartExtendedForTest(uint8_t prefix_length, DecodeBuffer* db) { return StartExtended(prefix_length, db); } DecodeStatus HpackVarintDecoder::ResumeForTest(DecodeBuffer* db) { return Resume(db); } }
#include "quiche/http2/hpack/varint/hpack_varint_decoder.h" #include <stddef.h> #include <cstdint> #include <string> #include <tuple> #include <utility> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionSuccess; namespace http2 { namespace test { namespace { class HpackVarintDecoderTest : public RandomDecoderTest, public ::testing::WithParamInterface<std::tuple<uint8_t, const char*>> { protected: HpackVarintDecoderTest() : high_bits_(std::get<0>(GetParam())), prefix_length_(0) { QUICHE_CHECK(absl::HexStringToBytes(std::get<1>(GetParam()), &suffix_)); } void DecodeExpectSuccess(absl::string_view data, uint32_t prefix_length, uint64_t expected_value) { Validator validator = [expected_value, this]( const DecodeBuffer& , DecodeStatus ) -> AssertionResult { HTTP2_VERIFY_EQ(expected_value, decoder_.value()) << "Value doesn't match expected: " << decoder_.value() << " != " << expected_value; return AssertionSuccess(); }; validator = ValidateDoneAndOffset( data.size(), std::move(validator)); EXPECT_TRUE(Decode(data, prefix_length, std::move(validator))); EXPECT_EQ(expected_value, decoder_.value()); } void DecodeExpectError(absl::string_view data, uint32_t prefix_length) { Validator validator = [](const DecodeBuffer& , DecodeStatus status) -> AssertionResult { HTTP2_VERIFY_EQ(DecodeStatus::kDecodeError, status); return AssertionSuccess(); }; EXPECT_TRUE(Decode(data, prefix_length, std::move(validator))); } private: AssertionResult Decode(absl::string_view data, uint32_t prefix_length, const Validator validator) { prefix_length_ = prefix_length; std::string data_copy(data); uint8_t high_bits_mask = 0b11111111 << prefix_length_; data_copy[0] |= (high_bits_mask & high_bits_); data_copy.append(suffix_); DecodeBuffer b(data_copy); bool return_non_zero_on_first = true; return DecodeAndValidateSeveralWays(&b, return_non_zero_on_first, validator); } DecodeStatus StartDecoding(DecodeBuffer* b) override { QUICHE_CHECK_LT(0u, b->Remaining()); uint8_t prefix = b->DecodeUInt8(); return decoder_.Start(prefix, prefix_length_, b); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { return decoder_.Resume(b); } const uint8_t high_bits_; std::string suffix_; HpackVarintDecoder decoder_; uint8_t prefix_length_; }; INSTANTIATE_TEST_SUITE_P( HpackVarintDecoderTest, HpackVarintDecoderTest, ::testing::Combine( ::testing::Values(0b00000000, 0b11111111, 0b10101010), ::testing::Values("", "00", "666f6f"))); struct { const char* data; uint32_t prefix_length; uint64_t expected_value; } kSuccessTestData[] = { {"00", 3, 0}, {"00", 4, 0}, {"00", 5, 0}, {"00", 6, 0}, {"00", 7, 0}, {"00", 8, 0}, {"06", 3, 6}, {"0d", 4, 13}, {"10", 5, 16}, {"29", 6, 41}, {"56", 7, 86}, {"bf", 8, 191}, {"0700", 3, 7}, {"0f00", 4, 15}, {"1f00", 5, 31}, {"3f00", 6, 63}, {"7f00", 7, 127}, {"ff00", 8, 255}, {"078000", 3, 7}, {"0f8000", 4, 15}, {"1f8000", 5, 31}, {"3f8000", 6, 63}, {"7f8000", 7, 127}, {"ff8000", 8, 255}, {"0760", 3, 103}, {"0f2a", 4, 57}, {"1f7f", 5, 158}, {"3f02", 6, 65}, {"7f49", 7, 200}, {"ff6f", 8, 366}, {"07e000", 3, 103}, {"0faa00", 4, 57}, {"1fff00", 5, 158}, {"3f8200", 6, 65}, {"7fc900", 7, 200}, {"ffef00", 8, 366}, {"07e08000", 3, 103}, {"0faa8000", 4, 57}, {"1fff8000", 5, 158}, {"3f828000", 6, 65}, {"7fc98000", 7, 200}, {"ffef8000", 8, 366}, {"07e0808080808080808000", 3, 103}, {"0faa808080808080808000", 4, 57}, {"1fff808080808080808000", 5, 158}, {"3f82808080808080808000", 6, 65}, {"7fc9808080808080808000", 7, 200}, {"ffef808080808080808000", 8, 366}, {"07b260", 3, 12345}, {"0f8a2a", 4, 5401}, {"1fa87f", 5, 16327}, {"3fd002", 6, 399}, {"7fff49", 7, 9598}, {"ffe32f", 8, 6370}, {"07b2e000", 3, 12345}, {"0f8aaa00", 4, 5401}, {"1fa8ff00", 5, 16327}, {"3fd08200", 6, 399}, {"7fffc900", 7, 9598}, {"ffe3af00", 8, 6370}, {"07b2e080808080808000", 3, 12345}, {"0f8aaa80808080808000", 4, 5401}, {"1fa8ff80808080808000", 5, 16327}, {"3fd08280808080808000", 6, 399}, {"7fffc980808080808000", 7, 9598}, {"ffe3af80808080808000", 8, 6370}, {"078ab260", 3, 1579281}, {"0fc18a2a", 4, 689488}, {"1fada87f", 5, 2085964}, {"3fa0d002", 6, 43103}, {"7ffeff49", 7, 1212541}, {"ff93de23", 8, 585746}, {"078ab2e000", 3, 1579281}, {"0fc18aaa00", 4, 689488}, {"1fada8ff00", 5, 2085964}, {"3fa0d08200", 6, 43103}, {"7ffeffc900", 7, 1212541}, {"ff93dea300", 8, 585746}, {"079f8ab260", 3, 202147110}, {"0fa2c18a2a", 4, 88252593}, {"1fd0ada87f", 5, 266999535}, {"3ff9a0d002", 6, 5509304}, {"7f9efeff49", 7, 155189149}, {"ffaa82f404", 8, 10289705}, {"079f8ab2e000", 3, 202147110}, {"0fa2c18aaa00", 4, 88252593}, {"1fd0ada8ff00", 5, 266999535}, {"3ff9a0d08200", 6, 5509304}, {"7f9efeffc900", 7, 155189149}, {"ffaa82f48400", 8, 10289705}, {"0783aa9f8ab260", 3, 3311978140938}, {"0ff0b0a2c18a2a", 4, 1445930244223}, {"1fda84d0ada87f", 5, 4374519874169}, {"3fb5fbf9a0d002", 6, 90263420404}, {"7fcff19efeff49", 7, 2542616951118}, {"ff9fa486bbc327", 8, 1358138807070}, {"07f19883aa9f8ab260", 3, 54263449861016696}, {"0f84fdf0b0a2c18a2a", 4, 23690121121119891}, {"1fa0dfda84d0ada87f", 5, 71672133617889215}, {"3f9ff0b5fbf9a0d002", 6, 1478875878881374}, {"7ffbc1cff19efeff49", 7, 41658236125045114}, {"ff91b6fb85af99c342", 8, 37450237664484368}, {"0794f1f19883aa9f8ab201", 3, 12832019021693745307u}, {"0fa08f84fdf0b0a2c18a01", 4, 9980690937382242223u}, {"1fbfdda0dfda84d0ada801", 5, 12131360551794650846u}, {"3f9dc79ff0b5fbf9a0d001", 6, 15006530362736632796u}, {"7f8790fbc1cff19efeff01", 7, 18445754019193211014u}, {"fffba8c5b8d3fe9f8c8401", 8, 9518498503615141242u}, {"07f8ffffffffffffffff01", 3, 18446744073709551615u}, {"0ff0ffffffffffffffff01", 4, 18446744073709551615u}, {"1fe0ffffffffffffffff01", 5, 18446744073709551615u}, {"3fc0ffffffffffffffff01", 6, 18446744073709551615u}, {"7f80ffffffffffffffff01", 7, 18446744073709551615u}, {"ff80feffffffffffffff01", 8, 18446744073709551615u}, {"0a", 5, 10}, {"1f9a0a", 5, 1337}, }; TEST_P(HpackVarintDecoderTest, Success) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kSuccessTestData); ++i) { std::string data_bytes; ASSERT_TRUE(absl::HexStringToBytes(kSuccessTestData[i].data, &data_bytes)); DecodeExpectSuccess(data_bytes, kSuccessTestData[i].prefix_length, kSuccessTestData[i].expected_value); } } struct { const char* data; uint32_t prefix_length; } kErrorTestData[] = { {"0780808080808080808080", 3}, {"0f80808080808080808080", 4}, {"1f80808080808080808080", 5}, {"3f80808080808080808080", 6}, {"7f80808080808080808080", 7}, {"ff80808080808080808080", 8}, {"07ffffffffffffffffffff", 3}, {"0fffffffffffffffffffff", 4}, {"1fffffffffffffffffffff", 5}, {"3fffffffffffffffffffff", 6}, {"7fffffffffffffffffffff", 7}, {"ffffffffffffffffffffff", 8}, {"07f9ffffffffffffffff01", 3}, {"0ff1ffffffffffffffff01", 4}, {"1fe1ffffffffffffffff01", 5}, {"3fc1ffffffffffffffff01", 6}, {"7f81ffffffffffffffff01", 7}, {"ff81feffffffffffffff01", 8}, {"07f8ffffffffffffffff8100", 3}, {"0ff0ffffffffffffffff8100", 4}, {"1fe0ffffffffffffffff8100", 5}, {"3fc0ffffffffffffffff8100", 6}, {"7f80ffffffffffffffff8100", 7}, {"ff80feffffffffffffff8100", 8}}; TEST_P(HpackVarintDecoderTest, Error) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kErrorTestData); ++i) { std::string data_bytes; ASSERT_TRUE(absl::HexStringToBytes(kErrorTestData[i].data, &data_bytes)); DecodeExpectError(data_bytes, kErrorTestData[i].prefix_length); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/varint/hpack_varint_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/varint/hpack_varint_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
af3cb316-da96-4619-8d4c-eff187dc6413
cpp
google/quiche
hpack_decoder_string_buffer
quiche/http2/hpack/decoder/hpack_decoder_string_buffer.cc
quiche/http2/hpack/decoder/hpack_decoder_string_buffer_test.cc
#include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h" #include <ostream> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer::State v) { switch (v) { case HpackDecoderStringBuffer::State::RESET: return out << "RESET"; case HpackDecoderStringBuffer::State::COLLECTING: return out << "COLLECTING"; case HpackDecoderStringBuffer::State::COMPLETE: return out << "COMPLETE"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_50_1) << "Invalid HpackDecoderStringBuffer::State: " << unknown; return out << "HpackDecoderStringBuffer::State(" << unknown << ")"; } std::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer::Backing v) { switch (v) { case HpackDecoderStringBuffer::Backing::RESET: return out << "RESET"; case HpackDecoderStringBuffer::Backing::UNBUFFERED: return out << "UNBUFFERED"; case HpackDecoderStringBuffer::Backing::BUFFERED: return out << "BUFFERED"; } auto v2 = static_cast<int>(v); QUICHE_BUG(http2_bug_50_2) << "Invalid HpackDecoderStringBuffer::Backing: " << v2; return out << "HpackDecoderStringBuffer::Backing(" << v2 << ")"; } HpackDecoderStringBuffer::HpackDecoderStringBuffer() : remaining_len_(0), is_huffman_encoded_(false), state_(State::RESET), backing_(Backing::RESET) {} HpackDecoderStringBuffer::~HpackDecoderStringBuffer() = default; void HpackDecoderStringBuffer::Reset() { QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::Reset"; state_ = State::RESET; } void HpackDecoderStringBuffer::OnStart(bool huffman_encoded, size_t len) { QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnStart"; QUICHE_DCHECK_EQ(state_, State::RESET); remaining_len_ = len; is_huffman_encoded_ = huffman_encoded; state_ = State::COLLECTING; if (huffman_encoded) { decoder_.Reset(); buffer_.clear(); backing_ = Backing::BUFFERED; len = len * 8 / 5; if (buffer_.capacity() < len) { buffer_.reserve(len); } } else { backing_ = Backing::RESET; value_ = absl::string_view(); } } bool HpackDecoderStringBuffer::OnData(const char* data, size_t len) { QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnData state=" << state_ << ", backing=" << backing_; QUICHE_DCHECK_EQ(state_, State::COLLECTING); QUICHE_DCHECK_LE(len, remaining_len_); remaining_len_ -= len; if (is_huffman_encoded_) { QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED); return decoder_.Decode(absl::string_view(data, len), &buffer_); } if (backing_ == Backing::RESET) { if (remaining_len_ == 0) { value_ = absl::string_view(data, len); backing_ = Backing::UNBUFFERED; return true; } backing_ = Backing::BUFFERED; buffer_.reserve(remaining_len_ + len); buffer_.assign(data, len); return true; } QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED); buffer_.append(data, len); return true; } bool HpackDecoderStringBuffer::OnEnd() { QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnEnd"; QUICHE_DCHECK_EQ(state_, State::COLLECTING); QUICHE_DCHECK_EQ(0u, remaining_len_); if (is_huffman_encoded_) { QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED); if (!decoder_.InputProperlyTerminated()) { return false; } value_ = buffer_; } else if (backing_ == Backing::BUFFERED) { value_ = buffer_; } state_ = State::COMPLETE; return true; } void HpackDecoderStringBuffer::BufferStringIfUnbuffered() { QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferStringIfUnbuffered state=" << state_ << ", backing=" << backing_; if (state_ != State::RESET && backing_ == Backing::UNBUFFERED) { QUICHE_DVLOG(2) << "HpackDecoderStringBuffer buffering std::string of length " << value_.size(); buffer_.assign(value_.data(), value_.size()); if (state_ == State::COMPLETE) { value_ = buffer_; } backing_ = Backing::BUFFERED; } } bool HpackDecoderStringBuffer::IsBuffered() const { QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::IsBuffered"; return state_ != State::RESET && backing_ == Backing::BUFFERED; } size_t HpackDecoderStringBuffer::BufferedLength() const { QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferedLength"; return IsBuffered() ? buffer_.size() : 0; } absl::string_view HpackDecoderStringBuffer::str() const { QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::str"; QUICHE_DCHECK_EQ(state_, State::COMPLETE); return value_; } absl::string_view HpackDecoderStringBuffer::GetStringIfComplete() const { if (state_ != State::COMPLETE) { return {}; } return str(); } std::string HpackDecoderStringBuffer::ReleaseString() { QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::ReleaseString"; QUICHE_DCHECK_EQ(state_, State::COMPLETE); QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED); if (state_ == State::COMPLETE) { state_ = State::RESET; if (backing_ == Backing::BUFFERED) { return std::move(buffer_); } else { return std::string(value_); } } return ""; } void HpackDecoderStringBuffer::OutputDebugStringTo(std::ostream& out) const { out << "{state=" << state_; if (state_ != State::RESET) { out << ", backing=" << backing_; out << ", remaining_len=" << remaining_len_; out << ", is_huffman_encoded=" << is_huffman_encoded_; if (backing_ == Backing::BUFFERED) { out << ", buffer: " << buffer_; } else { out << ", value: " << value_; } } out << "}"; } std::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer& v) { v.OutputDebugStringTo(out); return out; } }
#include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h" #include <initializer_list> #include <sstream> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::HasSubstr; namespace http2 { namespace test { namespace { class HpackDecoderStringBufferTest : public quiche::test::QuicheTest { protected: typedef HpackDecoderStringBuffer::State State; typedef HpackDecoderStringBuffer::Backing Backing; State state() const { return buf_.state_for_testing(); } Backing backing() const { return buf_.backing_for_testing(); } AssertionResult VerifyLogHasSubstrs(std::initializer_list<std::string> strs) { QUICHE_VLOG(1) << buf_; std::ostringstream ss; buf_.OutputDebugStringTo(ss); std::string dbg_str(ss.str()); for (const auto& expected : strs) { HTTP2_VERIFY_TRUE(absl::StrContains(dbg_str, expected)); } return AssertionSuccess(); } HpackDecoderStringBuffer buf_; }; TEST_F(HpackDecoderStringBufferTest, PlainWhole) { absl::string_view data("some text."); QUICHE_LOG(INFO) << buf_; EXPECT_EQ(state(), State::RESET); buf_.OnStart( false, data.size()); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::RESET); QUICHE_LOG(INFO) << buf_; EXPECT_TRUE(buf_.OnData(data.data(), data.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::UNBUFFERED); EXPECT_TRUE(buf_.OnEnd()); EXPECT_EQ(state(), State::COMPLETE); EXPECT_EQ(backing(), Backing::UNBUFFERED); EXPECT_EQ(0u, buf_.BufferedLength()); EXPECT_TRUE(VerifyLogHasSubstrs( {"state=COMPLETE", "backing=UNBUFFERED", "value: some text."})); EXPECT_EQ(data.data(), buf_.str().data()); buf_.BufferStringIfUnbuffered(); QUICHE_LOG(INFO) << buf_; EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), data.size()); EXPECT_EQ(data, buf_.str()); EXPECT_NE(data.data(), buf_.str().data()); EXPECT_TRUE(VerifyLogHasSubstrs( {"state=COMPLETE", "backing=BUFFERED", "buffer: some text."})); } TEST_F(HpackDecoderStringBufferTest, PlainSplit) { absl::string_view data("some text."); absl::string_view part1 = data.substr(0, 1); absl::string_view part2 = data.substr(1); EXPECT_EQ(state(), State::RESET); buf_.OnStart( false, data.size()); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::RESET); EXPECT_TRUE(buf_.OnData(part1.data(), part1.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), part1.size()); QUICHE_LOG(INFO) << buf_; EXPECT_TRUE(buf_.OnData(part2.data(), part2.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), data.size()); EXPECT_TRUE(buf_.OnEnd()); EXPECT_EQ(state(), State::COMPLETE); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), data.size()); QUICHE_LOG(INFO) << buf_; absl::string_view buffered = buf_.str(); EXPECT_EQ(data, buffered); EXPECT_NE(data.data(), buffered.data()); buf_.BufferStringIfUnbuffered(); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), data.size()); EXPECT_EQ(buffered, buf_.str()); EXPECT_EQ(buffered.data(), buf_.str().data()); } TEST_F(HpackDecoderStringBufferTest, HuffmanWhole) { std::string encoded; ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded)); absl::string_view decoded("www.example.com"); EXPECT_EQ(state(), State::RESET); buf_.OnStart( true, encoded.size()); EXPECT_EQ(state(), State::COLLECTING); EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_TRUE(buf_.OnEnd()); EXPECT_EQ(state(), State::COMPLETE); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), decoded.size()); EXPECT_EQ(decoded, buf_.str()); EXPECT_TRUE(VerifyLogHasSubstrs( {"{state=COMPLETE", "backing=BUFFERED", "buffer: www.example.com}"})); std::string s = buf_.ReleaseString(); EXPECT_EQ(s, decoded); EXPECT_EQ(state(), State::RESET); } TEST_F(HpackDecoderStringBufferTest, HuffmanSplit) { std::string encoded; ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded)); std::string part1 = encoded.substr(0, 5); std::string part2 = encoded.substr(5); absl::string_view decoded("www.example.com"); EXPECT_EQ(state(), State::RESET); buf_.OnStart( true, encoded.size()); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(0u, buf_.BufferedLength()); QUICHE_LOG(INFO) << buf_; EXPECT_TRUE(buf_.OnData(part1.data(), part1.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_GT(buf_.BufferedLength(), 0u); EXPECT_LT(buf_.BufferedLength(), decoded.size()); QUICHE_LOG(INFO) << buf_; EXPECT_TRUE(buf_.OnData(part2.data(), part2.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), decoded.size()); QUICHE_LOG(INFO) << buf_; EXPECT_TRUE(buf_.OnEnd()); EXPECT_EQ(state(), State::COMPLETE); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_EQ(buf_.BufferedLength(), decoded.size()); EXPECT_EQ(decoded, buf_.str()); QUICHE_LOG(INFO) << buf_; buf_.Reset(); EXPECT_EQ(state(), State::RESET); QUICHE_LOG(INFO) << buf_; } TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnData) { std::string encoded; ASSERT_TRUE(absl::HexStringToBytes("ffffffff", &encoded)); buf_.OnStart( true, encoded.size()); EXPECT_EQ(state(), State::COLLECTING); EXPECT_FALSE(buf_.OnData(encoded.data(), encoded.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); QUICHE_LOG(INFO) << buf_; } TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnEnd) { std::string encoded; ASSERT_TRUE(absl::HexStringToBytes("00", &encoded)); buf_.OnStart( true, encoded.size()); EXPECT_EQ(state(), State::COLLECTING); EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size())); EXPECT_EQ(state(), State::COLLECTING); EXPECT_EQ(backing(), Backing::BUFFERED); EXPECT_FALSE(buf_.OnEnd()); QUICHE_LOG(INFO) << buf_; } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_string_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_string_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
905c7aba-44b7-45a2-bde2-d929d4789674
cpp
google/quiche
hpack_string_decoder
quiche/http2/hpack/decoder/hpack_string_decoder.cc
quiche/http2/hpack/decoder/hpack_string_decoder_test.cc
#include "quiche/http2/hpack/decoder/hpack_string_decoder.h" #include <ostream> #include <string> #include "absl/strings/str_cat.h" namespace http2 { std::string HpackStringDecoder::DebugString() const { return absl::StrCat("HpackStringDecoder(state=", StateToString(state_), ", length=", length_decoder_.DebugString(), ", remaining=", remaining_, ", huffman=", huffman_encoded_ ? "true)" : "false)"); } std::string HpackStringDecoder::StateToString(StringDecoderState v) { switch (v) { case kStartDecodingLength: return "kStartDecodingLength"; case kDecodingString: return "kDecodingString"; case kResumeDecodingLength: return "kResumeDecodingLength"; } return absl::StrCat("UNKNOWN_STATE(", static_cast<uint32_t>(v), ")"); } std::ostream& operator<<(std::ostream& out, const HpackStringDecoder& v) { return out << v.DebugString(); } }
#include "quiche/http2/hpack/decoder/hpack_string_decoder.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/decoder/hpack_string_decoder_listener.h" #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/test_tools/hpack_string_collector.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { const bool kMayReturnZeroOnFirst = false; const bool kCompressed = true; const bool kUncompressed = false; class HpackStringDecoderTest : public RandomDecoderTest { protected: HpackStringDecoderTest() : listener_(&collector_) {} DecodeStatus StartDecoding(DecodeBuffer* b) override { ++start_decoding_calls_; collector_.Clear(); return decoder_.Start(b, &listener_); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { QUICHE_VLOG(1) << decoder_.DebugString(); QUICHE_VLOG(2) << collector_; return decoder_.Resume(b, &listener_); } AssertionResult Collected(absl::string_view s, bool huffman_encoded) { QUICHE_VLOG(1) << collector_; return collector_.Collected(s, huffman_encoded); } Validator MakeValidator(const std::string& expected_str, bool expected_huffman) { return [expected_str, expected_huffman, this]( const DecodeBuffer& , DecodeStatus ) -> AssertionResult { AssertionResult result = Collected(expected_str, expected_huffman); if (result) { HTTP2_VERIFY_EQ(collector_, HpackStringCollector(expected_str, expected_huffman)); } else { HTTP2_VERIFY_NE(collector_, HpackStringCollector(expected_str, expected_huffman)); } QUICHE_VLOG(2) << collector_.ToString(); collector_.Clear(); QUICHE_VLOG(2) << collector_; return result; }; } HpackStringDecoder decoder_; HpackStringCollector collector_; HpackStringDecoderVLoggingListener listener_; size_t start_decoding_calls_ = 0; }; TEST_F(HpackStringDecoderTest, DecodeEmptyString) { { Validator validator = ValidateDoneAndEmpty(MakeValidator("", kCompressed)); const char kData[] = {'\x80'}; DecodeBuffer b(kData); EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator)); } { Validator validator = ValidateDoneAndOffset(1, MakeValidator("", kUncompressed)); const char kData[] = {'\x00', '\xff'}; DecodeBuffer b(kData); EXPECT_EQ(2u, b.Remaining()); EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator)); EXPECT_EQ(1u, b.Remaining()); } } TEST_F(HpackStringDecoderTest, DecodeShortString) { { Validator validator = ValidateDoneAndOffset(11, MakeValidator("start end.", kCompressed)); const char kData[] = "\x8astart end.Don't peek at this."; DecodeBuffer b(kData); EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator)); } { Validator validator = ValidateDoneAndOffset(11, MakeValidator("start end.", kUncompressed)); absl::string_view data("\x0astart end."); DecodeBuffer b(data); EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator)); } } TEST_F(HpackStringDecoderTest, DecodeLongStrings) { std::string name = Random().RandString(1024); std::string value = Random().RandString(65536); HpackBlockBuilder hbb; hbb.AppendString(false, name); uint32_t offset_after_name = hbb.size(); EXPECT_EQ(3 + name.size(), offset_after_name); hbb.AppendString(true, value); uint32_t offset_after_value = hbb.size(); EXPECT_EQ(3 + name.size() + 4 + value.size(), offset_after_value); DecodeBuffer b(hbb.buffer()); EXPECT_TRUE(DecodeAndValidateSeveralWays( &b, kMayReturnZeroOnFirst, ValidateDoneAndOffset(offset_after_name, MakeValidator(name, kUncompressed)))); EXPECT_EQ(offset_after_name, b.Offset()); EXPECT_EQ(offset_after_value - offset_after_name, b.Remaining()); EXPECT_TRUE(DecodeAndValidateSeveralWays( &b, kMayReturnZeroOnFirst, ValidateDoneAndOffset(offset_after_value - offset_after_name, MakeValidator(value, kCompressed)))); EXPECT_EQ(offset_after_value, b.Offset()); EXPECT_EQ(0u, b.Remaining()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_string_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_string_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
95152f6f-c076-41eb-920e-fe5928becd50
cpp
google/quiche
hpack_decoder_state
quiche/http2/hpack/decoder/hpack_decoder_state.cc
quiche/http2/hpack/decoder/hpack_decoder_state_test.cc
#include "quiche/http2/hpack/decoder/hpack_decoder_state.h" #include <string> #include <utility> #include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace { std::string ExtractString(HpackDecoderStringBuffer* string_buffer) { if (string_buffer->IsBuffered()) { return string_buffer->ReleaseString(); } else { auto result = std::string(string_buffer->str()); string_buffer->Reset(); return result; } } } HpackDecoderState::HpackDecoderState(HpackDecoderListener* listener) : listener_(listener), final_header_table_size_(Http2SettingsInfo::DefaultHeaderTableSize()), lowest_header_table_size_(final_header_table_size_), require_dynamic_table_size_update_(false), allow_dynamic_table_size_update_(true), saw_dynamic_table_size_update_(false), error_(HpackDecodingError::kOk) { QUICHE_CHECK(listener_); } HpackDecoderState::~HpackDecoderState() = default; void HpackDecoderState::ApplyHeaderTableSizeSetting( uint32_t header_table_size) { QUICHE_DVLOG(2) << "HpackDecoderState::ApplyHeaderTableSizeSetting(" << header_table_size << ")"; QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_); if (header_table_size < lowest_header_table_size_) { lowest_header_table_size_ = header_table_size; } final_header_table_size_ = header_table_size; QUICHE_DVLOG(2) << "low water mark: " << lowest_header_table_size_; QUICHE_DVLOG(2) << "final limit: " << final_header_table_size_; } void HpackDecoderState::OnHeaderBlockStart() { QUICHE_DVLOG(2) << "HpackDecoderState::OnHeaderBlockStart"; QUICHE_DCHECK(error_ == HpackDecodingError::kOk) << HpackDecodingErrorToString(error_); QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_); allow_dynamic_table_size_update_ = true; saw_dynamic_table_size_update_ = false; require_dynamic_table_size_update_ = (lowest_header_table_size_ < decoder_tables_.current_header_table_size() || final_header_table_size_ < decoder_tables_.header_table_size_limit()); QUICHE_DVLOG(2) << "HpackDecoderState::OnHeaderListStart " << "require_dynamic_table_size_update_=" << require_dynamic_table_size_update_; listener_->OnHeaderListStart(); } void HpackDecoderState::OnIndexedHeader(size_t index) { QUICHE_DVLOG(2) << "HpackDecoderState::OnIndexedHeader: " << index; if (error_ != HpackDecodingError::kOk) { return; } if (require_dynamic_table_size_update_) { ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate); return; } allow_dynamic_table_size_update_ = false; const HpackStringPair* entry = decoder_tables_.Lookup(index); if (entry != nullptr) { listener_->OnHeader(entry->name, entry->value); } else { ReportError(HpackDecodingError::kInvalidIndex); } } void HpackDecoderState::OnNameIndexAndLiteralValue( HpackEntryType entry_type, size_t name_index, HpackDecoderStringBuffer* value_buffer) { QUICHE_DVLOG(2) << "HpackDecoderState::OnNameIndexAndLiteralValue " << entry_type << ", " << name_index << ", " << value_buffer->str(); if (error_ != HpackDecodingError::kOk) { return; } if (require_dynamic_table_size_update_) { ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate); return; } allow_dynamic_table_size_update_ = false; const HpackStringPair* entry = decoder_tables_.Lookup(name_index); if (entry != nullptr) { std::string value(ExtractString(value_buffer)); listener_->OnHeader(entry->name, value); if (entry_type == HpackEntryType::kIndexedLiteralHeader) { decoder_tables_.Insert(entry->name, std::move(value)); } } else { ReportError(HpackDecodingError::kInvalidNameIndex); } } void HpackDecoderState::OnLiteralNameAndValue( HpackEntryType entry_type, HpackDecoderStringBuffer* name_buffer, HpackDecoderStringBuffer* value_buffer) { QUICHE_DVLOG(2) << "HpackDecoderState::OnLiteralNameAndValue " << entry_type << ", " << name_buffer->str() << ", " << value_buffer->str(); if (error_ != HpackDecodingError::kOk) { return; } if (require_dynamic_table_size_update_) { ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate); return; } allow_dynamic_table_size_update_ = false; std::string name(ExtractString(name_buffer)); std::string value(ExtractString(value_buffer)); listener_->OnHeader(name, value); if (entry_type == HpackEntryType::kIndexedLiteralHeader) { decoder_tables_.Insert(std::move(name), std::move(value)); } } void HpackDecoderState::OnDynamicTableSizeUpdate(size_t size_limit) { QUICHE_DVLOG(2) << "HpackDecoderState::OnDynamicTableSizeUpdate " << size_limit << ", required=" << (require_dynamic_table_size_update_ ? "true" : "false") << ", allowed=" << (allow_dynamic_table_size_update_ ? "true" : "false"); if (error_ != HpackDecodingError::kOk) { return; } QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_); if (!allow_dynamic_table_size_update_) { ReportError(HpackDecodingError::kDynamicTableSizeUpdateNotAllowed); return; } if (require_dynamic_table_size_update_) { if (size_limit > lowest_header_table_size_) { ReportError(HpackDecodingError:: kInitialDynamicTableSizeUpdateIsAboveLowWaterMark); return; } require_dynamic_table_size_update_ = false; } else if (size_limit > final_header_table_size_) { ReportError( HpackDecodingError::kDynamicTableSizeUpdateIsAboveAcknowledgedSetting); return; } decoder_tables_.DynamicTableSizeUpdate(size_limit); if (saw_dynamic_table_size_update_) { allow_dynamic_table_size_update_ = false; } else { saw_dynamic_table_size_update_ = true; } lowest_header_table_size_ = final_header_table_size_; } void HpackDecoderState::OnHpackDecodeError(HpackDecodingError error) { QUICHE_DVLOG(2) << "HpackDecoderState::OnHpackDecodeError " << HpackDecodingErrorToString(error); if (error_ == HpackDecodingError::kOk) { ReportError(error); } } void HpackDecoderState::OnHeaderBlockEnd() { QUICHE_DVLOG(2) << "HpackDecoderState::OnHeaderBlockEnd"; if (error_ != HpackDecodingError::kOk) { return; } if (require_dynamic_table_size_update_) { ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate); } else { listener_->OnHeaderListEnd(); } } void HpackDecoderState::ReportError(HpackDecodingError error) { QUICHE_DVLOG(2) << "HpackDecoderState::ReportError is new=" << (error_ == HpackDecodingError::kOk ? "true" : "false") << ", error: " << HpackDecodingErrorToString(error); if (error_ == HpackDecodingError::kOk) { listener_->OnHeaderErrorDetected(HpackDecodingErrorToString(error)); error_ = error; } } }
#include "quiche/http2/hpack/decoder/hpack_decoder_state.h" #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::Eq; using ::testing::Mock; using ::testing::StrictMock; namespace http2 { namespace test { class HpackDecoderStatePeer { public: static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) { return &state->decoder_tables_; } }; namespace { class MockHpackDecoderListener : public HpackDecoderListener { public: MOCK_METHOD(void, OnHeaderListStart, (), (override)); MOCK_METHOD(void, OnHeader, (absl::string_view name, absl::string_view value), (override)); MOCK_METHOD(void, OnHeaderListEnd, (), (override)); MOCK_METHOD(void, OnHeaderErrorDetected, (absl::string_view error_message), (override)); }; enum StringBacking { UNBUFFERED, BUFFERED }; class HpackDecoderStateTest : public quiche::test::QuicheTest { protected: HpackDecoderStateTest() : decoder_state_(&listener_) {} HpackDecoderTables* GetDecoderTables() { return HpackDecoderStatePeer::GetDecoderTables(&decoder_state_); } const HpackStringPair* Lookup(size_t index) { return GetDecoderTables()->Lookup(index); } size_t current_header_table_size() { return GetDecoderTables()->current_header_table_size(); } size_t header_table_size_limit() { return GetDecoderTables()->header_table_size_limit(); } void set_header_table_size_limit(size_t size) { GetDecoderTables()->DynamicTableSizeUpdate(size); } void SetStringBuffer(absl::string_view s, StringBacking backing, HpackDecoderStringBuffer* string_buffer) { string_buffer->OnStart(false, s.size()); EXPECT_TRUE(string_buffer->OnData(s.data(), s.size())); EXPECT_TRUE(string_buffer->OnEnd()); if (backing == BUFFERED) { string_buffer->BufferStringIfUnbuffered(); } } void SetName(absl::string_view s, StringBacking backing) { SetStringBuffer(s, backing, &name_buffer_); } void SetValue(absl::string_view s, StringBacking backing) { SetStringBuffer(s, backing, &value_buffer_); } void SendStartAndVerifyCallback() { EXPECT_CALL(listener_, OnHeaderListStart()); decoder_state_.OnHeaderBlockStart(); Mock::VerifyAndClearExpectations(&listener_); } void SendSizeUpdate(size_t size) { decoder_state_.OnDynamicTableSizeUpdate(size); Mock::VerifyAndClearExpectations(&listener_); } void SendIndexAndVerifyCallback(size_t index, HpackEntryType , absl::string_view expected_name, absl::string_view expected_value) { EXPECT_CALL(listener_, OnHeader(Eq(expected_name), Eq(expected_value))); decoder_state_.OnIndexedHeader(index); Mock::VerifyAndClearExpectations(&listener_); } void SendValueAndVerifyCallback(size_t name_index, HpackEntryType entry_type, absl::string_view name, absl::string_view value, StringBacking value_backing) { SetValue(value, value_backing); EXPECT_CALL(listener_, OnHeader(Eq(name), Eq(value))); decoder_state_.OnNameIndexAndLiteralValue(entry_type, name_index, &value_buffer_); Mock::VerifyAndClearExpectations(&listener_); } void SendNameAndValueAndVerifyCallback(HpackEntryType entry_type, absl::string_view name, StringBacking name_backing, absl::string_view value, StringBacking value_backing) { SetName(name, name_backing); SetValue(value, value_backing); EXPECT_CALL(listener_, OnHeader(Eq(name), Eq(value))); decoder_state_.OnLiteralNameAndValue(entry_type, &name_buffer_, &value_buffer_); Mock::VerifyAndClearExpectations(&listener_); } void SendEndAndVerifyCallback() { EXPECT_CALL(listener_, OnHeaderListEnd()); decoder_state_.OnHeaderBlockEnd(); Mock::VerifyAndClearExpectations(&listener_); } AssertionResult VerifyEntry(size_t dynamic_index, absl::string_view name, absl::string_view value) { const HpackStringPair* entry = Lookup(dynamic_index + kFirstDynamicTableIndex - 1); HTTP2_VERIFY_NE(entry, nullptr); HTTP2_VERIFY_EQ(entry->name, name); HTTP2_VERIFY_EQ(entry->value, value); return AssertionSuccess(); } AssertionResult VerifyNoEntry(size_t dynamic_index) { const HpackStringPair* entry = Lookup(dynamic_index + kFirstDynamicTableIndex - 1); HTTP2_VERIFY_EQ(entry, nullptr); return AssertionSuccess(); } AssertionResult VerifyDynamicTableContents( const std::vector<std::pair<absl::string_view, absl::string_view>>& entries) { size_t index = 1; for (const auto& entry : entries) { HTTP2_VERIFY_SUCCESS(VerifyEntry(index, entry.first, entry.second)); ++index; } HTTP2_VERIFY_SUCCESS(VerifyNoEntry(index)); return AssertionSuccess(); } StrictMock<MockHpackDecoderListener> listener_; HpackDecoderState decoder_state_; HpackDecoderStringBuffer name_buffer_, value_buffer_; }; TEST_F(HpackDecoderStateTest, C3_RequestExamples) { SendStartAndVerifyCallback(); SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, ":method", "GET"); SendIndexAndVerifyCallback(6, HpackEntryType::kIndexedHeader, ":scheme", "http"); SendIndexAndVerifyCallback(4, HpackEntryType::kIndexedHeader, ":path", "/"); SendValueAndVerifyCallback(1, HpackEntryType::kIndexedLiteralHeader, ":authority", "www.example.com", UNBUFFERED); SendEndAndVerifyCallback(); ASSERT_TRUE(VerifyDynamicTableContents({{":authority", "www.example.com"}})); ASSERT_EQ(57u, current_header_table_size()); SendStartAndVerifyCallback(); SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, ":method", "GET"); SendIndexAndVerifyCallback(6, HpackEntryType::kIndexedHeader, ":scheme", "http"); SendIndexAndVerifyCallback(4, HpackEntryType::kIndexedHeader, ":path", "/"); SendIndexAndVerifyCallback(62, HpackEntryType::kIndexedHeader, ":authority", "www.example.com"); SendValueAndVerifyCallback(24, HpackEntryType::kIndexedLiteralHeader, "cache-control", "no-cache", UNBUFFERED); SendEndAndVerifyCallback(); ASSERT_TRUE(VerifyDynamicTableContents( {{"cache-control", "no-cache"}, {":authority", "www.example.com"}})); ASSERT_EQ(110u, current_header_table_size()); SendStartAndVerifyCallback(); SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, ":method", "GET"); SendIndexAndVerifyCallback(7, HpackEntryType::kIndexedHeader, ":scheme", "https"); SendIndexAndVerifyCallback(5, HpackEntryType::kIndexedHeader, ":path", "/index.html"); SendIndexAndVerifyCallback(63, HpackEntryType::kIndexedHeader, ":authority", "www.example.com"); SendNameAndValueAndVerifyCallback(HpackEntryType::kIndexedLiteralHeader, "custom-key", UNBUFFERED, "custom-value", UNBUFFERED); SendEndAndVerifyCallback(); ASSERT_TRUE(VerifyDynamicTableContents({{"custom-key", "custom-value"}, {"cache-control", "no-cache"}, {":authority", "www.example.com"}})); ASSERT_EQ(164u, current_header_table_size()); } TEST_F(HpackDecoderStateTest, C5_ResponseExamples) { set_header_table_size_limit(256); SendStartAndVerifyCallback(); SendValueAndVerifyCallback(8, HpackEntryType::kIndexedLiteralHeader, ":status", "302", BUFFERED); SendValueAndVerifyCallback(24, HpackEntryType::kIndexedLiteralHeader, "cache-control", "private", UNBUFFERED); SendValueAndVerifyCallback(33, HpackEntryType::kIndexedLiteralHeader, "date", "Mon, 21 Oct 2013 20:13:21 GMT", UNBUFFERED); SendValueAndVerifyCallback(46, HpackEntryType::kIndexedLiteralHeader, "location", "https: SendEndAndVerifyCallback(); ASSERT_TRUE( VerifyDynamicTableContents({{"location", "https: {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"cache-control", "private"}, {":status", "302"}})); ASSERT_EQ(222u, current_header_table_size()); SendStartAndVerifyCallback(); SendValueAndVerifyCallback(8, HpackEntryType::kIndexedLiteralHeader, ":status", "307", BUFFERED); SendIndexAndVerifyCallback(65, HpackEntryType::kIndexedHeader, "cache-control", "private"); SendIndexAndVerifyCallback(64, HpackEntryType::kIndexedHeader, "date", "Mon, 21 Oct 2013 20:13:21 GMT"); SendIndexAndVerifyCallback(63, HpackEntryType::kIndexedHeader, "location", "https: SendEndAndVerifyCallback(); ASSERT_TRUE( VerifyDynamicTableContents({{":status", "307"}, {"location", "https: {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"cache-control", "private"}})); ASSERT_EQ(222u, current_header_table_size()); SendStartAndVerifyCallback(); SendIndexAndVerifyCallback(8, HpackEntryType::kIndexedHeader, ":status", "200"); SendIndexAndVerifyCallback(65, HpackEntryType::kIndexedHeader, "cache-control", "private"); SendValueAndVerifyCallback(33, HpackEntryType::kIndexedLiteralHeader, "date", "Mon, 21 Oct 2013 20:13:22 GMT", BUFFERED); SendIndexAndVerifyCallback(64, HpackEntryType::kIndexedHeader, "location", "https: SendValueAndVerifyCallback(26, HpackEntryType::kIndexedLiteralHeader, "content-encoding", "gzip", UNBUFFERED); SendValueAndVerifyCallback( 55, HpackEntryType::kIndexedLiteralHeader, "set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", BUFFERED); SendEndAndVerifyCallback(); ASSERT_TRUE(VerifyDynamicTableContents( {{"set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, {"content-encoding", "gzip"}, {"date", "Mon, 21 Oct 2013 20:13:22 GMT"}})); ASSERT_EQ(215u, current_header_table_size()); } TEST_F(HpackDecoderStateTest, OptionalTableSizeChanges) { SendStartAndVerifyCallback(); EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); SendSizeUpdate(1024); EXPECT_EQ(1024u, header_table_size_limit()); SendSizeUpdate(0); EXPECT_EQ(0u, header_table_size_limit()); EXPECT_CALL(listener_, OnHeaderErrorDetected( Eq("Dynamic table size update not allowed"))); SendSizeUpdate(0); } TEST_F(HpackDecoderStateTest, RequiredTableSizeChangeBeforeHeader) { EXPECT_EQ(4096u, decoder_state_.GetCurrentHeaderTableSizeSetting()); decoder_state_.ApplyHeaderTableSizeSetting(1024); decoder_state_.ApplyHeaderTableSizeSetting(2048); EXPECT_EQ(2048u, decoder_state_.GetCurrentHeaderTableSizeSetting()); SendStartAndVerifyCallback(); EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); SendSizeUpdate(1024); EXPECT_EQ(1024u, header_table_size_limit()); SendSizeUpdate(1500); EXPECT_EQ(1500u, header_table_size_limit()); SendEndAndVerifyCallback(); decoder_state_.ApplyHeaderTableSizeSetting(1024); EXPECT_EQ(1024u, decoder_state_.GetCurrentHeaderTableSizeSetting()); SendStartAndVerifyCallback(); EXPECT_CALL(listener_, OnHeaderErrorDetected(Eq("Missing dynamic table size update"))); decoder_state_.OnIndexedHeader(1); decoder_state_.OnIndexedHeader(1); decoder_state_.OnDynamicTableSizeUpdate(1); SetValue("value", UNBUFFERED); decoder_state_.OnNameIndexAndLiteralValue( HpackEntryType::kIndexedLiteralHeader, 4, &value_buffer_); SetName("name", UNBUFFERED); decoder_state_.OnLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, &name_buffer_, &value_buffer_); decoder_state_.OnHeaderBlockEnd(); decoder_state_.OnHpackDecodeError(HpackDecodingError::kIndexVarintError); } TEST_F(HpackDecoderStateTest, InvalidRequiredSizeUpdate) { decoder_state_.ApplyHeaderTableSizeSetting(1024); SendStartAndVerifyCallback(); EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); EXPECT_CALL( listener_, OnHeaderErrorDetected( Eq("Initial dynamic table size update is above low water mark"))); SendSizeUpdate(2048); } TEST_F(HpackDecoderStateTest, RequiredTableSizeChangeBeforeEnd) { decoder_state_.ApplyHeaderTableSizeSetting(1024); SendStartAndVerifyCallback(); EXPECT_CALL(listener_, OnHeaderErrorDetected(Eq("Missing dynamic table size update"))); decoder_state_.OnHeaderBlockEnd(); } TEST_F(HpackDecoderStateTest, InvalidOptionalSizeUpdate) { SendStartAndVerifyCallback(); EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); EXPECT_CALL(listener_, OnHeaderErrorDetected(Eq( "Dynamic table size update is above acknowledged setting"))); SendSizeUpdate(Http2SettingsInfo::DefaultHeaderTableSize() + 1); } TEST_F(HpackDecoderStateTest, InvalidStaticIndex) { SendStartAndVerifyCallback(); EXPECT_CALL(listener_, OnHeaderErrorDetected( Eq("Invalid index in indexed header field representation"))); decoder_state_.OnIndexedHeader(0); } TEST_F(HpackDecoderStateTest, InvalidDynamicIndex) { SendStartAndVerifyCallback(); EXPECT_CALL(listener_, OnHeaderErrorDetected( Eq("Invalid index in indexed header field representation"))); decoder_state_.OnIndexedHeader(kFirstDynamicTableIndex); } TEST_F(HpackDecoderStateTest, InvalidNameIndex) { SendStartAndVerifyCallback(); EXPECT_CALL(listener_, OnHeaderErrorDetected(Eq("Invalid index in literal header field " "with indexed name representation"))); SetValue("value", UNBUFFERED); decoder_state_.OnNameIndexAndLiteralValue( HpackEntryType::kIndexedLiteralHeader, kFirstDynamicTableIndex, &value_buffer_); } TEST_F(HpackDecoderStateTest, ErrorsSuppressCallbacks) { SendStartAndVerifyCallback(); EXPECT_CALL(listener_, OnHeaderErrorDetected(Eq("Name Huffman encoding error"))); decoder_state_.OnHpackDecodeError(HpackDecodingError::kNameHuffmanError); decoder_state_.OnIndexedHeader(1); decoder_state_.OnDynamicTableSizeUpdate(1); SetValue("value", UNBUFFERED); decoder_state_.OnNameIndexAndLiteralValue( HpackEntryType::kIndexedLiteralHeader, 4, &value_buffer_); SetName("name", UNBUFFERED); decoder_state_.OnLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, &name_buffer_, &value_buffer_); decoder_state_.OnHeaderBlockEnd(); decoder_state_.OnHpackDecodeError(HpackDecodingError::kIndexVarintError); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_state.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_state_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
eebdf9b7-6617-46ed-9659-7b074107777a
cpp
google/quiche
hpack_whole_entry_buffer
quiche/http2/hpack/decoder/hpack_whole_entry_buffer.cc
quiche/http2/hpack/decoder/hpack_whole_entry_buffer_test.cc
#include "quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h" #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_text_utils.h" namespace http2 { HpackWholeEntryBuffer::HpackWholeEntryBuffer(HpackWholeEntryListener* listener, size_t max_string_size_bytes) : max_string_size_bytes_(max_string_size_bytes) { set_listener(listener); } HpackWholeEntryBuffer::~HpackWholeEntryBuffer() = default; void HpackWholeEntryBuffer::set_listener(HpackWholeEntryListener* listener) { QUICHE_CHECK(listener); listener_ = listener; } void HpackWholeEntryBuffer::set_max_string_size_bytes( size_t max_string_size_bytes) { max_string_size_bytes_ = max_string_size_bytes; } void HpackWholeEntryBuffer::BufferStringsIfUnbuffered() { name_.BufferStringIfUnbuffered(); value_.BufferStringIfUnbuffered(); } void HpackWholeEntryBuffer::OnIndexedHeader(size_t index) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnIndexedHeader: index=" << index; listener_->OnIndexedHeader(index); } void HpackWholeEntryBuffer::OnStartLiteralHeader(HpackEntryType entry_type, size_t maybe_name_index) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnStartLiteralHeader: entry_type=" << entry_type << ", maybe_name_index=" << maybe_name_index; entry_type_ = entry_type; maybe_name_index_ = maybe_name_index; } void HpackWholeEntryBuffer::OnNameStart(bool huffman_encoded, size_t len) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnNameStart: huffman_encoded=" << (huffman_encoded ? "true" : "false") << ", len=" << len; QUICHE_DCHECK_EQ(maybe_name_index_, 0u); if (!error_detected_) { if (len > max_string_size_bytes_) { QUICHE_DVLOG(1) << "Name length (" << len << ") is longer than permitted (" << max_string_size_bytes_ << ")"; ReportError(HpackDecodingError::kNameTooLong); QUICHE_CODE_COUNT_N(decompress_failure_3, 18, 23); return; } name_.OnStart(huffman_encoded, len); } } void HpackWholeEntryBuffer::OnNameData(const char* data, size_t len) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnNameData: len=" << len << " data:\n" << quiche::QuicheTextUtils::HexDump( absl::string_view(data, len)); QUICHE_DCHECK_EQ(maybe_name_index_, 0u); if (!error_detected_ && !name_.OnData(data, len)) { ReportError(HpackDecodingError::kNameHuffmanError); QUICHE_CODE_COUNT_N(decompress_failure_3, 19, 23); } } void HpackWholeEntryBuffer::OnNameEnd() { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnNameEnd"; QUICHE_DCHECK_EQ(maybe_name_index_, 0u); if (!error_detected_ && !name_.OnEnd()) { ReportError(HpackDecodingError::kNameHuffmanError); QUICHE_CODE_COUNT_N(decompress_failure_3, 20, 23); } } void HpackWholeEntryBuffer::OnValueStart(bool huffman_encoded, size_t len) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnValueStart: huffman_encoded=" << (huffman_encoded ? "true" : "false") << ", len=" << len; if (!error_detected_) { if (len > max_string_size_bytes_) { QUICHE_DVLOG(1) << "Value length (" << len << ") of [" << name_.GetStringIfComplete() << "] is longer than permitted (" << max_string_size_bytes_ << ")"; ReportError(HpackDecodingError::kValueTooLong); QUICHE_CODE_COUNT_N(decompress_failure_3, 21, 23); return; } value_.OnStart(huffman_encoded, len); } } void HpackWholeEntryBuffer::OnValueData(const char* data, size_t len) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnValueData: len=" << len << " data:\n" << quiche::QuicheTextUtils::HexDump( absl::string_view(data, len)); if (!error_detected_ && !value_.OnData(data, len)) { ReportError(HpackDecodingError::kValueHuffmanError); QUICHE_CODE_COUNT_N(decompress_failure_3, 22, 23); } } void HpackWholeEntryBuffer::OnValueEnd() { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnValueEnd"; if (error_detected_) { return; } if (!value_.OnEnd()) { ReportError(HpackDecodingError::kValueHuffmanError); QUICHE_CODE_COUNT_N(decompress_failure_3, 23, 23); return; } if (maybe_name_index_ == 0) { listener_->OnLiteralNameAndValue(entry_type_, &name_, &value_); name_.Reset(); } else { listener_->OnNameIndexAndLiteralValue(entry_type_, maybe_name_index_, &value_); } value_.Reset(); } void HpackWholeEntryBuffer::OnDynamicTableSizeUpdate(size_t size) { QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnDynamicTableSizeUpdate: size=" << size; listener_->OnDynamicTableSizeUpdate(size); } void HpackWholeEntryBuffer::ReportError(HpackDecodingError error) { if (!error_detected_) { QUICHE_DVLOG(1) << "HpackWholeEntryBuffer::ReportError: " << HpackDecodingErrorToString(error); error_detected_ = true; listener_->OnHpackDecodeError(error); listener_ = HpackWholeEntryNoOpListener::NoOpListener(); } } }
#include "quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::_; using ::testing::AllOf; using ::testing::InSequence; using ::testing::Property; using ::testing::StrictMock; namespace http2 { namespace test { namespace { constexpr size_t kMaxStringSize = 20; class MockHpackWholeEntryListener : public HpackWholeEntryListener { public: ~MockHpackWholeEntryListener() override = default; MOCK_METHOD(void, OnIndexedHeader, (size_t index), (override)); MOCK_METHOD(void, OnNameIndexAndLiteralValue, (HpackEntryType entry_type, size_t name_index, HpackDecoderStringBuffer* value_buffer), (override)); MOCK_METHOD(void, OnLiteralNameAndValue, (HpackEntryType entry_type, HpackDecoderStringBuffer* name_buffer, HpackDecoderStringBuffer* value_buffer), (override)); MOCK_METHOD(void, OnDynamicTableSizeUpdate, (size_t size), (override)); MOCK_METHOD(void, OnHpackDecodeError, (HpackDecodingError error), (override)); }; class HpackWholeEntryBufferTest : public quiche::test::QuicheTest { protected: HpackWholeEntryBufferTest() : entry_buffer_(&listener_, kMaxStringSize) {} ~HpackWholeEntryBufferTest() override = default; StrictMock<MockHpackWholeEntryListener> listener_; HpackWholeEntryBuffer entry_buffer_; }; TEST_F(HpackWholeEntryBufferTest, OnIndexedHeader) { { InSequence seq; EXPECT_CALL(listener_, OnIndexedHeader(17)); entry_buffer_.OnIndexedHeader(17); } { InSequence seq; EXPECT_CALL(listener_, OnIndexedHeader(62)); entry_buffer_.OnIndexedHeader(62); } { InSequence seq; EXPECT_CALL(listener_, OnIndexedHeader(62)); entry_buffer_.OnIndexedHeader(62); } { InSequence seq; EXPECT_CALL(listener_, OnIndexedHeader(128)); entry_buffer_.OnIndexedHeader(128); } StrictMock<MockHpackWholeEntryListener> listener2; entry_buffer_.set_listener(&listener2); { InSequence seq; EXPECT_CALL(listener2, OnIndexedHeader(100)); entry_buffer_.OnIndexedHeader(100); } } TEST_F(HpackWholeEntryBufferTest, OnDynamicTableSizeUpdate) { { InSequence seq; EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(4096)); entry_buffer_.OnDynamicTableSizeUpdate(4096); } { InSequence seq; EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(0)); entry_buffer_.OnDynamicTableSizeUpdate(0); } { InSequence seq; EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(1024)); entry_buffer_.OnDynamicTableSizeUpdate(1024); } { InSequence seq; EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(1024)); entry_buffer_.OnDynamicTableSizeUpdate(1024); } StrictMock<MockHpackWholeEntryListener> listener2; entry_buffer_.set_listener(&listener2); { InSequence seq; EXPECT_CALL(listener2, OnDynamicTableSizeUpdate(0)); entry_buffer_.OnDynamicTableSizeUpdate(0); } } TEST_F(HpackWholeEntryBufferTest, OnNameIndexAndLiteralValue) { entry_buffer_.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader, 123); entry_buffer_.OnValueStart(false, 10); entry_buffer_.OnValueData("some data.", 10); entry_buffer_.BufferStringsIfUnbuffered(); EXPECT_CALL( listener_, OnNameIndexAndLiteralValue( HpackEntryType::kNeverIndexedLiteralHeader, 123, AllOf(Property(&HpackDecoderStringBuffer::str, "some data."), Property(&HpackDecoderStringBuffer::BufferedLength, 10)))); entry_buffer_.OnValueEnd(); } TEST_F(HpackWholeEntryBufferTest, OnLiteralNameAndValue) { entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0); entry_buffer_.OnNameStart(false, 9); entry_buffer_.OnNameData("some-", 5); entry_buffer_.OnNameData("name", 4); entry_buffer_.OnNameEnd(); entry_buffer_.OnValueStart(false, 12); entry_buffer_.OnValueData("Header Value", 12); EXPECT_CALL( listener_, OnLiteralNameAndValue( HpackEntryType::kIndexedLiteralHeader, AllOf(Property(&HpackDecoderStringBuffer::str, "some-name"), Property(&HpackDecoderStringBuffer::BufferedLength, 9)), AllOf(Property(&HpackDecoderStringBuffer::str, "Header Value"), Property(&HpackDecoderStringBuffer::BufferedLength, 0)))); entry_buffer_.OnValueEnd(); } TEST_F(HpackWholeEntryBufferTest, NameTooLong) { entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0); EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kNameTooLong)); entry_buffer_.OnNameStart(false, kMaxStringSize + 1); } TEST_F(HpackWholeEntryBufferTest, ValueTooLong) { entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0); EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueTooLong)); entry_buffer_.OnNameStart(false, 4); entry_buffer_.OnNameData("path", 4); entry_buffer_.OnNameEnd(); entry_buffer_.OnValueStart(false, kMaxStringSize + 1); } TEST_F(HpackWholeEntryBufferTest, ValueTooLongWithoutName) { entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1); EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueTooLong)); entry_buffer_.OnValueStart(false, kMaxStringSize + 1); } TEST_F(HpackWholeEntryBufferTest, NameHuffmanError) { const char data[] = "\xff\xff\xff"; entry_buffer_.OnStartLiteralHeader(HpackEntryType::kUnindexedLiteralHeader, 0); entry_buffer_.OnNameStart(true, 4); entry_buffer_.OnNameData(data, 3); EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kNameHuffmanError)); entry_buffer_.OnNameData(data, 1); EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(8096)).Times(0); entry_buffer_.OnDynamicTableSizeUpdate(8096); } TEST_F(HpackWholeEntryBufferTest, ValueHuffmanError) { const char data[] = "\x00\x00\x00"; entry_buffer_.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader, 61); entry_buffer_.OnValueStart(true, 3); entry_buffer_.OnValueData(data, 3); EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueHuffmanError)); entry_buffer_.OnValueEnd(); EXPECT_CALL(listener_, OnIndexedHeader(17)).Times(0); entry_buffer_.OnIndexedHeader(17); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_whole_entry_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_whole_entry_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
54b89a8b-1450-4244-8eb6-f5d3b0bf5712
cpp
google/quiche
hpack_decoder
quiche/http2/hpack/decoder/hpack_decoder.cc
quiche/http2/hpack/decoder/hpack_decoder_test.cc
#include "quiche/http2/hpack/decoder/hpack_decoder.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { HpackDecoder::HpackDecoder(HpackDecoderListener* listener, size_t max_string_size) : decoder_state_(listener), entry_buffer_(&decoder_state_, max_string_size), block_decoder_(&entry_buffer_), error_(HpackDecodingError::kOk) {} HpackDecoder::~HpackDecoder() = default; void HpackDecoder::set_max_string_size_bytes(size_t max_string_size_bytes) { entry_buffer_.set_max_string_size_bytes(max_string_size_bytes); } void HpackDecoder::ApplyHeaderTableSizeSetting(uint32_t max_header_table_size) { decoder_state_.ApplyHeaderTableSizeSetting(max_header_table_size); } bool HpackDecoder::StartDecodingBlock() { QUICHE_DVLOG(3) << "HpackDecoder::StartDecodingBlock, error_detected=" << (DetectError() ? "true" : "false"); if (DetectError()) { return false; } block_decoder_.Reset(); decoder_state_.OnHeaderBlockStart(); return true; } bool HpackDecoder::DecodeFragment(DecodeBuffer* db) { QUICHE_DVLOG(3) << "HpackDecoder::DecodeFragment, error_detected=" << (DetectError() ? "true" : "false") << ", size=" << db->Remaining(); if (DetectError()) { QUICHE_CODE_COUNT_N(decompress_failure_3, 3, 23); return false; } DecodeStatus status = block_decoder_.Decode(db); if (status == DecodeStatus::kDecodeError) { ReportError(block_decoder_.error()); QUICHE_CODE_COUNT_N(decompress_failure_3, 4, 23); return false; } else if (DetectError()) { QUICHE_CODE_COUNT_N(decompress_failure_3, 5, 23); return false; } QUICHE_DCHECK_EQ(block_decoder_.before_entry(), status == DecodeStatus::kDecodeDone) << status; if (!block_decoder_.before_entry()) { entry_buffer_.BufferStringsIfUnbuffered(); } return true; } bool HpackDecoder::EndDecodingBlock() { QUICHE_DVLOG(3) << "HpackDecoder::EndDecodingBlock, error_detected=" << (DetectError() ? "true" : "false"); if (DetectError()) { QUICHE_CODE_COUNT_N(decompress_failure_3, 6, 23); return false; } if (!block_decoder_.before_entry()) { ReportError(HpackDecodingError::kTruncatedBlock); QUICHE_CODE_COUNT_N(decompress_failure_3, 7, 23); return false; } decoder_state_.OnHeaderBlockEnd(); if (DetectError()) { QUICHE_CODE_COUNT_N(decompress_failure_3, 8, 23); return false; } return true; } bool HpackDecoder::DetectError() { if (error_ != HpackDecodingError::kOk) { return true; } if (decoder_state_.error() != HpackDecodingError::kOk) { QUICHE_DVLOG(2) << "Error detected in decoder_state_"; QUICHE_CODE_COUNT_N(decompress_failure_3, 10, 23); error_ = decoder_state_.error(); } return error_ != HpackDecodingError::kOk; } void HpackDecoder::ReportError(HpackDecodingError error) { QUICHE_DVLOG(3) << "HpackDecoder::ReportError is new=" << (error_ == HpackDecodingError::kOk ? "true" : "false") << ", error: " << HpackDecodingErrorToString(error); if (error_ == HpackDecodingError::kOk) { error_ = error; decoder_state_.listener()->OnHeaderErrorDetected( HpackDecodingErrorToString(error)); } } }
#include "quiche/http2/hpack/decoder/hpack_decoder.h" #include <string> #include <tuple> #include <utility> #include <vector> #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/hpack/decoder/hpack_decoder_listener.h" #include "quiche/http2/hpack/decoder/hpack_decoder_state.h" #include "quiche/http2/hpack/decoder/hpack_decoder_tables.h" #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/test_tools/hpack_example.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/random_util.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::ElementsAreArray; using ::testing::Eq; namespace http2 { namespace test { class HpackDecoderStatePeer { public: static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) { return &state->decoder_tables_; } static void set_listener(HpackDecoderState* state, HpackDecoderListener* listener) { state->listener_ = listener; } }; class HpackDecoderPeer { public: static HpackDecoderState* GetDecoderState(HpackDecoder* decoder) { return &decoder->decoder_state_; } static HpackDecoderTables* GetDecoderTables(HpackDecoder* decoder) { return HpackDecoderStatePeer::GetDecoderTables(GetDecoderState(decoder)); } }; namespace { typedef std::pair<std::string, std::string> HpackHeaderEntry; typedef std::vector<HpackHeaderEntry> HpackHeaderEntries; class MockHpackDecoderListener : public HpackDecoderListener { public: MOCK_METHOD(void, OnHeaderListStart, (), (override)); MOCK_METHOD(void, OnHeader, (absl::string_view name, absl::string_view value), (override)); MOCK_METHOD(void, OnHeaderListEnd, (), (override)); MOCK_METHOD(void, OnHeaderErrorDetected, (absl::string_view error_message), (override)); }; class HpackDecoderTest : public quiche::test::QuicheTestWithParam<bool>, public HpackDecoderListener { protected: HpackDecoderTest() : decoder_(this, 4096) { fragment_the_hpack_block_ = GetParam(); } ~HpackDecoderTest() override = default; void OnHeaderListStart() override { ASSERT_FALSE(saw_start_); ASSERT_FALSE(saw_end_); saw_start_ = true; header_entries_.clear(); } void OnHeader(absl::string_view name, absl::string_view value) override { ASSERT_TRUE(saw_start_); ASSERT_FALSE(saw_end_); header_entries_.emplace_back(name, value); } void OnHeaderListEnd() override { ASSERT_TRUE(saw_start_); ASSERT_FALSE(saw_end_); ASSERT_TRUE(error_messages_.empty()); saw_end_ = true; } void OnHeaderErrorDetected(absl::string_view error_message) override { ASSERT_TRUE(saw_start_); error_messages_.push_back(std::string(error_message)); HpackDecoderStatePeer::set_listener( HpackDecoderPeer::GetDecoderState(&decoder_), &mock_listener_); } AssertionResult DecodeBlock(absl::string_view block) { QUICHE_VLOG(1) << "HpackDecoderTest::DecodeBlock"; HTTP2_VERIFY_FALSE(decoder_.DetectError()); HTTP2_VERIFY_TRUE(error_messages_.empty()); HTTP2_VERIFY_FALSE(saw_start_); HTTP2_VERIFY_FALSE(saw_end_); header_entries_.clear(); HTTP2_VERIFY_FALSE(decoder_.DetectError()); HTTP2_VERIFY_TRUE(decoder_.StartDecodingBlock()); HTTP2_VERIFY_FALSE(decoder_.DetectError()); if (fragment_the_hpack_block_) { while (!block.empty()) { size_t fragment_size = random_.RandomSizeSkewedLow(block.size()); DecodeBuffer db(block.substr(0, fragment_size)); HTTP2_VERIFY_TRUE(decoder_.DecodeFragment(&db)); HTTP2_VERIFY_EQ(0u, db.Remaining()); block.remove_prefix(fragment_size); } } else { DecodeBuffer db(block); HTTP2_VERIFY_TRUE(decoder_.DecodeFragment(&db)); HTTP2_VERIFY_EQ(0u, db.Remaining()); } HTTP2_VERIFY_FALSE(decoder_.DetectError()); HTTP2_VERIFY_TRUE(decoder_.EndDecodingBlock()); if (saw_end_) { HTTP2_VERIFY_FALSE(decoder_.DetectError()); HTTP2_VERIFY_TRUE(error_messages_.empty()); } else { HTTP2_VERIFY_TRUE(decoder_.DetectError()); HTTP2_VERIFY_FALSE(error_messages_.empty()); } saw_start_ = saw_end_ = false; return AssertionSuccess(); } const HpackDecoderTables& GetDecoderTables() { return *HpackDecoderPeer::GetDecoderTables(&decoder_); } const HpackStringPair* Lookup(size_t index) { return GetDecoderTables().Lookup(index); } size_t current_header_table_size() { return GetDecoderTables().current_header_table_size(); } size_t header_table_size_limit() { return GetDecoderTables().header_table_size_limit(); } void set_header_table_size_limit(size_t size) { HpackDecoderPeer::GetDecoderTables(&decoder_)->DynamicTableSizeUpdate(size); } AssertionResult VerifyEntry(size_t dynamic_index, const char* name, const char* value) { const HpackStringPair* entry = Lookup(dynamic_index + kFirstDynamicTableIndex - 1); HTTP2_VERIFY_NE(entry, nullptr); HTTP2_VERIFY_EQ(entry->name, name); HTTP2_VERIFY_EQ(entry->value, value); return AssertionSuccess(); } AssertionResult VerifyNoEntry(size_t dynamic_index) { const HpackStringPair* entry = Lookup(dynamic_index + kFirstDynamicTableIndex - 1); HTTP2_VERIFY_EQ(entry, nullptr); return AssertionSuccess(); } AssertionResult VerifyDynamicTableContents( const std::vector<std::pair<const char*, const char*>>& entries) { size_t index = 1; for (const auto& entry : entries) { HTTP2_VERIFY_SUCCESS(VerifyEntry(index, entry.first, entry.second)); ++index; } HTTP2_VERIFY_SUCCESS(VerifyNoEntry(index)); return AssertionSuccess(); } Http2Random random_; HpackDecoder decoder_; testing::StrictMock<MockHpackDecoderListener> mock_listener_; HpackHeaderEntries header_entries_; std::vector<std::string> error_messages_; bool fragment_the_hpack_block_; bool saw_start_ = false; bool saw_end_ = false; }; INSTANTIATE_TEST_SUITE_P(AllWays, HpackDecoderTest, ::testing::Bool()); TEST_P(HpackDecoderTest, C3_RequestExamples) { std::string hpack_block = HpackExampleToStringOrDie(R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 86 | == Indexed - Add == | idx = 6 | -> :scheme: http 84 | == Indexed - Add == | idx = 4 | -> :path: / 41 | == Literal indexed == | Indexed name (idx = 1) | :authority 0f | Literal value (len = 15) 7777 772e 6578 616d 706c 652e 636f 6d | www.example.com | -> :authority: | www.example.com )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":method", "GET"}, HpackHeaderEntry{":scheme", "http"}, HpackHeaderEntry{":path", "/"}, HpackHeaderEntry{":authority", "www.example.com"}, })); ASSERT_TRUE(VerifyDynamicTableContents({{":authority", "www.example.com"}})); ASSERT_EQ(57u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 86 | == Indexed - Add == | idx = 6 | -> :scheme: http 84 | == Indexed - Add == | idx = 4 | -> :path: / be | == Indexed - Add == | idx = 62 | -> :authority: | www.example.com 58 | == Literal indexed == | Indexed name (idx = 24) | cache-control 08 | Literal value (len = 8) 6e6f 2d63 6163 6865 | no-cache | -> cache-control: no-cache )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":method", "GET"}, HpackHeaderEntry{":scheme", "http"}, HpackHeaderEntry{":path", "/"}, HpackHeaderEntry{":authority", "www.example.com"}, HpackHeaderEntry{"cache-control", "no-cache"}, })); ASSERT_TRUE(VerifyDynamicTableContents( {{"cache-control", "no-cache"}, {":authority", "www.example.com"}})); ASSERT_EQ(110u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 87 | == Indexed - Add == | idx = 7 | -> :scheme: https 85 | == Indexed - Add == | idx = 5 | -> :path: /index.html bf | == Indexed - Add == | idx = 63 | -> :authority: | www.example.com 40 | == Literal indexed == 0a | Literal name (len = 10) 6375 7374 6f6d 2d6b 6579 | custom-key 0c | Literal value (len = 12) 6375 7374 6f6d 2d76 616c 7565 | custom-value | -> custom-key: | custom-value )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":method", "GET"}, HpackHeaderEntry{":scheme", "https"}, HpackHeaderEntry{":path", "/index.html"}, HpackHeaderEntry{":authority", "www.example.com"}, HpackHeaderEntry{"custom-key", "custom-value"}, })); ASSERT_TRUE(VerifyDynamicTableContents({{"custom-key", "custom-value"}, {"cache-control", "no-cache"}, {":authority", "www.example.com"}})); ASSERT_EQ(164u, current_header_table_size()); } TEST_P(HpackDecoderTest, C4_RequestExamplesWithHuffmanEncoding) { std::string hpack_block = HpackExampleToStringOrDie(R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 86 | == Indexed - Add == | idx = 6 | -> :scheme: http 84 | == Indexed - Add == | idx = 4 | -> :path: / 41 | == Literal indexed == | Indexed name (idx = 1) | :authority 8c | Literal value (len = 12) | Huffman encoded: f1e3 c2e5 f23a 6ba0 ab90 f4ff | .....:k..... | Decoded: | www.example.com | -> :authority: | www.example.com )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":method", "GET"}, HpackHeaderEntry{":scheme", "http"}, HpackHeaderEntry{":path", "/"}, HpackHeaderEntry{":authority", "www.example.com"}, })); ASSERT_TRUE(VerifyDynamicTableContents({{":authority", "www.example.com"}})); ASSERT_EQ(57u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 86 | == Indexed - Add == | idx = 6 | -> :scheme: http 84 | == Indexed - Add == | idx = 4 | -> :path: / be | == Indexed - Add == | idx = 62 | -> :authority: | www.example.com 58 | == Literal indexed == | Indexed name (idx = 24) | cache-control 86 | Literal value (len = 6) | Huffman encoded: a8eb 1064 9cbf | ...d.. | Decoded: | no-cache | -> cache-control: no-cache )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":method", "GET"}, HpackHeaderEntry{":scheme", "http"}, HpackHeaderEntry{":path", "/"}, HpackHeaderEntry{":authority", "www.example.com"}, HpackHeaderEntry{"cache-control", "no-cache"}, })); ASSERT_TRUE(VerifyDynamicTableContents( {{"cache-control", "no-cache"}, {":authority", "www.example.com"}})); ASSERT_EQ(110u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 87 | == Indexed - Add == | idx = 7 | -> :scheme: https 85 | == Indexed - Add == | idx = 5 | -> :path: /index.html bf | == Indexed - Add == | idx = 63 | -> :authority: | www.example.com 40 | == Literal indexed == 88 | Literal name (len = 8) | Huffman encoded: 25a8 49e9 5ba9 7d7f | %.I.[.}. | Decoded: | custom-key 89 | Literal value (len = 9) | Huffman encoded: 25a8 49e9 5bb8 e8b4 bf | %.I.[.... | Decoded: | custom-value | -> custom-key: | custom-value )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":method", "GET"}, HpackHeaderEntry{":scheme", "https"}, HpackHeaderEntry{":path", "/index.html"}, HpackHeaderEntry{":authority", "www.example.com"}, HpackHeaderEntry{"custom-key", "custom-value"}, })); ASSERT_TRUE(VerifyDynamicTableContents({{"custom-key", "custom-value"}, {"cache-control", "no-cache"}, {":authority", "www.example.com"}})); ASSERT_EQ(164u, current_header_table_size()); } TEST_P(HpackDecoderTest, C5_ResponseExamples) { set_header_table_size_limit(256); std::string hpack_block = HpackExampleToStringOrDie(R"( 48 | == Literal indexed == | Indexed name (idx = 8) | :status 03 | Literal value (len = 3) 3330 32 | 302 | -> :status: 302 58 | == Literal indexed == | Indexed name (idx = 24) | cache-control 07 | Literal value (len = 7) 7072 6976 6174 65 | private | -> cache-control: private 61 | == Literal indexed == | Indexed name (idx = 33) | date 1d | Literal value (len = 29) 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013 2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT | -> date: Mon, 21 Oct 2013 | 20:13:21 GMT 6e | == Literal indexed == | Indexed name (idx = 46) | location 17 | Literal value (len = 23) 6874 7470 733a 2f2f 7777 772e 6578 616d | https: 706c 652e 636f 6d | ple.com | -> location: | https: )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":status", "302"}, HpackHeaderEntry{"cache-control", "private"}, HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, HpackHeaderEntry{"location", "https: })); ASSERT_TRUE( VerifyDynamicTableContents({{"location", "https: {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"cache-control", "private"}, {":status", "302"}})); ASSERT_EQ(222u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 48 | == Literal indexed == | Indexed name (idx = 8) | :status 03 | Literal value (len = 3) 3330 37 | 307 | - evict: :status: 302 | -> :status: 307 c1 | == Indexed - Add == | idx = 65 | -> cache-control: private c0 | == Indexed - Add == | idx = 64 | -> date: Mon, 21 Oct 2013 | 20:13:21 GMT bf | == Indexed - Add == | idx = 63 | -> location: | https: )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":status", "307"}, HpackHeaderEntry{"cache-control", "private"}, HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, HpackHeaderEntry{"location", "https: })); ASSERT_TRUE( VerifyDynamicTableContents({{":status", "307"}, {"location", "https: {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"cache-control", "private"}})); ASSERT_EQ(222u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 88 | == Indexed - Add == | idx = 8 | -> :status: 200 c1 | == Indexed - Add == | idx = 65 | -> cache-control: private 61 | == Literal indexed == | Indexed name (idx = 33) | date 1d | Literal value (len = 29) 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013 2032 303a 3133 3a32 3220 474d 54 | 20:13:22 GMT | - evict: cache-control: | private | -> date: Mon, 21 Oct 2013 | 20:13:22 GMT c0 | == Indexed - Add == | idx = 64 | -> location: | https: 5a | == Literal indexed == | Indexed name (idx = 26) | content-encoding 04 | Literal value (len = 4) 677a 6970 | gzip | - evict: date: Mon, 21 Oct | 2013 20:13:21 GMT | -> content-encoding: gzip 77 | == Literal indexed == | Indexed name (idx = 55) | set-cookie 38 | Literal value (len = 56) 666f 6f3d 4153 444a 4b48 514b 425a 584f | foo=ASDJKHQKBZXO 5157 454f 5049 5541 5851 5745 4f49 553b | QWEOPIUAXQWEOIU; 206d 6178 2d61 6765 3d33 3630 303b 2076 | max-age=3600; v 6572 7369 6f6e 3d31 | ersion=1 | - evict: location: | https: | - evict: :status: 307 | -> set-cookie: foo=ASDJKHQ | KBZXOQWEOPIUAXQWEOIU; ma | x-age=3600; version=1 )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT( header_entries_, ElementsAreArray({ HpackHeaderEntry{":status", "200"}, HpackHeaderEntry{"cache-control", "private"}, HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:22 GMT"}, HpackHeaderEntry{"location", "https: HpackHeaderEntry{"content-encoding", "gzip"}, HpackHeaderEntry{ "set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, })); ASSERT_TRUE(VerifyDynamicTableContents( {{"set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, {"content-encoding", "gzip"}, {"date", "Mon, 21 Oct 2013 20:13:22 GMT"}})); ASSERT_EQ(215u, current_header_table_size()); } TEST_P(HpackDecoderTest, C6_ResponseExamplesWithHuffmanEncoding) { set_header_table_size_limit(256); std::string hpack_block = HpackExampleToStringOrDie(R"( 48 | == Literal indexed == | Indexed name (idx = 8) | :status 03 | Literal value (len = 3) 3330 32 | 302 | -> :status: 302 58 | == Literal indexed == | Indexed name (idx = 24) | cache-control 07 | Literal value (len = 7) 7072 6976 6174 65 | private | -> cache-control: private 61 | == Literal indexed == | Indexed name (idx = 33) | date 1d | Literal value (len = 29) 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013 2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT | -> date: Mon, 21 Oct 2013 | 20:13:21 GMT 6e | == Literal indexed == | Indexed name (idx = 46) | location 17 | Literal value (len = 23) 6874 7470 733a 2f2f 7777 772e 6578 616d | https: 706c 652e 636f 6d | ple.com | -> location: | https: )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":status", "302"}, HpackHeaderEntry{"cache-control", "private"}, HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, HpackHeaderEntry{"location", "https: })); ASSERT_TRUE( VerifyDynamicTableContents({{"location", "https: {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"cache-control", "private"}, {":status", "302"}})); ASSERT_EQ(222u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 48 | == Literal indexed == | Indexed name (idx = 8) | :status 03 | Literal value (len = 3) 3330 37 | 307 | - evict: :status: 302 | -> :status: 307 c1 | == Indexed - Add == | idx = 65 | -> cache-control: private c0 | == Indexed - Add == | idx = 64 | -> date: Mon, 21 Oct 2013 | 20:13:21 GMT bf | == Indexed - Add == | idx = 63 | -> location: | https: )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT(header_entries_, ElementsAreArray({ HpackHeaderEntry{":status", "307"}, HpackHeaderEntry{"cache-control", "private"}, HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, HpackHeaderEntry{"location", "https: })); ASSERT_TRUE( VerifyDynamicTableContents({{":status", "307"}, {"location", "https: {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"cache-control", "private"}})); ASSERT_EQ(222u, current_header_table_size()); hpack_block = HpackExampleToStringOrDie(R"( 88 | == Indexed - Add == | idx = 8 | -> :status: 200 c1 | == Indexed - Add == | idx = 65 | -> cache-control: private 61 | == Literal indexed == | Indexed name (idx = 33) | date 1d | Literal value (len = 29) 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013 2032 303a 3133 3a32 3220 474d 54 | 20:13:22 GMT | - evict: cache-control: | private | -> date: Mon, 21 Oct 2013 | 20:13:22 GMT c0 | == Indexed - Add == | idx = 64 | -> location: | https: 5a | == Literal indexed == | Indexed name (idx = 26) | content-encoding 04 | Literal value (len = 4) 677a 6970 | gzip | - evict: date: Mon, 21 Oct | 2013 20:13:21 GMT | -> content-encoding: gzip 77 | == Literal indexed == | Indexed name (idx = 55) | set-cookie 38 | Literal value (len = 56) 666f 6f3d 4153 444a 4b48 514b 425a 584f | foo=ASDJKHQKBZXO 5157 454f 5049 5541 5851 5745 4f49 553b | QWEOPIUAXQWEOIU; 206d 6178 2d61 6765 3d33 3630 303b 2076 | max-age=3600; v 6572 7369 6f6e 3d31 | ersion=1 | - evict: location: | https: | - evict: :status: 307 | -> set-cookie: foo=ASDJKHQ | KBZXOQWEOPIUAXQWEOIU; ma | x-age=3600; version=1 )"); EXPECT_TRUE(DecodeBlock(hpack_block)); ASSERT_THAT( header_entries_, ElementsAreArray({ HpackHeaderEntry{":status", "200"}, HpackHeaderEntry{"cache-control", "private"}, HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:22 GMT"}, HpackHeaderEntry{"location", "https: HpackHeaderEntry{"content-encoding", "gzip"}, HpackHeaderEntry{ "set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, })); ASSERT_TRUE(VerifyDynamicTableContents( {{"set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, {"content-encoding", "gzip"}, {"date", "Mon, 21 Oct 2013 20:13:22 GMT"}})); ASSERT_EQ(215u, current_header_table_size()); } TEST_P(HpackDecoderTest, ProcessesOptionalTableSizeUpdates) { EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(3000); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_EQ(3000u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); EXPECT_TRUE(header_entries_.empty()); } { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(2000); hbb.AppendDynamicTableSizeUpdate(2500); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_EQ(2500u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); EXPECT_TRUE(header_entries_.empty()); } { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(1500); hbb.AppendDynamicTableSizeUpdate(1000); hbb.AppendDynamicTableSizeUpdate(500); EXPECT_FALSE(DecodeBlock(hbb.buffer())); EXPECT_EQ(HpackDecodingError::kDynamicTableSizeUpdateNotAllowed, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Dynamic table size update not allowed")); EXPECT_EQ(1000u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); EXPECT_TRUE(header_entries_.empty()); } DecodeBuffer db("\x80"); EXPECT_FALSE(decoder_.DecodeFragment(&db)); EXPECT_EQ(0u, db.Offset()); EXPECT_EQ(1u, error_messages_.size()); } TEST_P(HpackDecoderTest, ProcessesRequiredTableSizeUpdate) { EXPECT_EQ(4096u, decoder_.GetCurrentHeaderTableSizeSetting()); decoder_.ApplyHeaderTableSizeSetting(1024); decoder_.ApplyHeaderTableSizeSetting(2048); EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); EXPECT_EQ(2048u, decoder_.GetCurrentHeaderTableSizeSetting()); { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(1024); hbb.AppendIndexedHeader(4); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_THAT(header_entries_, ElementsAreArray({HpackHeaderEntry{":path", "/"}})); EXPECT_EQ(1024u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); } decoder_.ApplyHeaderTableSizeSetting(1000); decoder_.ApplyHeaderTableSizeSetting(1500); EXPECT_EQ(1500u, decoder_.GetCurrentHeaderTableSizeSetting()); { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(500); hbb.AppendDynamicTableSizeUpdate(1250); hbb.AppendIndexedHeader(5); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_THAT(header_entries_, ElementsAreArray({HpackHeaderEntry{":path", "/index.html"}})); EXPECT_EQ(1250u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); } decoder_.ApplyHeaderTableSizeSetting(500); decoder_.ApplyHeaderTableSizeSetting(1000); EXPECT_EQ(1000u, decoder_.GetCurrentHeaderTableSizeSetting()); { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(200); hbb.AppendDynamicTableSizeUpdate(700); hbb.AppendDynamicTableSizeUpdate(900); hbb.AppendIndexedHeader(5); EXPECT_FALSE(DecodeBlock(hbb.buffer())); EXPECT_FALSE(saw_end_); EXPECT_EQ(HpackDecodingError::kDynamicTableSizeUpdateNotAllowed, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Dynamic table size update not allowed")); EXPECT_EQ(700u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); EXPECT_TRUE(header_entries_.empty()); } EXPECT_EQ(1000u, decoder_.GetCurrentHeaderTableSizeSetting()); EXPECT_FALSE(decoder_.StartDecodingBlock()); } TEST_P(HpackDecoderTest, InvalidRequiredSizeUpdate) { decoder_.ApplyHeaderTableSizeSetting(1); decoder_.ApplyHeaderTableSizeSetting(1024); HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(2); EXPECT_TRUE(decoder_.StartDecodingBlock()); DecodeBuffer db(hbb.buffer()); EXPECT_FALSE(decoder_.DecodeFragment(&db)); EXPECT_FALSE(saw_end_); EXPECT_EQ( HpackDecodingError::kInitialDynamicTableSizeUpdateIsAboveLowWaterMark, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Initial dynamic table size update is above low water mark")); EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(), header_table_size_limit()); } TEST_P(HpackDecoderTest, RequiredTableSizeChangeBeforeEnd) { decoder_.ApplyHeaderTableSizeSetting(1024); EXPECT_FALSE(DecodeBlock("")); EXPECT_EQ(HpackDecodingError::kMissingDynamicTableSizeUpdate, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Missing dynamic table size update")); EXPECT_FALSE(saw_end_); } TEST_P(HpackDecoderTest, RequiredTableSizeChangeBeforeIndexedHeader) { decoder_.ApplyHeaderTableSizeSetting(1024); HpackBlockBuilder hbb; hbb.AppendIndexedHeader(1); EXPECT_FALSE(DecodeBlock(hbb.buffer())); EXPECT_EQ(HpackDecodingError::kMissingDynamicTableSizeUpdate, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Missing dynamic table size update")); EXPECT_FALSE(saw_end_); EXPECT_TRUE(header_entries_.empty()); } TEST_P(HpackDecoderTest, RequiredTableSizeChangeBeforeIndexedHeaderName) { decoder_.ApplyHeaderTableSizeSetting(1024); HpackBlockBuilder hbb; hbb.AppendNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 2, false, "PUT"); EXPECT_FALSE(DecodeBlock(hbb.buffer())); EXPECT_EQ(HpackDecodingError::kMissingDynamicTableSizeUpdate, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Missing dynamic table size update")); EXPECT_FALSE(saw_end_); EXPECT_TRUE(header_entries_.empty()); } TEST_P(HpackDecoderTest, RequiredTableSizeChangeBeforeLiteralName) { decoder_.ApplyHeaderTableSizeSetting(1024); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, "name", false, "some data."); EXPECT_FALSE(DecodeBlock(hbb.buffer())); EXPECT_EQ(HpackDecodingError::kMissingDynamicTableSizeUpdate, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Missing dynamic table size update")); EXPECT_FALSE(saw_end_); EXPECT_TRUE(header_entries_.empty()); } TEST_P(HpackDecoderTest, InvalidIndexedHeaderVarint) { EXPECT_TRUE(decoder_.StartDecodingBlock()); DecodeBuffer db("\xff\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x00"); EXPECT_FALSE(decoder_.DecodeFragment(&db)); EXPECT_TRUE(decoder_.DetectError()); EXPECT_FALSE(saw_end_); EXPECT_EQ(HpackDecodingError::kIndexVarintError, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Index varint beyond implementation limit")); EXPECT_TRUE(header_entries_.empty()); EXPECT_FALSE(decoder_.EndDecodingBlock()); } TEST_P(HpackDecoderTest, InvalidIndex) { EXPECT_TRUE(decoder_.StartDecodingBlock()); DecodeBuffer db("\x80"); EXPECT_FALSE(decoder_.DecodeFragment(&db)); EXPECT_TRUE(decoder_.DetectError()); EXPECT_FALSE(saw_end_); EXPECT_EQ(HpackDecodingError::kInvalidIndex, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Invalid index in indexed header field representation")); EXPECT_TRUE(header_entries_.empty()); EXPECT_FALSE(decoder_.EndDecodingBlock()); } TEST_P(HpackDecoderTest, TruncatedBlock) { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(3000); EXPECT_EQ(3u, hbb.size()); hbb.AppendDynamicTableSizeUpdate(4000); EXPECT_EQ(6u, hbb.size()); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_EQ(4000u, header_table_size_limit()); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_EQ(4000u, header_table_size_limit()); EXPECT_FALSE(DecodeBlock(hbb.buffer().substr(0, hbb.size() - 1))); EXPECT_FALSE(saw_end_); EXPECT_EQ(HpackDecodingError::kTruncatedBlock, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Block ends in the middle of an instruction")); EXPECT_EQ(3000u, header_table_size_limit()); EXPECT_EQ(0u, current_header_table_size()); EXPECT_TRUE(header_entries_.empty()); } TEST_P(HpackDecoderTest, OversizeStringDetected) { HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, "name", false, "some data."); hbb.AppendLiteralNameAndValue(HpackEntryType::kUnindexedLiteralHeader, false, "name2", false, "longer data"); EXPECT_TRUE(DecodeBlock(hbb.buffer())); EXPECT_THAT(header_entries_, ElementsAreArray({HpackHeaderEntry{"name", "some data."}, HpackHeaderEntry{"name2", "longer data"}})); decoder_.set_max_string_size_bytes(10); EXPECT_FALSE(DecodeBlock(hbb.buffer())); EXPECT_THAT(header_entries_, ElementsAreArray({HpackHeaderEntry{"name", "some data."}})); EXPECT_FALSE(saw_end_); EXPECT_EQ(HpackDecodingError::kValueTooLong, decoder_.error()); EXPECT_EQ(1u, error_messages_.size()); EXPECT_THAT(error_messages_[0], Eq("Value length exceeds buffer limit")); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f48c8a8a-3466-49c9-86cf-eb251d62efa9
cpp
google/quiche
hpack_entry_decoder
quiche/http2/hpack/decoder/hpack_entry_decoder.cc
quiche/http2/hpack/decoder/hpack_entry_decoder_test.cc
#include "quiche/http2/hpack/decoder/hpack_entry_decoder.h" #include <stddef.h> #include <cstdint> #include <ostream> #include <sstream> #include <string> #include "absl/base/macros.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace { class NameDecoderListener { public: explicit NameDecoderListener(HpackEntryDecoderListener* listener) : listener_(listener) {} bool OnStringStart(bool huffman_encoded, size_t len) { listener_->OnNameStart(huffman_encoded, len); return true; } void OnStringData(const char* data, size_t len) { listener_->OnNameData(data, len); } void OnStringEnd() { listener_->OnNameEnd(); } private: HpackEntryDecoderListener* listener_; }; class ValueDecoderListener { public: explicit ValueDecoderListener(HpackEntryDecoderListener* listener) : listener_(listener) {} bool OnStringStart(bool huffman_encoded, size_t len) { listener_->OnValueStart(huffman_encoded, len); return true; } void OnStringData(const char* data, size_t len) { listener_->OnValueData(data, len); } void OnStringEnd() { listener_->OnValueEnd(); } private: HpackEntryDecoderListener* listener_; }; } DecodeStatus HpackEntryDecoder::Start(DecodeBuffer* db, HpackEntryDecoderListener* listener) { QUICHE_DCHECK(db != nullptr); QUICHE_DCHECK(listener != nullptr); QUICHE_DCHECK(db->HasData()); DecodeStatus status = entry_type_decoder_.Start(db); switch (status) { case DecodeStatus::kDecodeDone: if (entry_type_decoder_.entry_type() == HpackEntryType::kIndexedHeader) { listener->OnIndexedHeader(entry_type_decoder_.varint()); return DecodeStatus::kDecodeDone; } state_ = EntryDecoderState::kDecodedType; return Resume(db, listener); case DecodeStatus::kDecodeInProgress: QUICHE_DCHECK_EQ(0u, db->Remaining()); state_ = EntryDecoderState::kResumeDecodingType; return status; case DecodeStatus::kDecodeError: QUICHE_CODE_COUNT_N(decompress_failure_3, 11, 23); error_ = HpackDecodingError::kIndexVarintError; return status; } QUICHE_BUG(http2_bug_63_1) << "Unreachable"; return DecodeStatus::kDecodeError; } DecodeStatus HpackEntryDecoder::Resume(DecodeBuffer* db, HpackEntryDecoderListener* listener) { QUICHE_DCHECK(db != nullptr); QUICHE_DCHECK(listener != nullptr); DecodeStatus status; do { switch (state_) { case EntryDecoderState::kResumeDecodingType: QUICHE_DVLOG(1) << "kResumeDecodingType: db->Remaining=" << db->Remaining(); status = entry_type_decoder_.Resume(db); if (status == DecodeStatus::kDecodeError) { QUICHE_CODE_COUNT_N(decompress_failure_3, 12, 23); error_ = HpackDecodingError::kIndexVarintError; } if (status != DecodeStatus::kDecodeDone) { return status; } state_ = EntryDecoderState::kDecodedType; ABSL_FALLTHROUGH_INTENDED; case EntryDecoderState::kDecodedType: QUICHE_DVLOG(1) << "kDecodedType: db->Remaining=" << db->Remaining(); if (DispatchOnType(listener)) { return DecodeStatus::kDecodeDone; } continue; case EntryDecoderState::kStartDecodingName: QUICHE_DVLOG(1) << "kStartDecodingName: db->Remaining=" << db->Remaining(); { NameDecoderListener ncb(listener); status = string_decoder_.Start(db, &ncb); } if (status != DecodeStatus::kDecodeDone) { state_ = EntryDecoderState::kResumeDecodingName; if (status == DecodeStatus::kDecodeError) { QUICHE_CODE_COUNT_N(decompress_failure_3, 13, 23); error_ = HpackDecodingError::kNameLengthVarintError; } return status; } state_ = EntryDecoderState::kStartDecodingValue; ABSL_FALLTHROUGH_INTENDED; case EntryDecoderState::kStartDecodingValue: QUICHE_DVLOG(1) << "kStartDecodingValue: db->Remaining=" << db->Remaining(); { ValueDecoderListener vcb(listener); status = string_decoder_.Start(db, &vcb); } if (status == DecodeStatus::kDecodeError) { QUICHE_CODE_COUNT_N(decompress_failure_3, 14, 23); error_ = HpackDecodingError::kValueLengthVarintError; } if (status == DecodeStatus::kDecodeDone) { return status; } state_ = EntryDecoderState::kResumeDecodingValue; return status; case EntryDecoderState::kResumeDecodingName: QUICHE_DVLOG(1) << "kResumeDecodingName: db->Remaining=" << db->Remaining(); { NameDecoderListener ncb(listener); status = string_decoder_.Resume(db, &ncb); } if (status != DecodeStatus::kDecodeDone) { state_ = EntryDecoderState::kResumeDecodingName; if (status == DecodeStatus::kDecodeError) { QUICHE_CODE_COUNT_N(decompress_failure_3, 15, 23); error_ = HpackDecodingError::kNameLengthVarintError; } return status; } state_ = EntryDecoderState::kStartDecodingValue; break; case EntryDecoderState::kResumeDecodingValue: QUICHE_DVLOG(1) << "kResumeDecodingValue: db->Remaining=" << db->Remaining(); { ValueDecoderListener vcb(listener); status = string_decoder_.Resume(db, &vcb); } if (status == DecodeStatus::kDecodeError) { QUICHE_CODE_COUNT_N(decompress_failure_3, 16, 23); error_ = HpackDecodingError::kValueLengthVarintError; } if (status == DecodeStatus::kDecodeDone) { return status; } state_ = EntryDecoderState::kResumeDecodingValue; return status; } } while (true); } bool HpackEntryDecoder::DispatchOnType(HpackEntryDecoderListener* listener) { const HpackEntryType entry_type = entry_type_decoder_.entry_type(); const uint32_t varint = static_cast<uint32_t>(entry_type_decoder_.varint()); switch (entry_type) { case HpackEntryType::kIndexedHeader: listener->OnIndexedHeader(varint); return true; case HpackEntryType::kIndexedLiteralHeader: case HpackEntryType::kUnindexedLiteralHeader: case HpackEntryType::kNeverIndexedLiteralHeader: listener->OnStartLiteralHeader(entry_type, varint); if (varint == 0) { state_ = EntryDecoderState::kStartDecodingName; } else { state_ = EntryDecoderState::kStartDecodingValue; } return false; case HpackEntryType::kDynamicTableSizeUpdate: listener->OnDynamicTableSizeUpdate(varint); return true; } QUICHE_BUG(http2_bug_63_2) << "Unreachable, entry_type=" << entry_type; return true; } void HpackEntryDecoder::OutputDebugString(std::ostream& out) const { out << "HpackEntryDecoder(state=" << state_ << ", " << entry_type_decoder_ << ", " << string_decoder_ << ")"; } std::string HpackEntryDecoder::DebugString() const { std::stringstream s; s << *this; return s.str(); } std::ostream& operator<<(std::ostream& out, const HpackEntryDecoder& v) { v.OutputDebugString(out); return out; } std::ostream& operator<<(std::ostream& out, HpackEntryDecoder::EntryDecoderState state) { typedef HpackEntryDecoder::EntryDecoderState EntryDecoderState; switch (state) { case EntryDecoderState::kResumeDecodingType: return out << "kResumeDecodingType"; case EntryDecoderState::kDecodedType: return out << "kDecodedType"; case EntryDecoderState::kStartDecodingName: return out << "kStartDecodingName"; case EntryDecoderState::kResumeDecodingName: return out << "kResumeDecodingName"; case EntryDecoderState::kStartDecodingValue: return out << "kStartDecodingValue"; case EntryDecoderState::kResumeDecodingValue: return out << "kResumeDecodingValue"; } return out << static_cast<int>(state); } }
#include "quiche/http2/hpack/decoder/hpack_entry_decoder.h" #include <cstdint> #include <string> #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/test_tools/hpack_entry_collector.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { class HpackEntryDecoderTest : public RandomDecoderTest { protected: HpackEntryDecoderTest() : listener_(&collector_) {} DecodeStatus StartDecoding(DecodeBuffer* b) override { collector_.Clear(); return decoder_.Start(b, &listener_); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { return decoder_.Resume(b, &listener_); } AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db, const Validator& validator) { bool return_non_zero_on_first = true; return RandomDecoderTest::DecodeAndValidateSeveralWays( db, return_non_zero_on_first, validator); } AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb, const Validator& validator) { DecodeBuffer db(hbb.buffer()); return DecodeAndValidateSeveralWays(&db, validator); } HpackEntryDecoder decoder_; HpackEntryCollector collector_; HpackEntryDecoderVLoggingListener listener_; }; TEST_F(HpackEntryDecoderTest, IndexedHeader_Literals) { { const char input[] = {'\x82'}; DecodeBuffer b(input); auto do_check = [this]() { return collector_.ValidateIndexedHeader(2); }; EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } collector_.Clear(); { const char input[] = {'\xfe'}; DecodeBuffer b(input); auto do_check = [this]() { return collector_.ValidateIndexedHeader(126); }; EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } collector_.Clear(); { const char input[] = {'\xff', '\x00'}; DecodeBuffer b(input); auto do_check = [this]() { return collector_.ValidateIndexedHeader(127); }; EXPECT_TRUE( DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } } TEST_F(HpackEntryDecoderTest, IndexedHeader_Various) { for (const uint32_t ndx : {1, 2, 61, 62, 63, 126, 127, 254, 255, 256}) { HpackBlockBuilder hbb; hbb.AppendIndexedHeader(ndx); auto do_check = [this, ndx]() { return collector_.ValidateIndexedHeader(ndx); }; EXPECT_TRUE( DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } } TEST_F(HpackEntryDecoderTest, IndexedLiteralValue_Literal) { const char input[] = "\x7f" "\x01" "\x0d" "custom-header"; DecodeBuffer b(input, sizeof input - 1); auto do_check = [this]() { return collector_.ValidateLiteralValueHeader( HpackEntryType::kIndexedLiteralHeader, 0x40, false, "custom-header"); }; EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } TEST_F(HpackEntryDecoderTest, IndexedLiteralNameValue_Literal) { const char input[] = "\x40" "\x0a" "custom-key" "\x0d" "custom-header"; DecodeBuffer b(input, sizeof input - 1); auto do_check = [this]() { return collector_.ValidateLiteralNameValueHeader( HpackEntryType::kIndexedLiteralHeader, false, "custom-key", false, "custom-header"); }; EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } TEST_F(HpackEntryDecoderTest, DynamicTableSizeUpdate_Literal) { const char input[] = "\x3f\x00"; DecodeBuffer b(input, 2); auto do_check = [this]() { return collector_.ValidateDynamicTableSizeUpdate(31); }; EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } class HpackLiteralEntryDecoderTest : public HpackEntryDecoderTest, public ::testing::WithParamInterface<HpackEntryType> { protected: HpackLiteralEntryDecoderTest() : entry_type_(GetParam()) {} const HpackEntryType entry_type_; }; INSTANTIATE_TEST_SUITE_P( AllLiteralTypes, HpackLiteralEntryDecoderTest, testing::Values(HpackEntryType::kIndexedLiteralHeader, HpackEntryType::kUnindexedLiteralHeader, HpackEntryType::kNeverIndexedLiteralHeader)); TEST_P(HpackLiteralEntryDecoderTest, RandNameIndexAndLiteralValue) { for (int n = 0; n < 10; n++) { const uint32_t ndx = 1 + Random().Rand8(); const bool value_is_huffman_encoded = (n % 2) == 0; const std::string value = Random().RandString(Random().Rand8()); HpackBlockBuilder hbb; hbb.AppendNameIndexAndLiteralValue(entry_type_, ndx, value_is_huffman_encoded, value); auto do_check = [this, ndx, value_is_huffman_encoded, value]() -> AssertionResult { return collector_.ValidateLiteralValueHeader( entry_type_, ndx, value_is_huffman_encoded, value); }; EXPECT_TRUE( DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } } TEST_P(HpackLiteralEntryDecoderTest, RandLiteralNameAndValue) { for (int n = 0; n < 10; n++) { const bool name_is_huffman_encoded = (n & 1) == 0; const int name_len = 1 + Random().Rand8(); const std::string name = Random().RandString(name_len); const bool value_is_huffman_encoded = (n & 2) == 0; const int value_len = Random().Skewed(10); const std::string value = Random().RandString(value_len); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(entry_type_, name_is_huffman_encoded, name, value_is_huffman_encoded, value); auto do_check = [this, name_is_huffman_encoded, name, value_is_huffman_encoded, value]() -> AssertionResult { return collector_.ValidateLiteralNameValueHeader( entry_type_, name_is_huffman_encoded, name, value_is_huffman_encoded, value); }; EXPECT_TRUE( DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_entry_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_entry_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b6c1594a-127c-43ef-a7fd-eb27fc8713a4
cpp
google/quiche
hpack_decoder_tables
quiche/http2/hpack/decoder/hpack_decoder_tables.cc
quiche/http2/hpack/decoder/hpack_decoder_tables_test.cc
#include "quiche/http2/hpack/decoder/hpack_decoder_tables.h" #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace { std::vector<HpackStringPair>* MakeStaticTable() { auto* ptr = new std::vector<HpackStringPair>(); ptr->reserve(kFirstDynamicTableIndex); ptr->emplace_back("", ""); #define STATIC_TABLE_ENTRY(name, value, index) \ QUICHE_DCHECK_EQ(ptr->size(), static_cast<size_t>(index)); \ ptr->emplace_back(name, value) #include "quiche/http2/hpack/hpack_static_table_entries.inc" #undef STATIC_TABLE_ENTRY return ptr; } const std::vector<HpackStringPair>* GetStaticTable() { static const std::vector<HpackStringPair>* const g_static_table = MakeStaticTable(); return g_static_table; } } HpackStringPair::HpackStringPair(std::string name, std::string value) : name(std::move(name)), value(std::move(value)) { QUICHE_DVLOG(3) << DebugString() << " ctor"; } HpackStringPair::~HpackStringPair() { QUICHE_DVLOG(3) << DebugString() << " dtor"; } std::string HpackStringPair::DebugString() const { return absl::StrCat("HpackStringPair(name=", name, ", value=", value, ")"); } std::ostream& operator<<(std::ostream& os, const HpackStringPair& p) { os << p.DebugString(); return os; } HpackDecoderStaticTable::HpackDecoderStaticTable( const std::vector<HpackStringPair>* table) : table_(table) {} HpackDecoderStaticTable::HpackDecoderStaticTable() : table_(GetStaticTable()) {} const HpackStringPair* HpackDecoderStaticTable::Lookup(size_t index) const { if (0 < index && index < kFirstDynamicTableIndex) { return &((*table_)[index]); } return nullptr; } HpackDecoderDynamicTable::HpackDecoderDynamicTable() : insert_count_(kFirstDynamicTableIndex - 1) {} HpackDecoderDynamicTable::~HpackDecoderDynamicTable() = default; void HpackDecoderDynamicTable::DynamicTableSizeUpdate(size_t size_limit) { QUICHE_DVLOG(3) << "HpackDecoderDynamicTable::DynamicTableSizeUpdate " << size_limit; EnsureSizeNoMoreThan(size_limit); QUICHE_DCHECK_LE(current_size_, size_limit); size_limit_ = size_limit; } void HpackDecoderDynamicTable::Insert(std::string name, std::string value) { HpackStringPair entry(std::move(name), std::move(value)); size_t entry_size = entry.size(); QUICHE_DVLOG(2) << "InsertEntry of size=" << entry_size << "\n name: " << entry.name << "\n value: " << entry.value; if (entry_size > size_limit_) { QUICHE_DVLOG(2) << "InsertEntry: entry larger than table, removing " << table_.size() << " entries, of total size " << current_size_ << " bytes."; table_.clear(); current_size_ = 0; return; } ++insert_count_; size_t insert_limit = size_limit_ - entry_size; EnsureSizeNoMoreThan(insert_limit); table_.push_front(std::move(entry)); current_size_ += entry_size; QUICHE_DVLOG(2) << "InsertEntry: current_size_=" << current_size_; QUICHE_DCHECK_GE(current_size_, entry_size); QUICHE_DCHECK_LE(current_size_, size_limit_); } const HpackStringPair* HpackDecoderDynamicTable::Lookup(size_t index) const { if (index < table_.size()) { return &table_[index]; } return nullptr; } void HpackDecoderDynamicTable::EnsureSizeNoMoreThan(size_t limit) { QUICHE_DVLOG(2) << "EnsureSizeNoMoreThan limit=" << limit << ", current_size_=" << current_size_; while (current_size_ > limit) { RemoveLastEntry(); } QUICHE_DCHECK_LE(current_size_, limit); } void HpackDecoderDynamicTable::RemoveLastEntry() { QUICHE_DCHECK(!table_.empty()); if (!table_.empty()) { QUICHE_DVLOG(2) << "RemoveLastEntry current_size_=" << current_size_ << ", last entry size=" << table_.back().size(); QUICHE_DCHECK_GE(current_size_, table_.back().size()); current_size_ -= table_.back().size(); table_.pop_back(); QUICHE_DCHECK_EQ(table_.empty(), current_size_ == 0); } } HpackDecoderTables::HpackDecoderTables() = default; HpackDecoderTables::~HpackDecoderTables() = default; const HpackStringPair* HpackDecoderTables::Lookup(size_t index) const { if (index < kFirstDynamicTableIndex) { return static_table_.Lookup(index); } else { return dynamic_table_.Lookup(index - kFirstDynamicTableIndex); } } }
#include "quiche/http2/hpack/decoder/hpack_decoder_tables.h" #include <algorithm> #include <string> #include <tuple> #include <vector> #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/random_util.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; namespace http2 { namespace test { class HpackDecoderTablesPeer { public: static size_t num_dynamic_entries(const HpackDecoderTables& tables) { return tables.dynamic_table_.table_.size(); } }; namespace { struct StaticEntry { const char* name; const char* value; size_t index; }; std::vector<StaticEntry> MakeSpecStaticEntries() { std::vector<StaticEntry> static_entries; #define STATIC_TABLE_ENTRY(name, value, index) \ QUICHE_DCHECK_EQ(static_entries.size() + 1, static_cast<size_t>(index)); \ static_entries.push_back({name, value, index}); #include "quiche/http2/hpack/hpack_static_table_entries.inc" #undef STATIC_TABLE_ENTRY return static_entries; } template <class C> void ShuffleCollection(C* collection, Http2Random* r) { std::shuffle(collection->begin(), collection->end(), *r); } class HpackDecoderStaticTableTest : public quiche::test::QuicheTest { protected: HpackDecoderStaticTableTest() = default; std::vector<StaticEntry> shuffled_static_entries() { std::vector<StaticEntry> entries = MakeSpecStaticEntries(); ShuffleCollection(&entries, &random_); return entries; } AssertionResult VerifyStaticTableContents() { for (const auto& expected : shuffled_static_entries()) { const HpackStringPair* found = Lookup(expected.index); HTTP2_VERIFY_NE(found, nullptr); HTTP2_VERIFY_EQ(expected.name, found->name) << expected.index; HTTP2_VERIFY_EQ(expected.value, found->value) << expected.index; } HTTP2_VERIFY_EQ(nullptr, Lookup(0)); return AssertionSuccess(); } virtual const HpackStringPair* Lookup(size_t index) { return static_table_.Lookup(index); } Http2Random* RandomPtr() { return &random_; } Http2Random random_; private: HpackDecoderStaticTable static_table_; }; TEST_F(HpackDecoderStaticTableTest, StaticTableContents) { EXPECT_TRUE(VerifyStaticTableContents()); } size_t Size(const std::string& name, const std::string& value) { return name.size() + value.size() + 32; } typedef std::tuple<std::string, std::string, size_t> FakeHpackEntry; const std::string& Name(const FakeHpackEntry& entry) { return std::get<0>(entry); } const std::string& Value(const FakeHpackEntry& entry) { return std::get<1>(entry); } size_t Size(const FakeHpackEntry& entry) { return std::get<2>(entry); } class HpackDecoderTablesTest : public HpackDecoderStaticTableTest { protected: const HpackStringPair* Lookup(size_t index) override { return tables_.Lookup(index); } size_t dynamic_size_limit() const { return tables_.header_table_size_limit(); } size_t current_dynamic_size() const { return tables_.current_header_table_size(); } size_t num_dynamic_entries() const { return HpackDecoderTablesPeer::num_dynamic_entries(tables_); } void FakeInsert(const std::string& name, const std::string& value) { FakeHpackEntry entry(name, value, Size(name, value)); fake_dynamic_table_.insert(fake_dynamic_table_.begin(), entry); } size_t FakeSize() { size_t sz = 0; for (const auto& entry : fake_dynamic_table_) { sz += Size(entry); } return sz; } size_t FakeTrim(size_t limit) { size_t original_size = FakeSize(); size_t total_size = 0; for (size_t ndx = 0; ndx < fake_dynamic_table_.size(); ++ndx) { total_size += Size(fake_dynamic_table_[ndx]); if (total_size > limit) { fake_dynamic_table_.erase(fake_dynamic_table_.begin() + ndx, fake_dynamic_table_.end()); return original_size - FakeSize(); } } return 0; } AssertionResult VerifyDynamicTableContents() { HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize()); HTTP2_VERIFY_EQ(num_dynamic_entries(), fake_dynamic_table_.size()); for (size_t ndx = 0; ndx < fake_dynamic_table_.size(); ++ndx) { const HpackStringPair* found = Lookup(ndx + kFirstDynamicTableIndex); HTTP2_VERIFY_NE(found, nullptr); const auto& expected = fake_dynamic_table_[ndx]; HTTP2_VERIFY_EQ(Name(expected), found->name); HTTP2_VERIFY_EQ(Value(expected), found->value); } HTTP2_VERIFY_EQ( nullptr, Lookup(fake_dynamic_table_.size() + kFirstDynamicTableIndex)); return AssertionSuccess(); } AssertionResult DynamicTableSizeUpdate(size_t size_limit) { HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize()); if (size_limit < current_dynamic_size()) { tables_.DynamicTableSizeUpdate(size_limit); FakeTrim(size_limit); return VerifyDynamicTableContents(); } tables_.DynamicTableSizeUpdate(size_limit); return VerifyDynamicTableContents(); } AssertionResult Insert(const std::string& name, const std::string& value) { size_t old_count = num_dynamic_entries(); tables_.Insert(name, value); FakeInsert(name, value); HTTP2_VERIFY_EQ(old_count + 1, fake_dynamic_table_.size()); FakeTrim(dynamic_size_limit()); HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize()); HTTP2_VERIFY_EQ(num_dynamic_entries(), fake_dynamic_table_.size()); return VerifyDynamicTableContents(); } private: HpackDecoderTables tables_; std::vector<FakeHpackEntry> fake_dynamic_table_; }; TEST_F(HpackDecoderTablesTest, StaticTableContents) { EXPECT_TRUE(VerifyStaticTableContents()); } TEST_F(HpackDecoderTablesTest, RandomDynamicTable) { EXPECT_EQ(0u, current_dynamic_size()); EXPECT_TRUE(VerifyStaticTableContents()); EXPECT_TRUE(VerifyDynamicTableContents()); std::vector<size_t> table_sizes; table_sizes.push_back(dynamic_size_limit()); table_sizes.push_back(0); table_sizes.push_back(dynamic_size_limit() / 2); table_sizes.push_back(dynamic_size_limit()); table_sizes.push_back(dynamic_size_limit() / 2); table_sizes.push_back(0); table_sizes.push_back(dynamic_size_limit()); for (size_t limit : table_sizes) { ASSERT_TRUE(DynamicTableSizeUpdate(limit)); for (int insert_count = 0; insert_count < 100; ++insert_count) { std::string name = GenerateHttp2HeaderName(random_.UniformInRange(2, 40), RandomPtr()); std::string value = GenerateWebSafeString(random_.UniformInRange(2, 600), RandomPtr()); ASSERT_TRUE(Insert(name, value)); } EXPECT_TRUE(VerifyStaticTableContents()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_tables.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_decoder_tables_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
ea72a9d2-860f-466d-ac49-7b322bc3a955
cpp
google/quiche
hpack_block_decoder
quiche/http2/hpack/decoder/hpack_block_decoder.cc
quiche/http2/hpack/decoder/hpack_block_decoder_test.cc
#include "quiche/http2/hpack/decoder/hpack_block_decoder.h" #include <cstdint> #include <ostream> #include <string> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus HpackBlockDecoder::Decode(DecodeBuffer* db) { if (!before_entry_) { QUICHE_DVLOG(2) << "HpackBlockDecoder::Decode resume entry, db->Remaining=" << db->Remaining(); DecodeStatus status = entry_decoder_.Resume(db, listener_); switch (status) { case DecodeStatus::kDecodeDone: before_entry_ = true; break; case DecodeStatus::kDecodeInProgress: QUICHE_DCHECK_EQ(0u, db->Remaining()); return DecodeStatus::kDecodeInProgress; case DecodeStatus::kDecodeError: QUICHE_CODE_COUNT_N(decompress_failure_3, 1, 23); return DecodeStatus::kDecodeError; } } QUICHE_DCHECK(before_entry_); while (db->HasData()) { QUICHE_DVLOG(2) << "HpackBlockDecoder::Decode start entry, db->Remaining=" << db->Remaining(); DecodeStatus status = entry_decoder_.Start(db, listener_); switch (status) { case DecodeStatus::kDecodeDone: continue; case DecodeStatus::kDecodeInProgress: QUICHE_DCHECK_EQ(0u, db->Remaining()); before_entry_ = false; return DecodeStatus::kDecodeInProgress; case DecodeStatus::kDecodeError: QUICHE_CODE_COUNT_N(decompress_failure_3, 2, 23); return DecodeStatus::kDecodeError; } QUICHE_DCHECK(false); } QUICHE_DCHECK(before_entry_); return DecodeStatus::kDecodeDone; } std::string HpackBlockDecoder::DebugString() const { return absl::StrCat( "HpackBlockDecoder(", entry_decoder_.DebugString(), ", listener@", absl::Hex(reinterpret_cast<intptr_t>(listener_)), (before_entry_ ? ", between entries)" : ", in an entry)")); } std::ostream& operator<<(std::ostream& out, const HpackBlockDecoder& v) { return out << v.DebugString(); } }
#include "quiche/http2/hpack/decoder/hpack_block_decoder.h" #include <cstdint> #include <sstream> #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/test_tools/hpack_block_collector.h" #include "quiche/http2/test_tools/hpack_example.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { class HpackBlockDecoderTest : public RandomDecoderTest { protected: HpackBlockDecoderTest() : listener_(&collector_), decoder_(&listener_) { stop_decode_on_done_ = false; decoder_.Reset(); std::ostringstream strm; strm << decoder_; } DecodeStatus StartDecoding(DecodeBuffer* db) override { collector_.Clear(); decoder_.Reset(); return ResumeDecoding(db); } DecodeStatus ResumeDecoding(DecodeBuffer* db) override { DecodeStatus status = decoder_.Decode(db); std::ostringstream strm; strm << decoder_; return status; } AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db, const Validator& validator) { bool return_non_zero_on_first = false; return RandomDecoderTest::DecodeAndValidateSeveralWays( db, return_non_zero_on_first, validator); } AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb, const Validator& validator) { DecodeBuffer db(hbb.buffer()); return DecodeAndValidateSeveralWays(&db, validator); } AssertionResult DecodeHpackExampleAndValidateSeveralWays( absl::string_view hpack_example, Validator validator) { std::string input = HpackExampleToStringOrDie(hpack_example); DecodeBuffer db(input); return DecodeAndValidateSeveralWays(&db, validator); } uint8_t Rand8() { return Random().Rand8(); } std::string Rand8String() { return Random().RandString(Rand8()); } HpackBlockCollector collector_; HpackEntryDecoderVLoggingListener listener_; HpackBlockDecoder decoder_; }; TEST_F(HpackBlockDecoderTest, SpecExample_C_2_1) { auto do_check = [this]() { return collector_.ValidateSoleLiteralNameValueHeader( HpackEntryType::kIndexedLiteralHeader, false, "custom-key", false, "custom-header"); }; const char hpack_example[] = R"( 40 | == Literal indexed == 0a | Literal name (len = 10) 6375 7374 6f6d 2d6b 6579 | custom-key 0d | Literal value (len = 13) 6375 7374 6f6d 2d68 6561 6465 72 | custom-header | -> custom-key: | custom-header )"; EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays( hpack_example, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } TEST_F(HpackBlockDecoderTest, SpecExample_C_2_2) { auto do_check = [this]() { return collector_.ValidateSoleLiteralValueHeader( HpackEntryType::kUnindexedLiteralHeader, 4, false, "/sample/path"); }; const char hpack_example[] = R"( 04 | == Literal not indexed == | Indexed name (idx = 4) | :path 0c | Literal value (len = 12) 2f73 616d 706c 652f 7061 7468 | /sample/path | -> :path: /sample/path )"; EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays( hpack_example, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } TEST_F(HpackBlockDecoderTest, SpecExample_C_2_3) { auto do_check = [this]() { return collector_.ValidateSoleLiteralNameValueHeader( HpackEntryType::kNeverIndexedLiteralHeader, false, "password", false, "secret"); }; const char hpack_example[] = R"( 10 | == Literal never indexed == 08 | Literal name (len = 8) 7061 7373 776f 7264 | password 06 | Literal value (len = 6) 7365 6372 6574 | secret | -> password: secret )"; EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays( hpack_example, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } TEST_F(HpackBlockDecoderTest, SpecExample_C_2_4) { auto do_check = [this]() { return collector_.ValidateSoleIndexedHeader(2); }; const char hpack_example[] = R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET )"; EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays( hpack_example, ValidateDoneAndEmpty(do_check))); EXPECT_TRUE(do_check()); } TEST_F(HpackBlockDecoderTest, SpecExample_C_3_1) { std::string example = R"( 82 | == Indexed - Add == | idx = 2 | -> :method: GET 86 | == Indexed - Add == | idx = 6 | -> :scheme: http 84 | == Indexed - Add == | idx = 4 | -> :path: / 41 | == Literal indexed == | Indexed name (idx = 1) | :authority 0f | Literal value (len = 15) 7777 772e 6578 616d 706c 652e 636f 6d | www.example.com | -> :authority: | www.example.com )"; HpackBlockCollector expected; expected.ExpectIndexedHeader(2); expected.ExpectIndexedHeader(6); expected.ExpectIndexedHeader(4); expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 1, false, "www.example.com"); EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays( example, ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); }))); EXPECT_TRUE(collector_.VerifyEq(expected)); } TEST_F(HpackBlockDecoderTest, SpecExample_C_5_1) { std::string example = R"( 48 | == Literal indexed == | Indexed name (idx = 8) | :status 03 | Literal value (len = 3) 3330 32 | 302 | -> :status: 302 58 | == Literal indexed == | Indexed name (idx = 24) | cache-control 07 | Literal value (len = 7) 7072 6976 6174 65 | private | -> cache-control: private 61 | == Literal indexed == | Indexed name (idx = 33) | date 1d | Literal value (len = 29) 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013 2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT | -> date: Mon, 21 Oct 2013 | 20:13:21 GMT 6e | == Literal indexed == | Indexed name (idx = 46) | location 17 | Literal value (len = 23) 6874 7470 733a 2f2f 7777 772e 6578 616d | https: 706c 652e 636f 6d | ple.com | -> location: | https: )"; HpackBlockCollector expected; expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 8, false, "302"); expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 24, false, "private"); expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 33, false, "Mon, 21 Oct 2013 20:13:21 GMT"); expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 46, false, "https: EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays( example, ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); }))); EXPECT_TRUE(collector_.VerifyEq(expected)); } TEST_F(HpackBlockDecoderTest, Computed) { HpackBlockCollector expected; expected.ExpectIndexedHeader(0); expected.ExpectIndexedHeader(1); expected.ExpectIndexedHeader(126); expected.ExpectIndexedHeader(127); expected.ExpectIndexedHeader(128); expected.ExpectDynamicTableSizeUpdate(0); expected.ExpectDynamicTableSizeUpdate(1); expected.ExpectDynamicTableSizeUpdate(14); expected.ExpectDynamicTableSizeUpdate(15); expected.ExpectDynamicTableSizeUpdate(30); expected.ExpectDynamicTableSizeUpdate(31); expected.ExpectDynamicTableSizeUpdate(4095); expected.ExpectDynamicTableSizeUpdate(4096); expected.ExpectDynamicTableSizeUpdate(8192); for (auto type : {HpackEntryType::kIndexedLiteralHeader, HpackEntryType::kUnindexedLiteralHeader, HpackEntryType::kNeverIndexedLiteralHeader}) { for (bool value_huffman : {false, true}) { expected.ExpectNameIndexAndLiteralValue(type, Rand8() + 1, value_huffman, Rand8String()); expected.ExpectLiteralNameAndValue(type, false, Rand8String(), value_huffman, Rand8String()); expected.ExpectLiteralNameAndValue(type, true, Rand8String(), value_huffman, Rand8String()); } } expected.ShuffleEntries(RandomPtr()); HpackBlockBuilder hbb; expected.AppendToHpackBlockBuilder(&hbb); EXPECT_TRUE(DecodeAndValidateSeveralWays( hbb, ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); }))); EXPECT_TRUE(collector_.VerifyEq(expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_block_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_block_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
96f35dab-a701-498b-ae92-c12871c4bc1e
cpp
google/quiche
hpack_entry_type_decoder
quiche/http2/hpack/decoder/hpack_entry_type_decoder.cc
quiche/http2/hpack/decoder/hpack_entry_type_decoder_test.cc
#include "quiche/http2/hpack/decoder/hpack_entry_type_decoder.h" #include <ios> #include <ostream> #include <string> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::string HpackEntryTypeDecoder::DebugString() const { return absl::StrCat( "HpackEntryTypeDecoder(varint_decoder=", varint_decoder_.DebugString(), ", entry_type=", entry_type_, ")"); } std::ostream& operator<<(std::ostream& out, const HpackEntryTypeDecoder& v) { return out << v.DebugString(); } DecodeStatus HpackEntryTypeDecoder::Start(DecodeBuffer* db) { QUICHE_DCHECK(db != nullptr); QUICHE_DCHECK(db->HasData()); uint8_t byte = db->DecodeUInt8(); switch (byte) { case 0b00000000: case 0b00000001: case 0b00000010: case 0b00000011: case 0b00000100: case 0b00000101: case 0b00000110: case 0b00000111: case 0b00001000: case 0b00001001: case 0b00001010: case 0b00001011: case 0b00001100: case 0b00001101: case 0b00001110: entry_type_ = HpackEntryType::kUnindexedLiteralHeader; varint_decoder_.set_value(byte); return DecodeStatus::kDecodeDone; case 0b00001111: entry_type_ = HpackEntryType::kUnindexedLiteralHeader; return varint_decoder_.StartExtended(4, db); case 0b00010000: case 0b00010001: case 0b00010010: case 0b00010011: case 0b00010100: case 0b00010101: case 0b00010110: case 0b00010111: case 0b00011000: case 0b00011001: case 0b00011010: case 0b00011011: case 0b00011100: case 0b00011101: case 0b00011110: entry_type_ = HpackEntryType::kNeverIndexedLiteralHeader; varint_decoder_.set_value(byte & 0x0f); return DecodeStatus::kDecodeDone; case 0b00011111: entry_type_ = HpackEntryType::kNeverIndexedLiteralHeader; return varint_decoder_.StartExtended(4, db); case 0b00100000: case 0b00100001: case 0b00100010: case 0b00100011: case 0b00100100: case 0b00100101: case 0b00100110: case 0b00100111: case 0b00101000: case 0b00101001: case 0b00101010: case 0b00101011: case 0b00101100: case 0b00101101: case 0b00101110: case 0b00101111: case 0b00110000: case 0b00110001: case 0b00110010: case 0b00110011: case 0b00110100: case 0b00110101: case 0b00110110: case 0b00110111: case 0b00111000: case 0b00111001: case 0b00111010: case 0b00111011: case 0b00111100: case 0b00111101: case 0b00111110: entry_type_ = HpackEntryType::kDynamicTableSizeUpdate; varint_decoder_.set_value(byte & 0x01f); return DecodeStatus::kDecodeDone; case 0b00111111: entry_type_ = HpackEntryType::kDynamicTableSizeUpdate; return varint_decoder_.StartExtended(5, db); case 0b01000000: case 0b01000001: case 0b01000010: case 0b01000011: case 0b01000100: case 0b01000101: case 0b01000110: case 0b01000111: case 0b01001000: case 0b01001001: case 0b01001010: case 0b01001011: case 0b01001100: case 0b01001101: case 0b01001110: case 0b01001111: case 0b01010000: case 0b01010001: case 0b01010010: case 0b01010011: case 0b01010100: case 0b01010101: case 0b01010110: case 0b01010111: case 0b01011000: case 0b01011001: case 0b01011010: case 0b01011011: case 0b01011100: case 0b01011101: case 0b01011110: case 0b01011111: case 0b01100000: case 0b01100001: case 0b01100010: case 0b01100011: case 0b01100100: case 0b01100101: case 0b01100110: case 0b01100111: case 0b01101000: case 0b01101001: case 0b01101010: case 0b01101011: case 0b01101100: case 0b01101101: case 0b01101110: case 0b01101111: case 0b01110000: case 0b01110001: case 0b01110010: case 0b01110011: case 0b01110100: case 0b01110101: case 0b01110110: case 0b01110111: case 0b01111000: case 0b01111001: case 0b01111010: case 0b01111011: case 0b01111100: case 0b01111101: case 0b01111110: entry_type_ = HpackEntryType::kIndexedLiteralHeader; varint_decoder_.set_value(byte & 0x03f); return DecodeStatus::kDecodeDone; case 0b01111111: entry_type_ = HpackEntryType::kIndexedLiteralHeader; return varint_decoder_.StartExtended(6, db); case 0b10000000: case 0b10000001: case 0b10000010: case 0b10000011: case 0b10000100: case 0b10000101: case 0b10000110: case 0b10000111: case 0b10001000: case 0b10001001: case 0b10001010: case 0b10001011: case 0b10001100: case 0b10001101: case 0b10001110: case 0b10001111: case 0b10010000: case 0b10010001: case 0b10010010: case 0b10010011: case 0b10010100: case 0b10010101: case 0b10010110: case 0b10010111: case 0b10011000: case 0b10011001: case 0b10011010: case 0b10011011: case 0b10011100: case 0b10011101: case 0b10011110: case 0b10011111: case 0b10100000: case 0b10100001: case 0b10100010: case 0b10100011: case 0b10100100: case 0b10100101: case 0b10100110: case 0b10100111: case 0b10101000: case 0b10101001: case 0b10101010: case 0b10101011: case 0b10101100: case 0b10101101: case 0b10101110: case 0b10101111: case 0b10110000: case 0b10110001: case 0b10110010: case 0b10110011: case 0b10110100: case 0b10110101: case 0b10110110: case 0b10110111: case 0b10111000: case 0b10111001: case 0b10111010: case 0b10111011: case 0b10111100: case 0b10111101: case 0b10111110: case 0b10111111: case 0b11000000: case 0b11000001: case 0b11000010: case 0b11000011: case 0b11000100: case 0b11000101: case 0b11000110: case 0b11000111: case 0b11001000: case 0b11001001: case 0b11001010: case 0b11001011: case 0b11001100: case 0b11001101: case 0b11001110: case 0b11001111: case 0b11010000: case 0b11010001: case 0b11010010: case 0b11010011: case 0b11010100: case 0b11010101: case 0b11010110: case 0b11010111: case 0b11011000: case 0b11011001: case 0b11011010: case 0b11011011: case 0b11011100: case 0b11011101: case 0b11011110: case 0b11011111: case 0b11100000: case 0b11100001: case 0b11100010: case 0b11100011: case 0b11100100: case 0b11100101: case 0b11100110: case 0b11100111: case 0b11101000: case 0b11101001: case 0b11101010: case 0b11101011: case 0b11101100: case 0b11101101: case 0b11101110: case 0b11101111: case 0b11110000: case 0b11110001: case 0b11110010: case 0b11110011: case 0b11110100: case 0b11110101: case 0b11110110: case 0b11110111: case 0b11111000: case 0b11111001: case 0b11111010: case 0b11111011: case 0b11111100: case 0b11111101: case 0b11111110: entry_type_ = HpackEntryType::kIndexedHeader; varint_decoder_.set_value(byte & 0x07f); return DecodeStatus::kDecodeDone; case 0b11111111: entry_type_ = HpackEntryType::kIndexedHeader; return varint_decoder_.StartExtended(7, db); } QUICHE_BUG(http2_bug_66_1) << "Unreachable, byte=" << std::hex << static_cast<uint32_t>(byte); QUICHE_CODE_COUNT_N(decompress_failure_3, 17, 23); return DecodeStatus::kDecodeError; } }
#include "quiche/http2/hpack/decoder/hpack_entry_type_decoder.h" #include <vector> #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionSuccess; namespace http2 { namespace test { namespace { const bool kReturnNonZeroOnFirst = true; class HpackEntryTypeDecoderTest : public RandomDecoderTest { protected: DecodeStatus StartDecoding(DecodeBuffer* b) override { QUICHE_CHECK_LT(0u, b->Remaining()); return decoder_.Start(b); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { return decoder_.Resume(b); } HpackEntryTypeDecoder decoder_; }; TEST_F(HpackEntryTypeDecoderTest, DynamicTableSizeUpdate) { for (uint32_t size = 0; size < 1000 * 1000; size += 256) { HpackBlockBuilder bb; bb.AppendDynamicTableSizeUpdate(size); DecodeBuffer db(bb.buffer()); auto validator = [size, this]() -> AssertionResult { HTTP2_VERIFY_EQ(HpackEntryType::kDynamicTableSizeUpdate, decoder_.entry_type()); HTTP2_VERIFY_EQ(size, decoder_.varint()); return AssertionSuccess(); }; EXPECT_TRUE(DecodeAndValidateSeveralWays(&db, kReturnNonZeroOnFirst, ValidateDoneAndEmpty(validator))) << "\nentry_type=kDynamicTableSizeUpdate, size=" << size; EXPECT_TRUE(validator()); } } TEST_F(HpackEntryTypeDecoderTest, HeaderWithIndex) { std::vector<HpackEntryType> entry_types = { HpackEntryType::kIndexedHeader, HpackEntryType::kIndexedLiteralHeader, HpackEntryType::kUnindexedLiteralHeader, HpackEntryType::kNeverIndexedLiteralHeader, }; for (const HpackEntryType entry_type : entry_types) { const uint32_t first = entry_type == HpackEntryType::kIndexedHeader ? 1 : 0; for (uint32_t index = first; index < 1000; ++index) { HpackBlockBuilder bb; bb.AppendEntryTypeAndVarint(entry_type, index); DecodeBuffer db(bb.buffer()); auto validator = [entry_type, index, this]() -> AssertionResult { HTTP2_VERIFY_EQ(entry_type, decoder_.entry_type()); HTTP2_VERIFY_EQ(index, decoder_.varint()); return AssertionSuccess(); }; EXPECT_TRUE(DecodeAndValidateSeveralWays(&db, kReturnNonZeroOnFirst, ValidateDoneAndEmpty(validator))) << "\nentry_type=" << entry_type << ", index=" << index; EXPECT_TRUE(validator()); } } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_entry_type_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_entry_type_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
c8fc6d04-bc82-4fe0-8eab-312e35fd1f38
cpp
google/quiche
hpack_huffman_encoder
quiche/http2/hpack/huffman/hpack_huffman_encoder.cc
quiche/http2/hpack/huffman/hpack_huffman_encoder_test.cc
#include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include <string> #include "quiche/http2/hpack/huffman/huffman_spec_tables.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { size_t HuffmanSize(absl::string_view plain) { size_t bits = 0; for (const uint8_t c : plain) { bits += HuffmanSpecTables::kCodeLengths[c]; } return (bits + 7) / 8; } void HuffmanEncode(absl::string_view input, size_t encoded_size, std::string* output) { const size_t original_size = output->size(); const size_t final_size = original_size + encoded_size; output->resize(final_size + 4, 0); char* const first = &*output->begin() + original_size; size_t bit_counter = 0; for (uint8_t c : input) { uint64_t code = static_cast<uint64_t>(HuffmanSpecTables::kLeftCodes[c]) << (8 - (bit_counter % 8)); char* const current = first + (bit_counter / 8); bit_counter += HuffmanSpecTables::kCodeLengths[c]; *current |= code >> 32; *(current + 1) |= (code >> 24) & 0xff; if ((code & 0xff0000) == 0) { continue; } *(current + 2) |= (code >> 16) & 0xff; if ((code & 0xff00) == 0) { continue; } *(current + 3) |= (code >> 8) & 0xff; *(current + 4) |= code & 0xff; } QUICHE_DCHECK_EQ(encoded_size, (bit_counter + 7) / 8); if (bit_counter % 8 != 0) { *(first + encoded_size - 1) |= 0xff >> (bit_counter & 7); } output->resize(final_size); } }
#include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include <cstddef> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace { TEST(HuffmanEncoderTest, Empty) { std::string empty(""); size_t encoded_size = HuffmanSize(empty); EXPECT_EQ(0u, encoded_size); std::string buffer; HuffmanEncode(empty, encoded_size, &buffer); EXPECT_EQ("", buffer); } TEST(HuffmanEncoderTest, SpecRequestExamples) { std::string test_table[] = { "f1e3c2e5f23a6ba0ab90f4ff", "www.example.com", "a8eb10649cbf", "no-cache", "25a849e95ba97d7f", "custom-key", "25a849e95bb8e8b4bf", "custom-value", }; for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) { std::string huffman_encoded; ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded)); const std::string& plain_string(test_table[i + 1]); size_t encoded_size = HuffmanSize(plain_string); EXPECT_EQ(huffman_encoded.size(), encoded_size); std::string buffer; buffer.reserve(huffman_encoded.size()); HuffmanEncode(plain_string, encoded_size, &buffer); EXPECT_EQ(buffer, huffman_encoded) << "Error encoding " << plain_string; } } TEST(HuffmanEncoderTest, SpecResponseExamples) { std::string test_table[] = { "6402", "302", "aec3771a4b", "private", "d07abe941054d444a8200595040b8166e082a62d1bff", "Mon, 21 Oct 2013 20:13:21 GMT", "9d29ad171863c78f0b97c8e9ae82ae43d3", "https: "94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0" "03ed4ee5b1063d5007", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", }; for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) { std::string huffman_encoded; ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded)); const std::string& plain_string(test_table[i + 1]); size_t encoded_size = HuffmanSize(plain_string); EXPECT_EQ(huffman_encoded.size(), encoded_size); std::string buffer; HuffmanEncode(plain_string, encoded_size, &buffer); EXPECT_EQ(buffer, huffman_encoded) << "Error encoding " << plain_string; } } TEST(HuffmanEncoderTest, EncodedSizeAgreesWithEncodeString) { std::string test_table[] = { "", "Mon, 21 Oct 2013 20:13:21 GMT", "https: "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", std::string(1, '\0'), std::string("foo\0bar", 7), std::string(256, '\0'), }; for (size_t i = 0; i != 256; ++i) { test_table[ABSL_ARRAYSIZE(test_table) - 1][i] = static_cast<char>(i); } for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); ++i) { const std::string& plain_string = test_table[i]; size_t encoded_size = HuffmanSize(plain_string); std::string huffman_encoded; HuffmanEncode(plain_string, encoded_size, &huffman_encoded); EXPECT_EQ(encoded_size, huffman_encoded.size()); } } TEST(HuffmanEncoderTest, AppendToOutput) { size_t encoded_size = HuffmanSize("foo"); std::string buffer; HuffmanEncode("foo", encoded_size, &buffer); std::string expected_encoding; ASSERT_TRUE(absl::HexStringToBytes("94e7", &expected_encoding)); EXPECT_EQ(expected_encoding, buffer); encoded_size = HuffmanSize("bar"); HuffmanEncode("bar", encoded_size, &buffer); ASSERT_TRUE(absl::HexStringToBytes("94e78c767f", &expected_encoding)); EXPECT_EQ(expected_encoding, buffer); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/huffman/hpack_huffman_encoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/huffman/hpack_huffman_encoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
547914af-97d2-4cfc-bdfe-0b2d0b6bf109
cpp
google/quiche
hpack_huffman_decoder
quiche/http2/hpack/huffman/hpack_huffman_decoder.cc
quiche/http2/hpack/huffman/hpack_huffman_decoder_test.cc
#include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h" #include <bitset> #include <limits> #include <ostream> #include <sstream> #include <string> #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace { typedef uint32_t HuffmanCode; typedef uint16_t HuffmanCodeBitCount; typedef std::bitset<32> HuffmanCodeBitSet; typedef std::bitset<64> HuffmanAccumulatorBitSet; static constexpr HuffmanCodeBitCount kMinCodeBitCount = 5; static constexpr HuffmanCodeBitCount kMaxCodeBitCount = 30; static constexpr HuffmanCodeBitCount kHuffmanCodeBitCount = std::numeric_limits<HuffmanCode>::digits; static_assert(std::numeric_limits<HuffmanCode>::digits >= kMaxCodeBitCount, "HuffmanCode isn't big enough."); static_assert(std::numeric_limits<HuffmanAccumulator>::digits >= kMaxCodeBitCount, "HuffmanAccumulator isn't big enough."); static constexpr HuffmanAccumulatorBitCount kHuffmanAccumulatorBitCount = std::numeric_limits<HuffmanAccumulator>::digits; static constexpr HuffmanAccumulatorBitCount kExtraAccumulatorBitCount = kHuffmanAccumulatorBitCount - kHuffmanCodeBitCount; struct PrefixInfo { uint32_t DecodeToCanonical(HuffmanCode bits) const { HuffmanCode ordinal_in_length = ((bits - first_code) >> (kHuffmanCodeBitCount - code_length)); return first_canonical + ordinal_in_length; } const HuffmanCode first_code; const uint16_t code_length; const uint16_t first_canonical; }; inline std::ostream& operator<<(std::ostream& out, const PrefixInfo& v) { return out << "{first_code: " << HuffmanCodeBitSet(v.first_code) << ", code_length: " << v.code_length << ", first_canonical: " << v.first_canonical << "}"; } PrefixInfo PrefixToInfo(HuffmanCode value) { if (value < 0b10111000000000000000000000000000) { if (value < 0b01010000000000000000000000000000) { return {0b00000000000000000000000000000000, 5, 0}; } else { return {0b01010000000000000000000000000000, 6, 10}; } } else { if (value < 0b11111110000000000000000000000000) { if (value < 0b11111000000000000000000000000000) { return {0b10111000000000000000000000000000, 7, 36}; } else { return {0b11111000000000000000000000000000, 8, 68}; } } else { if (value < 0b11111111110000000000000000000000) { if (value < 0b11111111101000000000000000000000) { if (value < 0b11111111010000000000000000000000) { return {0b11111110000000000000000000000000, 10, 74}; } else { return {0b11111111010000000000000000000000, 11, 79}; } } else { return {0b11111111101000000000000000000000, 12, 82}; } } else { if (value < 0b11111111111111100000000000000000) { if (value < 0b11111111111110000000000000000000) { if (value < 0b11111111111100000000000000000000) { return {0b11111111110000000000000000000000, 13, 84}; } else { return {0b11111111111100000000000000000000, 14, 90}; } } else { return {0b11111111111110000000000000000000, 15, 92}; } } else { if (value < 0b11111111111111110100100000000000) { if (value < 0b11111111111111101110000000000000) { if (value < 0b11111111111111100110000000000000) { return {0b11111111111111100000000000000000, 19, 95}; } else { return {0b11111111111111100110000000000000, 20, 98}; } } else { return {0b11111111111111101110000000000000, 21, 106}; } } else { if (value < 0b11111111111111111110101000000000) { if (value < 0b11111111111111111011000000000000) { return {0b11111111111111110100100000000000, 22, 119}; } else { return {0b11111111111111111011000000000000, 23, 145}; } } else { if (value < 0b11111111111111111111101111000000) { if (value < 0b11111111111111111111100000000000) { if (value < 0b11111111111111111111011000000000) { return {0b11111111111111111110101000000000, 24, 174}; } else { return {0b11111111111111111111011000000000, 25, 186}; } } else { return {0b11111111111111111111100000000000, 26, 190}; } } else { if (value < 0b11111111111111111111111111110000) { if (value < 0b11111111111111111111111000100000) { return {0b11111111111111111111101111000000, 27, 205}; } else { return {0b11111111111111111111111000100000, 28, 224}; } } else { return {0b11111111111111111111111111110000, 30, 253}; } } } } } } } } } constexpr unsigned char kCanonicalToSymbol[] = { '0', '1', '2', 'a', 'c', 'e', 'i', 'o', 's', 't', 0x20, '%', '-', '.', '/', '3', '4', '5', '6', '7', '8', '9', '=', 'A', '_', 'b', 'd', 'f', 'g', 'h', 'l', 'm', 'n', 'p', 'r', 'u', ':', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'j', 'k', 'q', 'v', 'w', 'x', 'y', 'z', '&', '*', ',', ';', 'X', 'Z', '!', '\"', '(', ')', '?', '\'', '+', '|', '#', '>', 0x00, '$', '@', '[', ']', '~', '^', '}', '<', '`', '{', '\\', 0xc3, 0xd0, 0x80, 0x82, 0x83, 0xa2, 0xb8, 0xc2, 0xe0, 0xe2, 0x99, 0xa1, 0xa7, 0xac, 0xb0, 0xb1, 0xb3, 0xd1, 0xd8, 0xd9, 0xe3, 0xe5, 0xe6, 0x81, 0x84, 0x85, 0x86, 0x88, 0x92, 0x9a, 0x9c, 0xa0, 0xa3, 0xa4, 0xa9, 0xaa, 0xad, 0xb2, 0xb5, 0xb9, 0xba, 0xbb, 0xbd, 0xbe, 0xc4, 0xc6, 0xe4, 0xe8, 0xe9, 0x01, 0x87, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8f, 0x93, 0x95, 0x96, 0x97, 0x98, 0x9b, 0x9d, 0x9e, 0xa5, 0xa6, 0xa8, 0xae, 0xaf, 0xb4, 0xb6, 0xb7, 0xbc, 0xbf, 0xc5, 0xe7, 0xef, 0x09, 0x8e, 0x90, 0x91, 0x94, 0x9f, 0xab, 0xce, 0xd7, 0xe1, 0xec, 0xed, 0xc7, 0xcf, 0xea, 0xeb, 0xc0, 0xc1, 0xc8, 0xc9, 0xca, 0xcd, 0xd2, 0xd5, 0xda, 0xdb, 0xee, 0xf0, 0xf2, 0xf3, 0xff, 0xcb, 0xcc, 0xd3, 0xd4, 0xd6, 0xdd, 0xde, 0xdf, 0xf1, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0b, 0x0c, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x7f, 0xdc, 0xf9, 0x0a, 0x0d, 0x16, }; constexpr size_t kShortCodeTableSize = 124; struct ShortCodeInfo { uint8_t symbol; uint8_t length; } kShortCodeTable[kShortCodeTableSize] = { {0x30, 5}, {0x30, 5}, {0x30, 5}, {0x30, 5}, {0x31, 5}, {0x31, 5}, {0x31, 5}, {0x31, 5}, {0x32, 5}, {0x32, 5}, {0x32, 5}, {0x32, 5}, {0x61, 5}, {0x61, 5}, {0x61, 5}, {0x61, 5}, {0x63, 5}, {0x63, 5}, {0x63, 5}, {0x63, 5}, {0x65, 5}, {0x65, 5}, {0x65, 5}, {0x65, 5}, {0x69, 5}, {0x69, 5}, {0x69, 5}, {0x69, 5}, {0x6f, 5}, {0x6f, 5}, {0x6f, 5}, {0x6f, 5}, {0x73, 5}, {0x73, 5}, {0x73, 5}, {0x73, 5}, {0x74, 5}, {0x74, 5}, {0x74, 5}, {0x74, 5}, {0x20, 6}, {0x20, 6}, {0x25, 6}, {0x25, 6}, {0x2d, 6}, {0x2d, 6}, {0x2e, 6}, {0x2e, 6}, {0x2f, 6}, {0x2f, 6}, {0x33, 6}, {0x33, 6}, {0x34, 6}, {0x34, 6}, {0x35, 6}, {0x35, 6}, {0x36, 6}, {0x36, 6}, {0x37, 6}, {0x37, 6}, {0x38, 6}, {0x38, 6}, {0x39, 6}, {0x39, 6}, {0x3d, 6}, {0x3d, 6}, {0x41, 6}, {0x41, 6}, {0x5f, 6}, {0x5f, 6}, {0x62, 6}, {0x62, 6}, {0x64, 6}, {0x64, 6}, {0x66, 6}, {0x66, 6}, {0x67, 6}, {0x67, 6}, {0x68, 6}, {0x68, 6}, {0x6c, 6}, {0x6c, 6}, {0x6d, 6}, {0x6d, 6}, {0x6e, 6}, {0x6e, 6}, {0x70, 6}, {0x70, 6}, {0x72, 6}, {0x72, 6}, {0x75, 6}, {0x75, 6}, {0x3a, 7}, {0x42, 7}, {0x43, 7}, {0x44, 7}, {0x45, 7}, {0x46, 7}, {0x47, 7}, {0x48, 7}, {0x49, 7}, {0x4a, 7}, {0x4b, 7}, {0x4c, 7}, {0x4d, 7}, {0x4e, 7}, {0x4f, 7}, {0x50, 7}, {0x51, 7}, {0x52, 7}, {0x53, 7}, {0x54, 7}, {0x55, 7}, {0x56, 7}, {0x57, 7}, {0x59, 7}, {0x6a, 7}, {0x6b, 7}, {0x71, 7}, {0x76, 7}, {0x77, 7}, {0x78, 7}, {0x79, 7}, {0x7a, 7}, }; } HuffmanBitBuffer::HuffmanBitBuffer() { Reset(); } void HuffmanBitBuffer::Reset() { accumulator_ = 0; count_ = 0; } size_t HuffmanBitBuffer::AppendBytes(absl::string_view input) { HuffmanAccumulatorBitCount free_cnt = free_count(); size_t bytes_available = input.size(); if (free_cnt < 8 || bytes_available == 0) { return 0; } size_t bytes_used = 0; auto* ptr = reinterpret_cast<const uint8_t*>(input.data()); do { auto b = static_cast<HuffmanAccumulator>(*ptr++); free_cnt -= 8; accumulator_ |= (b << free_cnt); ++bytes_used; } while (free_cnt >= 8 && bytes_used < bytes_available); count_ += (bytes_used * 8); return bytes_used; } HuffmanAccumulatorBitCount HuffmanBitBuffer::free_count() const { return kHuffmanAccumulatorBitCount - count_; } void HuffmanBitBuffer::ConsumeBits(HuffmanAccumulatorBitCount code_length) { QUICHE_DCHECK_LE(code_length, count_); accumulator_ <<= code_length; count_ -= code_length; } bool HuffmanBitBuffer::InputProperlyTerminated() const { auto cnt = count(); if (cnt < 8) { if (cnt == 0) { return true; } HuffmanAccumulator expected = ~(~HuffmanAccumulator() >> cnt); QUICHE_DCHECK_EQ(accumulator_ & ~expected, 0u) << "\n expected: " << HuffmanAccumulatorBitSet(expected) << "\n " << *this; return accumulator_ == expected; } return false; } std::string HuffmanBitBuffer::DebugString() const { std::stringstream ss; ss << "{accumulator: " << HuffmanAccumulatorBitSet(accumulator_) << "; count: " << count_ << "}"; return ss.str(); } HpackHuffmanDecoder::HpackHuffmanDecoder() = default; HpackHuffmanDecoder::~HpackHuffmanDecoder() = default; bool HpackHuffmanDecoder::Decode(absl::string_view input, std::string* output) { QUICHE_DVLOG(1) << "HpackHuffmanDecoder::Decode"; input.remove_prefix(bit_buffer_.AppendBytes(input)); while (true) { QUICHE_DVLOG(3) << "Enter Decode Loop, bit_buffer_: " << bit_buffer_; if (bit_buffer_.count() >= 7) { uint8_t short_code = bit_buffer_.value() >> (kHuffmanAccumulatorBitCount - 7); QUICHE_DCHECK_LT(short_code, 128); if (short_code < kShortCodeTableSize) { ShortCodeInfo info = kShortCodeTable[short_code]; bit_buffer_.ConsumeBits(info.length); output->push_back(static_cast<char>(info.symbol)); continue; } } else { size_t byte_count = bit_buffer_.AppendBytes(input); if (byte_count > 0) { input.remove_prefix(byte_count); continue; } } HuffmanCode code_prefix = bit_buffer_.value() >> kExtraAccumulatorBitCount; QUICHE_DVLOG(3) << "code_prefix: " << HuffmanCodeBitSet(code_prefix); PrefixInfo prefix_info = PrefixToInfo(code_prefix); QUICHE_DVLOG(3) << "prefix_info: " << prefix_info; QUICHE_DCHECK_LE(kMinCodeBitCount, prefix_info.code_length); QUICHE_DCHECK_LE(prefix_info.code_length, kMaxCodeBitCount); if (prefix_info.code_length <= bit_buffer_.count()) { uint32_t canonical = prefix_info.DecodeToCanonical(code_prefix); if (canonical < 256) { char c = kCanonicalToSymbol[canonical]; output->push_back(c); bit_buffer_.ConsumeBits(prefix_info.code_length); continue; } QUICHE_DLOG(ERROR) << "EOS explicitly encoded!\n " << bit_buffer_ << "\n " << prefix_info; return false; } size_t byte_count = bit_buffer_.AppendBytes(input); if (byte_count == 0) { QUICHE_DCHECK_EQ(input.size(), 0u); return true; } input.remove_prefix(byte_count); } } std::string HpackHuffmanDecoder::DebugString() const { return bit_buffer_.DebugString(); } }
#include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h" #include <cstddef> #include <iostream> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { TEST(HuffmanBitBufferTest, Reset) { HuffmanBitBuffer bb; EXPECT_TRUE(bb.IsEmpty()); EXPECT_TRUE(bb.InputProperlyTerminated()); EXPECT_EQ(bb.count(), 0u); EXPECT_EQ(bb.free_count(), 64u); EXPECT_EQ(bb.value(), 0u); } TEST(HuffmanBitBufferTest, AppendBytesAligned) { std::string s; s.push_back('\x11'); s.push_back('\x22'); s.push_back('\x33'); absl::string_view sp(s); HuffmanBitBuffer bb; sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_TRUE(sp.empty()); EXPECT_FALSE(bb.IsEmpty()) << bb; EXPECT_FALSE(bb.InputProperlyTerminated()); EXPECT_EQ(bb.count(), 24u) << bb; EXPECT_EQ(bb.free_count(), 40u) << bb; EXPECT_EQ(bb.value(), HuffmanAccumulator(0x112233) << 40) << bb; s.clear(); s.push_back('\x44'); sp = s; sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_TRUE(sp.empty()); EXPECT_EQ(bb.count(), 32u) << bb; EXPECT_EQ(bb.free_count(), 32u) << bb; EXPECT_EQ(bb.value(), HuffmanAccumulator(0x11223344) << 32) << bb; s.clear(); s.push_back('\x55'); s.push_back('\x66'); s.push_back('\x77'); s.push_back('\x88'); s.push_back('\x99'); sp = s; sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_EQ(sp.size(), 1u); EXPECT_EQ('\x99', sp[0]); EXPECT_EQ(bb.count(), 64u) << bb; EXPECT_EQ(bb.free_count(), 0u) << bb; EXPECT_EQ(bb.value(), HuffmanAccumulator(0x1122334455667788LL)) << bb; sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_EQ(sp.size(), 1u); EXPECT_EQ('\x99', sp[0]); EXPECT_EQ(bb.count(), 64u) << bb; EXPECT_EQ(bb.free_count(), 0u) << bb; EXPECT_EQ(bb.value(), HuffmanAccumulator(0x1122334455667788LL)) << bb; } TEST(HuffmanBitBufferTest, ConsumeBits) { std::string s; s.push_back('\x11'); s.push_back('\x22'); s.push_back('\x33'); absl::string_view sp(s); HuffmanBitBuffer bb; sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_TRUE(sp.empty()); bb.ConsumeBits(1); EXPECT_EQ(bb.count(), 23u) << bb; EXPECT_EQ(bb.free_count(), 41u) << bb; EXPECT_EQ(bb.value(), HuffmanAccumulator(0x112233) << 41) << bb; bb.ConsumeBits(20); EXPECT_EQ(bb.count(), 3u) << bb; EXPECT_EQ(bb.free_count(), 61u) << bb; EXPECT_EQ(bb.value(), HuffmanAccumulator(0x3) << 61) << bb; } TEST(HuffmanBitBufferTest, AppendBytesUnaligned) { std::string s; s.push_back('\x11'); s.push_back('\x22'); s.push_back('\x33'); s.push_back('\x44'); s.push_back('\x55'); s.push_back('\x66'); s.push_back('\x77'); s.push_back('\x88'); s.push_back('\x99'); s.push_back('\xaa'); s.push_back('\xbb'); s.push_back('\xcc'); s.push_back('\xdd'); absl::string_view sp(s); HuffmanBitBuffer bb; sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_EQ(sp.size(), 5u); EXPECT_FALSE(bb.InputProperlyTerminated()); bb.ConsumeBits(15); EXPECT_EQ(bb.count(), 49u) << bb; EXPECT_EQ(bb.free_count(), 15u) << bb; HuffmanAccumulator expected(0x1122334455667788); expected <<= 15; EXPECT_EQ(bb.value(), expected); sp.remove_prefix(bb.AppendBytes(sp)); EXPECT_EQ(sp.size(), 4u); EXPECT_EQ(bb.count(), 57u) << bb; EXPECT_EQ(bb.free_count(), 7u) << bb; expected |= (HuffmanAccumulator(0x99) << 7); EXPECT_EQ(bb.value(), expected) << bb << std::hex << "\n actual: " << bb.value() << "\n expected: " << expected; } class HpackHuffmanDecoderTest : public RandomDecoderTest { protected: HpackHuffmanDecoderTest() { stop_decode_on_done_ = false; } DecodeStatus StartDecoding(DecodeBuffer* b) override { input_bytes_seen_ = 0; output_buffer_.clear(); decoder_.Reset(); return ResumeDecoding(b); } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { input_bytes_seen_ += b->Remaining(); absl::string_view sp(b->cursor(), b->Remaining()); if (decoder_.Decode(sp, &output_buffer_)) { b->AdvanceCursor(b->Remaining()); EXPECT_LE(input_bytes_seen_, input_bytes_expected_); if (input_bytes_expected_ == input_bytes_seen_) { if (decoder_.InputProperlyTerminated()) { return DecodeStatus::kDecodeDone; } else { return DecodeStatus::kDecodeError; } } return DecodeStatus::kDecodeInProgress; } return DecodeStatus::kDecodeError; } HpackHuffmanDecoder decoder_; std::string output_buffer_; size_t input_bytes_seen_; size_t input_bytes_expected_; }; TEST_F(HpackHuffmanDecoderTest, SpecRequestExamples) { HpackHuffmanDecoder decoder; std::string test_table[] = { "f1e3c2e5f23a6ba0ab90f4ff", "www.example.com", "a8eb10649cbf", "no-cache", "25a849e95ba97d7f", "custom-key", "25a849e95bb8e8b4bf", "custom-value", }; for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) { std::string huffman_encoded; ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded)); const std::string& plain_string(test_table[i + 1]); std::string buffer; decoder.Reset(); EXPECT_TRUE(decoder.Decode(huffman_encoded, &buffer)) << decoder; EXPECT_TRUE(decoder.InputProperlyTerminated()) << decoder; EXPECT_EQ(buffer, plain_string); } } TEST_F(HpackHuffmanDecoderTest, SpecResponseExamples) { HpackHuffmanDecoder decoder; std::string test_table[] = { "6402", "302", "aec3771a4b", "private", "d07abe941054d444a8200595040b8166e082a62d1bff", "Mon, 21 Oct 2013 20:13:21 GMT", "9d29ad171863c78f0b97c8e9ae82ae43d3", "https: "94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0" "03ed4ee5b1063d5007", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", }; for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) { std::string huffman_encoded; ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded)); const std::string& plain_string(test_table[i + 1]); std::string buffer; decoder.Reset(); EXPECT_TRUE(decoder.Decode(huffman_encoded, &buffer)) << decoder; EXPECT_TRUE(decoder.InputProperlyTerminated()) << decoder; EXPECT_EQ(buffer, plain_string); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/huffman/hpack_huffman_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/huffman/hpack_huffman_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
daee26e5-7dff-4070-9fef-3d31284ec703
cpp
google/quiche
hpack_example
quiche/http2/test_tools/hpack_example.cc
quiche/http2/test_tools/hpack_example_test.cc
#include "quiche/http2/test_tools/hpack_example.h" #include <ctype.h> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace test { namespace { void HpackExampleToStringOrDie(absl::string_view example, std::string* output) { while (!example.empty()) { const char c0 = example[0]; if (isxdigit(c0)) { QUICHE_CHECK_GT(example.size(), 1u) << "Truncated hex byte?"; const char c1 = example[1]; QUICHE_CHECK(isxdigit(c1)) << "Found half a byte?"; std::string byte; QUICHE_CHECK(absl::HexStringToBytes(example.substr(0, 2), &byte)) << "Can't parse hex byte"; absl::StrAppend(output, byte); example.remove_prefix(2); continue; } if (isspace(c0)) { example.remove_prefix(1); continue; } if (!example.empty() && example[0] == '|') { auto pos = example.find('\n'); if (pos == absl::string_view::npos) { break; } example.remove_prefix(pos + 1); continue; } QUICHE_BUG(http2_bug_107_1) << "Can't parse byte " << static_cast<int>(c0) << absl::StrCat(" (0x", absl::Hex(c0), ")") << "\nExample: " << example; } QUICHE_CHECK_LT(0u, output->size()) << "Example is empty."; } } std::string HpackExampleToStringOrDie(absl::string_view example) { std::string output; HpackExampleToStringOrDie(example, &output); return output; } } }
#include "quiche/http2/test_tools/hpack_example.h" #include <string> #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { TEST(HpackExampleToStringOrDie, GoodInput) { std::string bytes = HpackExampleToStringOrDie(R"( 40 | == Literal never indexed == | Blank lines are OK in example: 08 | Literal name (len = 8) 7061 7373 776f 7264 | password 06 | Literal value (len = 6) 7365 6372 6574 | secret | -> password: secret )"); const char kExpected[] = { 0x40, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, }; EXPECT_EQ(absl::string_view(kExpected, sizeof kExpected), bytes); } #ifdef GTEST_HAS_DEATH_TEST TEST(HpackExampleToStringOrDie, InvalidInput) { EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie("4"), "Truncated"); EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie("4x"), "half"); EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie(""), "empty"); } #endif } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/hpack_example.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/hpack_example_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
cdd18497-ae46-451d-92e5-af2e64562aff
cpp
google/quiche
hpack_block_collector
quiche/http2/test_tools/hpack_block_collector.cc
quiche/http2/hpack/decoder/hpack_block_collector_test.cc
#include "quiche/http2/test_tools/hpack_block_collector.h" #include <algorithm> #include <memory> #include <string> #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; namespace http2 { namespace test { HpackBlockCollector::HpackBlockCollector() = default; HpackBlockCollector::HpackBlockCollector(const HpackBlockCollector& other) : pending_entry_(other.pending_entry_), entries_(other.entries_) {} HpackBlockCollector::~HpackBlockCollector() = default; void HpackBlockCollector::OnIndexedHeader(size_t index) { pending_entry_.OnIndexedHeader(index); PushPendingEntry(); } void HpackBlockCollector::OnDynamicTableSizeUpdate(size_t size) { pending_entry_.OnDynamicTableSizeUpdate(size); PushPendingEntry(); } void HpackBlockCollector::OnStartLiteralHeader(HpackEntryType header_type, size_t maybe_name_index) { pending_entry_.OnStartLiteralHeader(header_type, maybe_name_index); } void HpackBlockCollector::OnNameStart(bool huffman_encoded, size_t len) { pending_entry_.OnNameStart(huffman_encoded, len); } void HpackBlockCollector::OnNameData(const char* data, size_t len) { pending_entry_.OnNameData(data, len); } void HpackBlockCollector::OnNameEnd() { pending_entry_.OnNameEnd(); } void HpackBlockCollector::OnValueStart(bool huffman_encoded, size_t len) { pending_entry_.OnValueStart(huffman_encoded, len); } void HpackBlockCollector::OnValueData(const char* data, size_t len) { pending_entry_.OnValueData(data, len); } void HpackBlockCollector::OnValueEnd() { pending_entry_.OnValueEnd(); PushPendingEntry(); } void HpackBlockCollector::PushPendingEntry() { EXPECT_TRUE(pending_entry_.IsComplete()); QUICHE_DVLOG(2) << "PushPendingEntry: " << pending_entry_; entries_.push_back(pending_entry_); EXPECT_TRUE(entries_.back().IsComplete()); pending_entry_.Clear(); } void HpackBlockCollector::Clear() { pending_entry_.Clear(); entries_.clear(); } void HpackBlockCollector::ExpectIndexedHeader(size_t index) { entries_.push_back( HpackEntryCollector(HpackEntryType::kIndexedHeader, index)); } void HpackBlockCollector::ExpectDynamicTableSizeUpdate(size_t size) { entries_.push_back( HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, size)); } void HpackBlockCollector::ExpectNameIndexAndLiteralValue( HpackEntryType type, size_t index, bool value_huffman, const std::string& value) { entries_.push_back(HpackEntryCollector(type, index, value_huffman, value)); } void HpackBlockCollector::ExpectLiteralNameAndValue(HpackEntryType type, bool name_huffman, const std::string& name, bool value_huffman, const std::string& value) { entries_.push_back( HpackEntryCollector(type, name_huffman, name, value_huffman, value)); } void HpackBlockCollector::ShuffleEntries(Http2Random* rng) { std::shuffle(entries_.begin(), entries_.end(), *rng); } void HpackBlockCollector::AppendToHpackBlockBuilder( HpackBlockBuilder* hbb) const { QUICHE_CHECK(IsNotPending()); for (const auto& entry : entries_) { entry.AppendToHpackBlockBuilder(hbb); } } AssertionResult HpackBlockCollector::ValidateSoleIndexedHeader( size_t ndx) const { HTTP2_VERIFY_TRUE(pending_entry_.IsClear()); HTTP2_VERIFY_EQ(1u, entries_.size()); HTTP2_VERIFY_TRUE(entries_.front().ValidateIndexedHeader(ndx)); return AssertionSuccess(); } AssertionResult HpackBlockCollector::ValidateSoleLiteralValueHeader( HpackEntryType expected_type, size_t expected_index, bool expected_value_huffman, absl::string_view expected_value) const { HTTP2_VERIFY_TRUE(pending_entry_.IsClear()); HTTP2_VERIFY_EQ(1u, entries_.size()); HTTP2_VERIFY_TRUE(entries_.front().ValidateLiteralValueHeader( expected_type, expected_index, expected_value_huffman, expected_value)); return AssertionSuccess(); } AssertionResult HpackBlockCollector::ValidateSoleLiteralNameValueHeader( HpackEntryType expected_type, bool expected_name_huffman, absl::string_view expected_name, bool expected_value_huffman, absl::string_view expected_value) const { HTTP2_VERIFY_TRUE(pending_entry_.IsClear()); HTTP2_VERIFY_EQ(1u, entries_.size()); HTTP2_VERIFY_TRUE(entries_.front().ValidateLiteralNameValueHeader( expected_type, expected_name_huffman, expected_name, expected_value_huffman, expected_value)); return AssertionSuccess(); } AssertionResult HpackBlockCollector::ValidateSoleDynamicTableSizeUpdate( size_t size) const { HTTP2_VERIFY_TRUE(pending_entry_.IsClear()); HTTP2_VERIFY_EQ(1u, entries_.size()); HTTP2_VERIFY_TRUE(entries_.front().ValidateDynamicTableSizeUpdate(size)); return AssertionSuccess(); } AssertionResult HpackBlockCollector::VerifyEq( const HpackBlockCollector& that) const { HTTP2_VERIFY_EQ(pending_entry_, that.pending_entry_); HTTP2_VERIFY_EQ(entries_, that.entries_); return AssertionSuccess(); } } }
#include "quiche/http2/test_tools/hpack_block_collector.h" #include <string> #include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { TEST(HpackBlockCollectorTest, Clear) { HpackBlockCollector collector; EXPECT_TRUE(collector.IsClear()); EXPECT_TRUE(collector.IsNotPending()); collector.OnIndexedHeader(234); EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsNotPending()); collector.Clear(); EXPECT_TRUE(collector.IsClear()); EXPECT_TRUE(collector.IsNotPending()); collector.OnDynamicTableSizeUpdate(0); EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsNotPending()); collector.Clear(); collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1); EXPECT_FALSE(collector.IsClear()); EXPECT_FALSE(collector.IsNotPending()); } TEST(HpackBlockCollectorTest, IndexedHeader) { HpackBlockCollector a; a.OnIndexedHeader(123); EXPECT_TRUE(a.ValidateSoleIndexedHeader(123)); HpackBlockCollector b; EXPECT_FALSE(a.VerifyEq(b)); b.OnIndexedHeader(1); EXPECT_TRUE(b.ValidateSoleIndexedHeader(1)); EXPECT_FALSE(a.VerifyEq(b)); b.Clear(); b.OnIndexedHeader(123); EXPECT_TRUE(a.VerifyEq(b)); b.OnIndexedHeader(234); EXPECT_FALSE(b.VerifyEq(a)); a.OnIndexedHeader(234); EXPECT_TRUE(b.VerifyEq(a)); std::string expected; { HpackBlockBuilder hbb; hbb.AppendIndexedHeader(123); hbb.AppendIndexedHeader(234); EXPECT_EQ(3u, hbb.size()); expected = hbb.buffer(); } std::string actual; { HpackBlockBuilder hbb; a.AppendToHpackBlockBuilder(&hbb); EXPECT_EQ(3u, hbb.size()); actual = hbb.buffer(); } EXPECT_EQ(expected, actual); } TEST(HpackBlockCollectorTest, DynamicTableSizeUpdate) { HpackBlockCollector a; a.OnDynamicTableSizeUpdate(0); EXPECT_TRUE(a.ValidateSoleDynamicTableSizeUpdate(0)); HpackBlockCollector b; EXPECT_FALSE(a.VerifyEq(b)); b.OnDynamicTableSizeUpdate(1); EXPECT_TRUE(b.ValidateSoleDynamicTableSizeUpdate(1)); EXPECT_FALSE(a.VerifyEq(b)); b.Clear(); b.OnDynamicTableSizeUpdate(0); EXPECT_TRUE(a.VerifyEq(b)); b.OnDynamicTableSizeUpdate(4096); EXPECT_FALSE(b.VerifyEq(a)); a.OnDynamicTableSizeUpdate(4096); EXPECT_TRUE(b.VerifyEq(a)); std::string expected; { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(0); hbb.AppendDynamicTableSizeUpdate(4096); EXPECT_EQ(4u, hbb.size()); expected = hbb.buffer(); } std::string actual; { HpackBlockBuilder hbb; a.AppendToHpackBlockBuilder(&hbb); EXPECT_EQ(4u, hbb.size()); actual = hbb.buffer(); } EXPECT_EQ(expected, actual); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/hpack_block_collector.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_block_collector_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
90cb12a6-a116-4867-b829-8f9408189ca5
cpp
google/quiche
random_decoder_test_base
quiche/http2/test_tools/random_decoder_test_base.cc
quiche/http2/test_tools/random_decoder_test_base_test.cc
#include "quiche/http2/test_tools/random_decoder_test_base.h" #include <stddef.h> #include <algorithm> #include <memory> #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; namespace http2 { namespace test { RandomDecoderTest::RandomDecoderTest() = default; bool RandomDecoderTest::StopDecodeOnDone() { return stop_decode_on_done_; } DecodeStatus RandomDecoderTest::DecodeSegments(DecodeBuffer* original, const SelectSize& select_size) { DecodeStatus status = DecodeStatus::kDecodeInProgress; bool first = true; QUICHE_VLOG(2) << "DecodeSegments: input size=" << original->Remaining(); while (first || original->HasData()) { size_t remaining = original->Remaining(); size_t size = std::min(remaining, select_size(first, original->Offset(), remaining)); DecodeBuffer db(original->cursor(), size); QUICHE_VLOG(2) << "Decoding " << size << " bytes of " << remaining << " remaining"; if (first) { first = false; status = StartDecoding(&db); } else { status = ResumeDecoding(&db); } if (db.Offset() == 0 && db.HasData() && status != DecodeStatus::kDecodeError) { ADD_FAILURE() << "Decoder didn't make any progress; db.FullSize=" << db.FullSize() << " original.Offset=" << original->Offset(); return DecodeStatus::kDecodeError; } original->AdvanceCursor(db.Offset()); switch (status) { case DecodeStatus::kDecodeDone: if (original->Empty() || StopDecodeOnDone()) { return DecodeStatus::kDecodeDone; } continue; case DecodeStatus::kDecodeInProgress: continue; case DecodeStatus::kDecodeError: return DecodeStatus::kDecodeError; } } return status; } AssertionResult RandomDecoderTest::DecodeAndValidateSeveralWays( DecodeBuffer* original, bool return_non_zero_on_first, const Validator& validator) { const uint32_t original_remaining = original->Remaining(); QUICHE_VLOG(1) << "DecodeAndValidateSeveralWays - Start, remaining = " << original_remaining; uint32_t first_consumed; { DecodeBuffer input(original->cursor(), original_remaining); QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectRemaining"; HTTP2_VERIFY_SUCCESS( DecodeSegmentsAndValidate(&input, SelectRemaining(), validator)) << "\nFailed with SelectRemaining; input.Offset=" << input.Offset() << "; input.Remaining=" << input.Remaining(); first_consumed = input.Offset(); } if (original_remaining <= 30) { DecodeBuffer input(original->cursor(), original_remaining); QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectOne"; HTTP2_VERIFY_SUCCESS( DecodeSegmentsAndValidate(&input, SelectOne(), validator)) << "\nFailed with SelectOne; input.Offset=" << input.Offset() << "; input.Remaining=" << input.Remaining(); HTTP2_VERIFY_EQ(first_consumed, input.Offset()) << "\nFailed with SelectOne"; } if (original_remaining <= 20) { DecodeBuffer input(original->cursor(), original_remaining); QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectZeroAndOne"; HTTP2_VERIFY_SUCCESS(DecodeSegmentsAndValidate( &input, SelectZeroAndOne(return_non_zero_on_first), validator)) << "\nFailed with SelectZeroAndOne"; HTTP2_VERIFY_EQ(first_consumed, input.Offset()) << "\nFailed with SelectZeroAndOne; input.Offset=" << input.Offset() << "; input.Remaining=" << input.Remaining(); } { DecodeBuffer input(original->cursor(), original_remaining); QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectRandom"; HTTP2_VERIFY_SUCCESS(DecodeSegmentsAndValidate( &input, SelectRandom(return_non_zero_on_first), validator)) << "\nFailed with SelectRandom; input.Offset=" << input.Offset() << "; input.Remaining=" << input.Remaining(); HTTP2_VERIFY_EQ(first_consumed, input.Offset()) << "\nFailed with SelectRandom"; } HTTP2_VERIFY_EQ(original_remaining, original->Remaining()); original->AdvanceCursor(first_consumed); QUICHE_VLOG(1) << "DecodeAndValidateSeveralWays - SUCCESS"; return ::testing::AssertionSuccess(); } RandomDecoderTest::SelectSize RandomDecoderTest::SelectZeroAndOne( bool return_non_zero_on_first) { std::shared_ptr<bool> zero_next(new bool); *zero_next = !return_non_zero_on_first; return [zero_next](bool , size_t , size_t ) -> size_t { if (*zero_next) { *zero_next = false; return 0; } else { *zero_next = true; return 1; } }; } RandomDecoderTest::SelectSize RandomDecoderTest::SelectRandom( bool return_non_zero_on_first) { return [this, return_non_zero_on_first](bool first, size_t , size_t remaining) -> size_t { uint32_t r = random_.Rand32(); if (first && return_non_zero_on_first) { QUICHE_CHECK_LT(0u, remaining); if (remaining == 1) { return 1; } return 1 + (r % remaining); } return r % (remaining + 1); }; } uint32_t RandomDecoderTest::RandStreamId() { return random_.Rand32() & StreamIdMask(); } } }
#include "quiche/http2/test_tools/random_decoder_test_base.h" #include <stddef.h> #include <functional> #include <ios> #include <set> #include <type_traits> #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_callbacks.h" namespace http2 { namespace test { namespace { const char kData[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; const bool kReturnNonZeroOnFirst = true; const bool kMayReturnZeroOnFirst = false; class RandomDecoderTestTest : public RandomDecoderTest { public: RandomDecoderTestTest() : data_db_(kData) { QUICHE_CHECK_EQ(sizeof kData, 8u); } protected: typedef quiche::MultiUseCallback<DecodeStatus(DecodeBuffer* db)> DecodingFn; DecodeStatus StartDecoding(DecodeBuffer* db) override { ++start_decoding_calls_; if (start_decoding_fn_) { return start_decoding_fn_(db); } return DecodeStatus::kDecodeError; } DecodeStatus ResumeDecoding(DecodeBuffer* db) override { ++resume_decoding_calls_; if (resume_decoding_fn_) { return resume_decoding_fn_(db); } return DecodeStatus::kDecodeError; } bool StopDecodeOnDone() override { ++stop_decode_on_done_calls_; if (override_stop_decode_on_done_) { return sub_stop_decode_on_done_; } return RandomDecoderTest::StopDecodeOnDone(); } size_t start_decoding_calls_ = 0; size_t resume_decoding_calls_ = 0; size_t stop_decode_on_done_calls_ = 0; DecodingFn start_decoding_fn_; DecodingFn resume_decoding_fn_; DecodeBuffer data_db_; bool sub_stop_decode_on_done_ = true; bool override_stop_decode_on_done_ = true; }; TEST_F(RandomDecoderTestTest, StopOnStartPartiallyDone) { start_decoding_fn_ = [this](DecodeBuffer* db) { EXPECT_EQ(1u, start_decoding_calls_); EXPECT_EQ(kData, db->cursor()); EXPECT_EQ(sizeof kData, db->Remaining()); db->DecodeUInt8(); return DecodeStatus::kDecodeDone; }; EXPECT_EQ(DecodeStatus::kDecodeDone, DecodeSegments(&data_db_, SelectRemaining())); EXPECT_EQ(1u, data_db_.Offset()); EXPECT_EQ(1u, start_decoding_calls_); EXPECT_EQ(0u, resume_decoding_calls_); EXPECT_EQ(1u, stop_decode_on_done_calls_); } TEST_F(RandomDecoderTestTest, StopOnResumePartiallyDone) { start_decoding_fn_ = [this](DecodeBuffer* db) { EXPECT_EQ(1u, start_decoding_calls_); db->DecodeUInt8(); return DecodeStatus::kDecodeInProgress; }; resume_decoding_fn_ = [this](DecodeBuffer* db) { EXPECT_EQ(1u, resume_decoding_calls_); EXPECT_EQ(data_db_.cursor(), db->cursor()); db->DecodeUInt16(); return DecodeStatus::kDecodeDone; }; override_stop_decode_on_done_ = false; stop_decode_on_done_ = true; EXPECT_EQ(DecodeStatus::kDecodeDone, DecodeSegments(&data_db_, SelectRemaining())); EXPECT_EQ(3u, data_db_.Offset()); EXPECT_EQ(1u, start_decoding_calls_); EXPECT_EQ(1u, resume_decoding_calls_); EXPECT_EQ(1u, stop_decode_on_done_calls_); } TEST_F(RandomDecoderTestTest, InProgressWhenEmpty) { start_decoding_fn_ = [this](DecodeBuffer* db) { EXPECT_EQ(1u, start_decoding_calls_); if (db->HasData()) { db->DecodeUInt8(); if (db->HasData()) { db->DecodeUInt8(); } } return DecodeStatus::kDecodeInProgress; }; resume_decoding_fn_ = [](DecodeBuffer* db) { if (db->HasData()) { db->AdvanceCursor(db->Remaining()); } return DecodeStatus::kDecodeInProgress; }; EXPECT_EQ(DecodeStatus::kDecodeInProgress, DecodeSegments(&data_db_, SelectRandom(kMayReturnZeroOnFirst))); EXPECT_TRUE(data_db_.Empty()); EXPECT_EQ(1u, start_decoding_calls_); EXPECT_LE(1u, resume_decoding_calls_); EXPECT_EQ(0u, stop_decode_on_done_calls_); } TEST_F(RandomDecoderTestTest, DoneExactlyAtEnd) { start_decoding_fn_ = [this](DecodeBuffer* db) { EXPECT_EQ(1u, start_decoding_calls_); EXPECT_EQ(1u, db->Remaining()); EXPECT_EQ(1u, db->FullSize()); db->DecodeUInt8(); return DecodeStatus::kDecodeInProgress; }; resume_decoding_fn_ = [this](DecodeBuffer* db) { EXPECT_EQ(1u, db->Remaining()); EXPECT_EQ(1u, db->FullSize()); db->DecodeUInt8(); if (data_db_.Remaining() == 1) { return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; }; override_stop_decode_on_done_ = true; sub_stop_decode_on_done_ = true; EXPECT_EQ(DecodeStatus::kDecodeDone, DecodeSegments(&data_db_, SelectOne())); EXPECT_EQ(0u, data_db_.Remaining()); EXPECT_EQ(1u, start_decoding_calls_); EXPECT_EQ((sizeof kData) - 1, resume_decoding_calls_); EXPECT_EQ(0u, stop_decode_on_done_calls_); } TEST_F(RandomDecoderTestTest, DecodeSeveralWaysToEnd) { size_t decoded_since_start = 0; auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) { decoded_since_start += db->Remaining(); db->AdvanceCursor(db->Remaining()); EXPECT_EQ(0u, db->Remaining()); if (decoded_since_start == data_db_.FullSize()) { return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; }; start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) { decoded_since_start = 0; return shared_fn(db); }; resume_decoding_fn_ = shared_fn; Validator validator = ValidateDoneAndEmpty(); EXPECT_TRUE(DecodeAndValidateSeveralWays(&data_db_, kMayReturnZeroOnFirst, validator)); EXPECT_EQ(0u, data_db_.Remaining()); EXPECT_EQ(4u, start_decoding_calls_); EXPECT_EQ(0u, stop_decode_on_done_calls_); } TEST_F(RandomDecoderTestTest, DecodeTwoWaysAndStopEarly) { size_t decoded_since_start = 0; auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) { uint32_t amount = db->Remaining(); if (start_decoding_calls_ == 2 && amount > 1) { amount = 1; } decoded_since_start += amount; db->AdvanceCursor(amount); if (decoded_since_start == data_db_.FullSize()) { return DecodeStatus::kDecodeDone; } if (decoded_since_start > 1 && start_decoding_calls_ == 2) { return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; }; start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) { decoded_since_start = 0; return shared_fn(db); }; resume_decoding_fn_ = shared_fn; Validator validator = [this](const DecodeBuffer& , DecodeStatus status) -> AssertionResult { if (start_decoding_calls_ <= 2 && status != DecodeStatus::kDecodeDone) { return ::testing::AssertionFailure() << "Expected DecodeStatus::kDecodeDone, not " << status; } if (start_decoding_calls_ > 2) { return ::testing::AssertionFailure() << "How did we get to pass " << start_decoding_calls_; } return ::testing::AssertionSuccess(); }; EXPECT_FALSE(DecodeAndValidateSeveralWays(&data_db_, kMayReturnZeroOnFirst, validator)); EXPECT_EQ(2u, start_decoding_calls_); EXPECT_EQ(1u, stop_decode_on_done_calls_); } TEST_F(RandomDecoderTestTest, DecodeThreeWaysAndError) { size_t decoded_since_start = 0; auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) { if (start_decoding_calls_ == 3 && decoded_since_start > 0) { return DecodeStatus::kDecodeError; } uint32_t amount = db->Remaining(); if (start_decoding_calls_ == 3 && amount > 1) { amount = 1; } decoded_since_start += amount; db->AdvanceCursor(amount); if (decoded_since_start == data_db_.FullSize()) { return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; }; start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) { decoded_since_start = 0; return shared_fn(db); }; resume_decoding_fn_ = shared_fn; Validator validator = ValidateDoneAndEmpty(); EXPECT_FALSE(DecodeAndValidateSeveralWays(&data_db_, kReturnNonZeroOnFirst, validator)); EXPECT_EQ(3u, start_decoding_calls_); EXPECT_EQ(0u, stop_decode_on_done_calls_); } TEST(CorruptEnumTest, ManyValues) { std::set<uint64_t> values; DecodeStatus status; QUICHE_LOG(INFO) << "sizeof status = " << sizeof status; Http2Random rng; for (int ndx = 0; ndx < 256; ++ndx) { CorruptEnum(&status, &rng); values.insert(static_cast<uint64_t>(status)); } } typedef typename std::underlying_type<DecodeStatus>::type DecodeStatusUT; struct CorruptEnumTestStruct { DecodeStatusUT filler1; DecodeStatus status; DecodeStatusUT filler2; }; TEST(CorruptEnumTest, CorruptsOnlyEnum) { Http2Random rng; for (const DecodeStatusUT filler : {DecodeStatusUT(), ~DecodeStatusUT()}) { QUICHE_LOG(INFO) << "filler=0x" << std::hex << filler; CorruptEnumTestStruct s; s.filler1 = filler; s.filler2 = filler; for (int ndx = 0; ndx < 256; ++ndx) { CorruptEnum(&s.status, &rng); EXPECT_EQ(s.filler1, filler); EXPECT_EQ(s.filler2, filler); } } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/random_decoder_test_base.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/random_decoder_test_base_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
457750a6-4192-455a-a546-396945d39be3
cpp
google/quiche
http2_frame_builder
quiche/http2/test_tools/http2_frame_builder.cc
quiche/http2/test_tools/http2_frame_builder_test.cc
#include "quiche/http2/test_tools/http2_frame_builder.h" #ifdef WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #include <netinet/in.h> #endif #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { Http2FrameBuilder::Http2FrameBuilder(Http2FrameType type, uint8_t flags, uint32_t stream_id) { AppendUInt24(0); Append(type); AppendUInt8(flags); AppendUInt31(stream_id); } Http2FrameBuilder::Http2FrameBuilder(const Http2FrameHeader& v) { Append(v); } void Http2FrameBuilder::Append(absl::string_view s) { absl::StrAppend(&buffer_, s); } void Http2FrameBuilder::AppendBytes(const void* data, uint32_t num_bytes) { Append(absl::string_view(static_cast<const char*>(data), num_bytes)); } void Http2FrameBuilder::AppendZeroes(size_t num_zero_bytes) { char zero = 0; buffer_.append(num_zero_bytes, zero); } void Http2FrameBuilder::AppendUInt8(uint8_t value) { AppendBytes(&value, 1); } void Http2FrameBuilder::AppendUInt16(uint16_t value) { value = htons(value); AppendBytes(&value, 2); } void Http2FrameBuilder::AppendUInt24(uint32_t value) { EXPECT_EQ(value, value & 0xffffff); value = htonl(value); AppendBytes(reinterpret_cast<char*>(&value) + 1, 3); } void Http2FrameBuilder::AppendUInt31(uint32_t value) { uint32_t tmp = value & StreamIdMask(); EXPECT_EQ(value, value & StreamIdMask()) << "High-bit of uint32_t should be clear."; value = htonl(tmp); AppendBytes(&value, 4); } void Http2FrameBuilder::AppendUInt32(uint32_t value) { value = htonl(value); AppendBytes(&value, sizeof(value)); } void Http2FrameBuilder::Append(Http2ErrorCode error_code) { AppendUInt32(static_cast<uint32_t>(error_code)); } void Http2FrameBuilder::Append(Http2FrameType type) { AppendUInt8(static_cast<uint8_t>(type)); } void Http2FrameBuilder::Append(Http2SettingsParameter parameter) { AppendUInt16(static_cast<uint16_t>(parameter)); } void Http2FrameBuilder::Append(const Http2FrameHeader& v) { AppendUInt24(v.payload_length); Append(v.type); AppendUInt8(v.flags); AppendUInt31(v.stream_id); } void Http2FrameBuilder::Append(const Http2PriorityFields& v) { uint32_t tmp = v.stream_dependency & StreamIdMask(); EXPECT_EQ(tmp, v.stream_dependency); if (v.is_exclusive) { tmp |= 0x80000000; } AppendUInt32(tmp); ASSERT_LE(1u, v.weight); ASSERT_LE(v.weight, 256u); AppendUInt8(v.weight - 1); } void Http2FrameBuilder::Append(const Http2RstStreamFields& v) { Append(v.error_code); } void Http2FrameBuilder::Append(const Http2SettingFields& v) { Append(v.parameter); AppendUInt32(v.value); } void Http2FrameBuilder::Append(const Http2PushPromiseFields& v) { AppendUInt31(v.promised_stream_id); } void Http2FrameBuilder::Append(const Http2PingFields& v) { AppendBytes(v.opaque_bytes, sizeof Http2PingFields::opaque_bytes); } void Http2FrameBuilder::Append(const Http2GoAwayFields& v) { AppendUInt31(v.last_stream_id); Append(v.error_code); } void Http2FrameBuilder::Append(const Http2WindowUpdateFields& v) { EXPECT_NE(0u, v.window_size_increment) << "Increment must be non-zero."; AppendUInt31(v.window_size_increment); } void Http2FrameBuilder::Append(const Http2AltSvcFields& v) { AppendUInt16(v.origin_length); } void Http2FrameBuilder::Append(const Http2PriorityUpdateFields& v) { AppendUInt31(v.prioritized_stream_id); } void Http2FrameBuilder::WriteAt(absl::string_view s, size_t offset) { ASSERT_LE(offset, buffer_.size()); size_t len = offset + s.size(); if (len > buffer_.size()) { buffer_.resize(len); } for (size_t ndx = 0; ndx < s.size(); ++ndx) { buffer_[offset + ndx] = s[ndx]; } } void Http2FrameBuilder::WriteBytesAt(const void* data, uint32_t num_bytes, size_t offset) { WriteAt(absl::string_view(static_cast<const char*>(data), num_bytes), offset); } void Http2FrameBuilder::WriteUInt24At(uint32_t value, size_t offset) { ASSERT_LT(value, static_cast<uint32_t>(1 << 24)); value = htonl(value); WriteBytesAt(reinterpret_cast<char*>(&value) + 1, sizeof(value) - 1, offset); } void Http2FrameBuilder::SetPayloadLength(uint32_t payload_length) { WriteUInt24At(payload_length, 0); } size_t Http2FrameBuilder::SetPayloadLength() { EXPECT_GE(size(), Http2FrameHeader::EncodedSize()); uint32_t payload_length = size() - Http2FrameHeader::EncodedSize(); SetPayloadLength(payload_length); return payload_length; } } }
#include "quiche/http2/test_tools/http2_frame_builder.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { const char kHighBitSetMsg[] = "High-bit of uint32_t should be clear"; TEST(Http2FrameBuilderTest, Constructors) { { Http2FrameBuilder fb; EXPECT_EQ(0u, fb.size()); } { Http2FrameBuilder fb(Http2FrameType::DATA, 0, 123); EXPECT_EQ(9u, fb.size()); std::string expected_data; ASSERT_TRUE( absl::HexStringToBytes("000000" "00" "00" "0000007b", &expected_data)); EXPECT_EQ(expected_data, fb.buffer()); } { Http2FrameHeader header; header.payload_length = (1 << 24) - 1; header.type = Http2FrameType::HEADERS; header.flags = Http2FrameFlag::END_HEADERS; header.stream_id = StreamIdMask(); Http2FrameBuilder fb(header); EXPECT_EQ(9u, fb.size()); std::string expected_data; ASSERT_TRUE(absl::HexStringToBytes( "ffffff" "01" "04" "7fffffff", &expected_data)); EXPECT_EQ(expected_data, fb.buffer()); } } TEST(Http2FrameBuilderTest, SetPayloadLength) { Http2FrameBuilder fb(Http2FrameType::DATA, PADDED, 20000); EXPECT_EQ(9u, fb.size()); fb.AppendUInt8(50); EXPECT_EQ(10u, fb.size()); fb.Append("ten bytes."); EXPECT_EQ(20u, fb.size()); fb.AppendZeroes(50); EXPECT_EQ(70u, fb.size()); fb.SetPayloadLength(); EXPECT_EQ(70u, fb.size()); std::string expected_data; ASSERT_TRUE( absl::HexStringToBytes("00003d" "00" "08" "00004e20" "32" "74656e2062797465732e" "00000000000000000000" "00000000000000000000" "00000000000000000000" "00000000000000000000" "00000000000000000000", &expected_data)); EXPECT_EQ(expected_data, fb.buffer()); } TEST(Http2FrameBuilderTest, Settings) { Http2FrameBuilder fb(Http2FrameType::SETTINGS, 0, 0); Http2SettingFields sf; sf.parameter = Http2SettingsParameter::HEADER_TABLE_SIZE; sf.value = 1 << 12; fb.Append(sf); sf.parameter = Http2SettingsParameter::ENABLE_PUSH; sf.value = 0; fb.Append(sf); sf.parameter = Http2SettingsParameter::MAX_CONCURRENT_STREAMS; sf.value = ~0; fb.Append(sf); sf.parameter = Http2SettingsParameter::INITIAL_WINDOW_SIZE; sf.value = 1 << 16; fb.Append(sf); sf.parameter = Http2SettingsParameter::MAX_FRAME_SIZE; sf.value = 1 << 14; fb.Append(sf); sf.parameter = Http2SettingsParameter::MAX_HEADER_LIST_SIZE; sf.value = 1 << 10; fb.Append(sf); size_t payload_size = 6 * Http2SettingFields::EncodedSize(); EXPECT_EQ(Http2FrameHeader::EncodedSize() + payload_size, fb.size()); fb.SetPayloadLength(payload_size); std::string expected_data; ASSERT_TRUE( absl::HexStringToBytes("000024" "04" "00" "00000000" "0001" "00001000" "0002" "00000000" "0003" "ffffffff" "0004" "00010000" "0005" "00004000" "0006" "00000400", &expected_data)); EXPECT_EQ(expected_data, fb.buffer()); } TEST(Http2FrameBuilderTest, EnhanceYourCalm) { std::string expected_data; ASSERT_TRUE(absl::HexStringToBytes("0000000b", &expected_data)); { Http2FrameBuilder fb; fb.Append(Http2ErrorCode::ENHANCE_YOUR_CALM); EXPECT_EQ(expected_data, fb.buffer()); } { Http2FrameBuilder fb; Http2RstStreamFields rsp; rsp.error_code = Http2ErrorCode::ENHANCE_YOUR_CALM; fb.Append(rsp); EXPECT_EQ(expected_data, fb.buffer()); } } TEST(Http2FrameBuilderTest, PushPromise) { std::string expected_data; ASSERT_TRUE(absl::HexStringToBytes("7fffffff", &expected_data)); { Http2FrameBuilder fb; fb.Append(Http2PushPromiseFields{0x7fffffff}); EXPECT_EQ(expected_data, fb.buffer()); } { Http2FrameBuilder fb; EXPECT_NONFATAL_FAILURE(fb.Append(Http2PushPromiseFields{0xffffffff}), kHighBitSetMsg); EXPECT_EQ(expected_data, fb.buffer()); } } TEST(Http2FrameBuilderTest, Ping) { Http2FrameBuilder fb; Http2PingFields ping{"8 bytes"}; fb.Append(ping); const absl::string_view kData{"8 bytes\0", 8}; EXPECT_EQ(kData.size(), Http2PingFields::EncodedSize()); EXPECT_EQ(kData, fb.buffer()); } TEST(Http2FrameBuilderTest, GoAway) { std::string expected_data; ASSERT_TRUE( absl::HexStringToBytes("12345678" "00000001", &expected_data)); EXPECT_EQ(expected_data.size(), Http2GoAwayFields::EncodedSize()); { Http2FrameBuilder fb; Http2GoAwayFields ga(0x12345678, Http2ErrorCode::PROTOCOL_ERROR); fb.Append(ga); EXPECT_EQ(expected_data, fb.buffer()); } { Http2FrameBuilder fb; Http2GoAwayFields ga(0x92345678, Http2ErrorCode::PROTOCOL_ERROR); EXPECT_NONFATAL_FAILURE(fb.Append(ga), kHighBitSetMsg); EXPECT_EQ(expected_data, fb.buffer()); } } TEST(Http2FrameBuilderTest, WindowUpdate) { Http2FrameBuilder fb; fb.Append(Http2WindowUpdateFields{123456}); EXPECT_NONFATAL_FAILURE(fb.Append(Http2WindowUpdateFields{0x80000001}), kHighBitSetMsg); EXPECT_NONFATAL_FAILURE(fb.Append(Http2WindowUpdateFields{0}), "non-zero"); std::string expected_data; ASSERT_TRUE( absl::HexStringToBytes("0001e240" "00000001" "00000000", &expected_data)); EXPECT_EQ(expected_data.size(), 3 * Http2WindowUpdateFields::EncodedSize()); EXPECT_EQ(expected_data, fb.buffer()); } TEST(Http2FrameBuilderTest, AltSvc) { Http2FrameBuilder fb; fb.Append(Http2AltSvcFields{99}); fb.Append(Http2AltSvcFields{0}); std::string expected_data; ASSERT_TRUE( absl::HexStringToBytes("0063" "0000", &expected_data)); EXPECT_EQ(expected_data.size(), 2 * Http2AltSvcFields::EncodedSize()); EXPECT_EQ(expected_data, fb.buffer()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/http2_frame_builder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/http2_frame_builder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
518e59a4-3440-4e8e-8be3-93932fb4ac2c
cpp
google/quiche
hpack_block_builder
quiche/http2/test_tools/hpack_block_builder.cc
quiche/http2/test_tools/hpack_block_builder_test.cc
#include "quiche/http2/test_tools/hpack_block_builder.h" #include "quiche/http2/hpack/varint/hpack_varint_encoder.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { void HpackBlockBuilder::AppendHighBitsAndVarint(uint8_t high_bits, uint8_t prefix_length, uint64_t varint) { EXPECT_LE(3, prefix_length); EXPECT_LE(prefix_length, 8); HpackVarintEncoder::Encode(high_bits, prefix_length, varint, &buffer_); } void HpackBlockBuilder::AppendEntryTypeAndVarint(HpackEntryType entry_type, uint64_t varint) { uint8_t high_bits; uint8_t prefix_length; switch (entry_type) { case HpackEntryType::kIndexedHeader: high_bits = 0x80; prefix_length = 7; break; case HpackEntryType::kDynamicTableSizeUpdate: high_bits = 0x20; prefix_length = 5; break; case HpackEntryType::kIndexedLiteralHeader: high_bits = 0x40; prefix_length = 6; break; case HpackEntryType::kUnindexedLiteralHeader: high_bits = 0x00; prefix_length = 4; break; case HpackEntryType::kNeverIndexedLiteralHeader: high_bits = 0x10; prefix_length = 4; break; default: QUICHE_BUG(http2_bug_110_1) << "Unreached, entry_type=" << entry_type; high_bits = 0; prefix_length = 0; break; } AppendHighBitsAndVarint(high_bits, prefix_length, varint); } void HpackBlockBuilder::AppendString(bool is_huffman_encoded, absl::string_view str) { uint8_t high_bits = is_huffman_encoded ? 0x80 : 0; uint8_t prefix_length = 7; AppendHighBitsAndVarint(high_bits, prefix_length, str.size()); buffer_.append(str.data(), str.size()); } } }
#include "quiche/http2/test_tools/hpack_block_builder.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { const bool kUncompressed = false; const bool kCompressed = true; const uint32_t kStaticTableMethodGET = 2; const uint32_t kStaticTablePathSlash = 4; const uint32_t kStaticTableSchemeHttp = 6; TEST(HpackBlockBuilderTest, ExamplesFromSpecC2) { { HpackBlockBuilder b; b.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, kUncompressed, "custom-key", kUncompressed, "custom-header"); EXPECT_EQ(26u, b.size()); const char kExpected[] = "\x40" "\x0a" "custom-key" "\x0d" "custom-header"; EXPECT_EQ(kExpected, b.buffer()); } { HpackBlockBuilder b; b.AppendNameIndexAndLiteralValue(HpackEntryType::kUnindexedLiteralHeader, 4, kUncompressed, "/sample/path"); EXPECT_EQ(14u, b.size()); const char kExpected[] = "\x04" "\x0c" "/sample/path"; EXPECT_EQ(kExpected, b.buffer()); } { HpackBlockBuilder b; b.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, kUncompressed, "password", kUncompressed, "secret"); EXPECT_EQ(17u, b.size()); const char kExpected[] = "\x10" "\x08" "password" "\x06" "secret"; EXPECT_EQ(kExpected, b.buffer()); } { HpackBlockBuilder b; b.AppendIndexedHeader(2); EXPECT_EQ(1u, b.size()); const char kExpected[] = "\x82"; EXPECT_EQ(kExpected, b.buffer()); } } TEST(HpackBlockBuilderTest, ExamplesFromSpecC3) { { HpackBlockBuilder b; b.AppendIndexedHeader(2); b.AppendIndexedHeader(6); b.AppendIndexedHeader(4); b.AppendNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 1, kUncompressed, "www.example.com"); EXPECT_EQ(20u, b.size()); std::string expected; ASSERT_TRUE(absl::HexStringToBytes( "828684410f7777772e6578616d706c652e636f6d", &expected)); EXPECT_EQ(expected, b.buffer()); } } TEST(HpackBlockBuilderTest, ExamplesFromSpecC4) { { HpackBlockBuilder b; b.AppendIndexedHeader(kStaticTableMethodGET); b.AppendIndexedHeader(kStaticTableSchemeHttp); b.AppendIndexedHeader(kStaticTablePathSlash); const char kHuffmanWwwExampleCom[] = {'\xf1', '\xe3', '\xc2', '\xe5', '\xf2', '\x3a', '\x6b', '\xa0', '\xab', '\x90', '\xf4', '\xff'}; b.AppendNameIndexAndLiteralValue( HpackEntryType::kIndexedLiteralHeader, 1, kCompressed, absl::string_view(kHuffmanWwwExampleCom, sizeof kHuffmanWwwExampleCom)); EXPECT_EQ(17u, b.size()); std::string expected; ASSERT_TRUE(absl::HexStringToBytes("828684418cf1e3c2e5f23a6ba0ab90f4ff", &expected)); EXPECT_EQ(expected, b.buffer()); } } TEST(HpackBlockBuilderTest, DynamicTableSizeUpdate) { { HpackBlockBuilder b; b.AppendDynamicTableSizeUpdate(0); EXPECT_EQ(1u, b.size()); const char kData[] = {'\x20'}; absl::string_view expected(kData, sizeof kData); EXPECT_EQ(expected, b.buffer()); } { HpackBlockBuilder b; b.AppendDynamicTableSizeUpdate(4096); EXPECT_EQ(3u, b.size()); const char kData[] = {'\x3f', '\xe1', '\x1f'}; absl::string_view expected(kData, sizeof kData); EXPECT_EQ(expected, b.buffer()); } { HpackBlockBuilder b; b.AppendDynamicTableSizeUpdate(1000000000000); EXPECT_EQ(7u, b.size()); const char kData[] = {'\x3f', '\xe1', '\x9f', '\x94', '\xa5', '\x8d', '\x1d'}; absl::string_view expected(kData, sizeof kData); EXPECT_EQ(expected, b.buffer()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/hpack_block_builder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/hpack_block_builder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
03c00856-6e35-4f2e-b332-aac4d8d0f3c6
cpp
google/quiche
http2_random
quiche/http2/test_tools/http2_random.cc
quiche/http2/test_tools/http2_random_test.cc
#include "quiche/http2/test_tools/http2_random.h" #include <string> #include "absl/strings/escaping.h" #include "openssl/chacha.h" #include "openssl/rand.h" #include "quiche/common/platform/api/quiche_logging.h" static const uint8_t kZeroNonce[12] = {0}; namespace http2 { namespace test { Http2Random::Http2Random() { RAND_bytes(key_, sizeof(key_)); QUICHE_LOG(INFO) << "Initialized test RNG with the following key: " << Key(); } Http2Random::Http2Random(absl::string_view key) { std::string decoded_key = absl::HexStringToBytes(key); QUICHE_CHECK_EQ(sizeof(key_), decoded_key.size()); memcpy(key_, decoded_key.data(), sizeof(key_)); } std::string Http2Random::Key() const { return absl::BytesToHexString( absl::string_view(reinterpret_cast<const char*>(key_), sizeof(key_))); } void Http2Random::FillRandom(void* buffer, size_t buffer_size) { memset(buffer, 0, buffer_size); uint8_t* buffer_u8 = reinterpret_cast<uint8_t*>(buffer); CRYPTO_chacha_20(buffer_u8, buffer_u8, buffer_size, key_, kZeroNonce, counter_++); } std::string Http2Random::RandString(int length) { std::string result; result.resize(length); FillRandom(&result[0], length); return result; } uint64_t Http2Random::Rand64() { union { uint64_t number; uint8_t bytes[sizeof(uint64_t)]; } result; FillRandom(result.bytes, sizeof(result.bytes)); return result.number; } double Http2Random::RandDouble() { union { double f; uint64_t i; } value; value.i = (1023ull << 52ull) | (Rand64() & 0xfffffffffffffu); return value.f - 1.0; } std::string Http2Random::RandStringWithAlphabet(int length, absl::string_view alphabet) { std::string result; result.resize(length); for (int i = 0; i < length; i++) { result[i] = alphabet[Uniform(alphabet.size())]; } return result; } } }
#include "quiche/http2/test_tools/http2_random.h" #include <algorithm> #include <set> #include <string> #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { TEST(Http2RandomTest, ProducesDifferentNumbers) { Http2Random random; uint64_t value1 = random.Rand64(); uint64_t value2 = random.Rand64(); uint64_t value3 = random.Rand64(); EXPECT_NE(value1, value2); EXPECT_NE(value2, value3); EXPECT_NE(value3, value1); } TEST(Http2RandomTest, StartsWithDifferentKeys) { Http2Random random1; Http2Random random2; EXPECT_NE(random1.Key(), random2.Key()); EXPECT_NE(random1.Rand64(), random2.Rand64()); EXPECT_NE(random1.Rand64(), random2.Rand64()); EXPECT_NE(random1.Rand64(), random2.Rand64()); } TEST(Http2RandomTest, ReproducibleRandom) { Http2Random random; uint64_t value1 = random.Rand64(); uint64_t value2 = random.Rand64(); Http2Random clone_random(random.Key()); EXPECT_EQ(clone_random.Key(), random.Key()); EXPECT_EQ(value1, clone_random.Rand64()); EXPECT_EQ(value2, clone_random.Rand64()); } TEST(Http2RandomTest, STLShuffle) { Http2Random random; const std::string original = "abcdefghijklmonpqrsuvwxyz"; std::string shuffled = original; std::shuffle(shuffled.begin(), shuffled.end(), random); EXPECT_NE(original, shuffled); } TEST(Http2RandomTest, RandFloat) { Http2Random random; for (int i = 0; i < 10000; i++) { float value = random.RandFloat(); ASSERT_GE(value, 0.f); ASSERT_LE(value, 1.f); } } TEST(Http2RandomTest, RandStringWithAlphabet) { Http2Random random; std::string str = random.RandStringWithAlphabet(1000, "xyz"); EXPECT_EQ(1000u, str.size()); std::set<char> characters(str.begin(), str.end()); EXPECT_THAT(characters, testing::ElementsAre('x', 'y', 'z')); } TEST(Http2RandomTest, SkewedLow) { Http2Random random; constexpr size_t kMax = 1234; for (int i = 0; i < 10000; i++) { size_t value = random.RandomSizeSkewedLow(kMax); ASSERT_GE(value, 0u); ASSERT_LE(value, kMax); } } TEST(Http2RandomTest, SkewedLowFullRange) { Http2Random random; std::set<size_t> values; for (int i = 0; i < 1000; i++) { values.insert(random.RandomSizeSkewedLow(3)); } EXPECT_THAT(values, testing::ElementsAre(0, 1, 2, 3)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/http2_random.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/http2_random_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
801caa50-fb76-4a49-b918-3cf9f7903458
cpp
google/quiche
hpack_entry_collector
quiche/http2/test_tools/hpack_entry_collector.cc
quiche/http2/hpack/decoder/hpack_entry_collector_test.cc
#include "quiche/http2/test_tools/hpack_entry_collector.h" #include <ostream> #include <string> #include "absl/strings/str_cat.h" #include "quiche/http2/hpack/http2_hpack_constants.h" #include "quiche/http2/test_tools/hpack_string_collector.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; namespace http2 { namespace test { namespace { const HpackEntryType kInvalidHeaderType = static_cast<HpackEntryType>(99); const size_t kInvalidIndex = 99999999; } HpackEntryCollector::HpackEntryCollector() { Clear(); } HpackEntryCollector::HpackEntryCollector(const HpackEntryCollector& other) = default; HpackEntryCollector::HpackEntryCollector(HpackEntryType type, size_t index_or_size) : header_type_(type), index_(index_or_size), started_(true), ended_(true) {} HpackEntryCollector::HpackEntryCollector(HpackEntryType type, size_t index, bool value_huffman, const std::string& value) : header_type_(type), index_(index), value_(value, value_huffman), started_(true), ended_(true) {} HpackEntryCollector::HpackEntryCollector(HpackEntryType type, bool name_huffman, const std::string& name, bool value_huffman, const std::string& value) : header_type_(type), index_(0), name_(name, name_huffman), value_(value, value_huffman), started_(true), ended_(true) {} HpackEntryCollector::~HpackEntryCollector() = default; void HpackEntryCollector::OnIndexedHeader(size_t index) { ASSERT_FALSE(started_); ASSERT_TRUE(IsClear()) << ToString(); Init(HpackEntryType::kIndexedHeader, index); ended_ = true; } void HpackEntryCollector::OnStartLiteralHeader(HpackEntryType header_type, size_t maybe_name_index) { ASSERT_FALSE(started_); ASSERT_TRUE(IsClear()) << ToString(); Init(header_type, maybe_name_index); } void HpackEntryCollector::OnNameStart(bool huffman_encoded, size_t len) { ASSERT_TRUE(started_); ASSERT_FALSE(ended_); ASSERT_FALSE(IsClear()); ASSERT_TRUE(LiteralNameExpected()) << ToString(); name_.OnStringStart(huffman_encoded, len); } void HpackEntryCollector::OnNameData(const char* data, size_t len) { ASSERT_TRUE(started_); ASSERT_FALSE(ended_); ASSERT_TRUE(LiteralNameExpected()) << ToString(); ASSERT_TRUE(name_.IsInProgress()); name_.OnStringData(data, len); } void HpackEntryCollector::OnNameEnd() { ASSERT_TRUE(started_); ASSERT_FALSE(ended_); ASSERT_TRUE(LiteralNameExpected()) << ToString(); ASSERT_TRUE(name_.IsInProgress()); name_.OnStringEnd(); } void HpackEntryCollector::OnValueStart(bool huffman_encoded, size_t len) { ASSERT_TRUE(started_); ASSERT_FALSE(ended_); if (LiteralNameExpected()) { ASSERT_TRUE(name_.HasEnded()); } ASSERT_TRUE(LiteralValueExpected()) << ToString(); ASSERT_TRUE(value_.IsClear()) << value_.ToString(); value_.OnStringStart(huffman_encoded, len); } void HpackEntryCollector::OnValueData(const char* data, size_t len) { ASSERT_TRUE(started_); ASSERT_FALSE(ended_); ASSERT_TRUE(LiteralValueExpected()) << ToString(); ASSERT_TRUE(value_.IsInProgress()); value_.OnStringData(data, len); } void HpackEntryCollector::OnValueEnd() { ASSERT_TRUE(started_); ASSERT_FALSE(ended_); ASSERT_TRUE(LiteralValueExpected()) << ToString(); ASSERT_TRUE(value_.IsInProgress()); value_.OnStringEnd(); ended_ = true; } void HpackEntryCollector::OnDynamicTableSizeUpdate(size_t size) { ASSERT_FALSE(started_); ASSERT_TRUE(IsClear()) << ToString(); Init(HpackEntryType::kDynamicTableSizeUpdate, size); ended_ = true; } void HpackEntryCollector::Clear() { header_type_ = kInvalidHeaderType; index_ = kInvalidIndex; name_.Clear(); value_.Clear(); started_ = ended_ = false; } bool HpackEntryCollector::IsClear() const { return header_type_ == kInvalidHeaderType && index_ == kInvalidIndex && name_.IsClear() && value_.IsClear() && !started_ && !ended_; } bool HpackEntryCollector::IsComplete() const { return started_ && ended_; } bool HpackEntryCollector::LiteralNameExpected() const { switch (header_type_) { case HpackEntryType::kIndexedLiteralHeader: case HpackEntryType::kUnindexedLiteralHeader: case HpackEntryType::kNeverIndexedLiteralHeader: return index_ == 0; default: return false; } } bool HpackEntryCollector::LiteralValueExpected() const { switch (header_type_) { case HpackEntryType::kIndexedLiteralHeader: case HpackEntryType::kUnindexedLiteralHeader: case HpackEntryType::kNeverIndexedLiteralHeader: return true; default: return false; } } AssertionResult HpackEntryCollector::ValidateIndexedHeader( size_t expected_index) const { HTTP2_VERIFY_TRUE(started_); HTTP2_VERIFY_TRUE(ended_); HTTP2_VERIFY_EQ(HpackEntryType::kIndexedHeader, header_type_); HTTP2_VERIFY_EQ(expected_index, index_); return ::testing::AssertionSuccess(); } AssertionResult HpackEntryCollector::ValidateLiteralValueHeader( HpackEntryType expected_type, size_t expected_index, bool expected_value_huffman, absl::string_view expected_value) const { HTTP2_VERIFY_TRUE(started_); HTTP2_VERIFY_TRUE(ended_); HTTP2_VERIFY_EQ(expected_type, header_type_); HTTP2_VERIFY_NE(0u, expected_index); HTTP2_VERIFY_EQ(expected_index, index_); HTTP2_VERIFY_TRUE(name_.IsClear()); HTTP2_VERIFY_SUCCESS( value_.Collected(expected_value, expected_value_huffman)); return ::testing::AssertionSuccess(); } AssertionResult HpackEntryCollector::ValidateLiteralNameValueHeader( HpackEntryType expected_type, bool expected_name_huffman, absl::string_view expected_name, bool expected_value_huffman, absl::string_view expected_value) const { HTTP2_VERIFY_TRUE(started_); HTTP2_VERIFY_TRUE(ended_); HTTP2_VERIFY_EQ(expected_type, header_type_); HTTP2_VERIFY_EQ(0u, index_); HTTP2_VERIFY_SUCCESS(name_.Collected(expected_name, expected_name_huffman)); HTTP2_VERIFY_SUCCESS( value_.Collected(expected_value, expected_value_huffman)); return ::testing::AssertionSuccess(); } AssertionResult HpackEntryCollector::ValidateDynamicTableSizeUpdate( size_t size) const { HTTP2_VERIFY_TRUE(started_); HTTP2_VERIFY_TRUE(ended_); HTTP2_VERIFY_EQ(HpackEntryType::kDynamicTableSizeUpdate, header_type_); HTTP2_VERIFY_EQ(index_, size); return ::testing::AssertionSuccess(); } void HpackEntryCollector::AppendToHpackBlockBuilder( HpackBlockBuilder* hbb) const { ASSERT_TRUE(started_ && ended_) << *this; switch (header_type_) { case HpackEntryType::kIndexedHeader: hbb->AppendIndexedHeader(index_); return; case HpackEntryType::kDynamicTableSizeUpdate: hbb->AppendDynamicTableSizeUpdate(index_); return; case HpackEntryType::kIndexedLiteralHeader: case HpackEntryType::kUnindexedLiteralHeader: case HpackEntryType::kNeverIndexedLiteralHeader: ASSERT_TRUE(value_.HasEnded()) << *this; if (index_ != 0) { QUICHE_CHECK(name_.IsClear()); hbb->AppendNameIndexAndLiteralValue(header_type_, index_, value_.huffman_encoded, value_.s); } else { QUICHE_CHECK(name_.HasEnded()) << *this; hbb->AppendLiteralNameAndValue(header_type_, name_.huffman_encoded, name_.s, value_.huffman_encoded, value_.s); } return; default: ADD_FAILURE() << *this; } } std::string HpackEntryCollector::ToString() const { std::string result("Type="); switch (header_type_) { case HpackEntryType::kIndexedHeader: result += "IndexedHeader"; break; case HpackEntryType::kDynamicTableSizeUpdate: result += "DynamicTableSizeUpdate"; break; case HpackEntryType::kIndexedLiteralHeader: result += "IndexedLiteralHeader"; break; case HpackEntryType::kUnindexedLiteralHeader: result += "UnindexedLiteralHeader"; break; case HpackEntryType::kNeverIndexedLiteralHeader: result += "NeverIndexedLiteralHeader"; break; default: if (header_type_ == kInvalidHeaderType) { result += "<unset>"; } else { absl::StrAppend(&result, header_type_); } } if (index_ != 0) { absl::StrAppend(&result, " Index=", index_); } if (!name_.IsClear()) { absl::StrAppend(&result, " Name", name_.ToString()); } if (!value_.IsClear()) { absl::StrAppend(&result, " Value", value_.ToString()); } if (!started_) { EXPECT_FALSE(ended_); absl::StrAppend(&result, " !started"); } else if (!ended_) { absl::StrAppend(&result, " !ended"); } else { absl::StrAppend(&result, " Complete"); } return result; } void HpackEntryCollector::Init(HpackEntryType type, size_t maybe_index) { ASSERT_TRUE(IsClear()) << ToString(); header_type_ = type; index_ = maybe_index; started_ = true; } bool operator==(const HpackEntryCollector& a, const HpackEntryCollector& b) { return a.name() == b.name() && a.value() == b.value() && a.index() == b.index() && a.header_type() == b.header_type() && a.started() == b.started() && a.ended() == b.ended(); } bool operator!=(const HpackEntryCollector& a, const HpackEntryCollector& b) { return !(a == b); } std::ostream& operator<<(std::ostream& out, const HpackEntryCollector& v) { return out << v.ToString(); } } }
#include "quiche/http2/test_tools/hpack_entry_collector.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::HasSubstr; namespace http2 { namespace test { namespace { TEST(HpackEntryCollectorTest, Clear) { HpackEntryCollector collector; QUICHE_VLOG(1) << collector; EXPECT_THAT(collector.ToString(), HasSubstr("!started")); EXPECT_TRUE(collector.IsClear()); collector.set_header_type(HpackEntryType::kIndexedLiteralHeader); EXPECT_FALSE(collector.IsClear()); QUICHE_VLOG(1) << collector; collector.Clear(); EXPECT_TRUE(collector.IsClear()); collector.set_index(123); EXPECT_FALSE(collector.IsClear()); QUICHE_VLOG(1) << collector; collector.Clear(); EXPECT_TRUE(collector.IsClear()); collector.set_name(HpackStringCollector("name", true)); EXPECT_FALSE(collector.IsClear()); QUICHE_VLOG(1) << collector; collector.Clear(); EXPECT_TRUE(collector.IsClear()); collector.set_value(HpackStringCollector("value", false)); EXPECT_FALSE(collector.IsClear()); QUICHE_VLOG(1) << collector; } void IndexedHeaderErrorTest() { HpackEntryCollector collector; collector.OnIndexedHeader(1); collector.OnIndexedHeader(234); } TEST(HpackEntryCollectorTest, IndexedHeader) { HpackEntryCollector collector; collector.OnIndexedHeader(123); QUICHE_VLOG(1) << collector; EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsComplete()); EXPECT_TRUE(collector.ValidateIndexedHeader(123)); EXPECT_THAT(collector.ToString(), HasSubstr("IndexedHeader")); EXPECT_THAT(collector.ToString(), HasSubstr("Complete")); EXPECT_FATAL_FAILURE(IndexedHeaderErrorTest(), "Value of: started_"); } void LiteralValueErrorTest() { HpackEntryCollector collector; collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1); collector.OnNameStart(false, 10); } TEST(HpackEntryCollectorTest, LiteralValueHeader) { HpackEntryCollector collector; collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 4); QUICHE_VLOG(1) << collector; EXPECT_FALSE(collector.IsClear()); EXPECT_FALSE(collector.IsComplete()); EXPECT_THAT(collector.ToString(), HasSubstr("!ended")); collector.OnValueStart(true, 5); QUICHE_VLOG(1) << collector; collector.OnValueData("value", 5); collector.OnValueEnd(); QUICHE_VLOG(1) << collector; EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsComplete()); EXPECT_TRUE(collector.ValidateLiteralValueHeader( HpackEntryType::kIndexedLiteralHeader, 4, true, "value")); EXPECT_THAT(collector.ToString(), HasSubstr("IndexedLiteralHeader")); EXPECT_THAT(collector.ToString(), HasSubstr("Complete")); EXPECT_FATAL_FAILURE(LiteralValueErrorTest(), "Value of: LiteralNameExpected"); } void LiteralNameValueHeaderErrorTest() { HpackEntryCollector collector; collector.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader, 0); collector.OnValueStart(false, 10); } TEST(HpackEntryCollectorTest, LiteralNameValueHeader) { HpackEntryCollector collector; collector.OnStartLiteralHeader(HpackEntryType::kUnindexedLiteralHeader, 0); QUICHE_VLOG(1) << collector; EXPECT_FALSE(collector.IsClear()); EXPECT_FALSE(collector.IsComplete()); collector.OnNameStart(false, 4); collector.OnNameData("na", 2); QUICHE_VLOG(1) << collector; collector.OnNameData("me", 2); collector.OnNameEnd(); collector.OnValueStart(true, 5); QUICHE_VLOG(1) << collector; collector.OnValueData("Value", 5); collector.OnValueEnd(); QUICHE_VLOG(1) << collector; EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsComplete()); EXPECT_TRUE(collector.ValidateLiteralNameValueHeader( HpackEntryType::kUnindexedLiteralHeader, false, "name", true, "Value")); EXPECT_FATAL_FAILURE(LiteralNameValueHeaderErrorTest(), "Value of: name_.HasEnded"); } void DynamicTableSizeUpdateErrorTest() { HpackEntryCollector collector; collector.OnDynamicTableSizeUpdate(123); EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsComplete()); EXPECT_TRUE(collector.ValidateDynamicTableSizeUpdate(123)); collector.OnDynamicTableSizeUpdate(234); } TEST(HpackEntryCollectorTest, DynamicTableSizeUpdate) { HpackEntryCollector collector; collector.OnDynamicTableSizeUpdate(8192); QUICHE_VLOG(1) << collector; EXPECT_FALSE(collector.IsClear()); EXPECT_TRUE(collector.IsComplete()); EXPECT_TRUE(collector.ValidateDynamicTableSizeUpdate(8192)); EXPECT_EQ(collector, HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, 8192)); EXPECT_NE(collector, HpackEntryCollector(HpackEntryType::kIndexedHeader, 8192)); EXPECT_NE(collector, HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, 8191)); EXPECT_FATAL_FAILURE(DynamicTableSizeUpdateErrorTest(), "Value of: started_"); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/test_tools/hpack_entry_collector.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/hpack/decoder/hpack_entry_collector_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
cb21734b-9242-415e-ac25-360ddf2d0b25
cpp
google/quiche
decode_buffer
quiche/http2/decoder/decode_buffer.cc
quiche/http2/decoder/decode_buffer_test.cc
#include "quiche/http2/decoder/decode_buffer.h" namespace http2 { uint8_t DecodeBuffer::DecodeUInt8() { return static_cast<uint8_t>(DecodeChar()); } uint16_t DecodeBuffer::DecodeUInt16() { QUICHE_DCHECK_LE(2u, Remaining()); const uint8_t b1 = DecodeUInt8(); const uint8_t b2 = DecodeUInt8(); return b1 << 8 | b2; } uint32_t DecodeBuffer::DecodeUInt24() { QUICHE_DCHECK_LE(3u, Remaining()); const uint8_t b1 = DecodeUInt8(); const uint8_t b2 = DecodeUInt8(); const uint8_t b3 = DecodeUInt8(); return b1 << 16 | b2 << 8 | b3; } uint32_t DecodeBuffer::DecodeUInt31() { QUICHE_DCHECK_LE(4u, Remaining()); const uint8_t b1 = DecodeUInt8() & 0x7f; const uint8_t b2 = DecodeUInt8(); const uint8_t b3 = DecodeUInt8(); const uint8_t b4 = DecodeUInt8(); return b1 << 24 | b2 << 16 | b3 << 8 | b4; } uint32_t DecodeBuffer::DecodeUInt32() { QUICHE_DCHECK_LE(4u, Remaining()); const uint8_t b1 = DecodeUInt8(); const uint8_t b2 = DecodeUInt8(); const uint8_t b3 = DecodeUInt8(); const uint8_t b4 = DecodeUInt8(); return b1 << 24 | b2 << 16 | b3 << 8 | b4; } #ifndef NDEBUG void DecodeBuffer::set_subset_of_base(DecodeBuffer* base, const DecodeBufferSubset* subset) { QUICHE_DCHECK_EQ(this, subset); base->set_subset(subset); } void DecodeBuffer::clear_subset_of_base(DecodeBuffer* base, const DecodeBufferSubset* subset) { QUICHE_DCHECK_EQ(this, subset); base->clear_subset(subset); } void DecodeBuffer::set_subset(const DecodeBufferSubset* subset) { QUICHE_DCHECK(subset != nullptr); QUICHE_DCHECK_EQ(subset_, nullptr) << "There is already a subset"; subset_ = subset; } void DecodeBuffer::clear_subset(const DecodeBufferSubset* subset) { QUICHE_DCHECK(subset != nullptr); QUICHE_DCHECK_EQ(subset_, subset); subset_ = nullptr; } void DecodeBufferSubset::DebugSetup() { start_base_offset_ = base_buffer_->Offset(); max_base_offset_ = start_base_offset_ + FullSize(); QUICHE_DCHECK_LE(max_base_offset_, base_buffer_->FullSize()); set_subset_of_base(base_buffer_, this); } void DecodeBufferSubset::DebugTearDown() { QUICHE_DCHECK_EQ(start_base_offset_, base_buffer_->Offset()) << "The base buffer was modified"; size_t offset = Offset(); QUICHE_DCHECK_LE(offset, FullSize()); QUICHE_DCHECK_LE(start_base_offset_ + offset, max_base_offset_); QUICHE_DCHECK_LE(max_base_offset_, base_buffer_->FullSize()); clear_subset_of_base(base_buffer_, this); } #endif }
#include "quiche/http2/decoder/decode_buffer.h" #include <functional> #include "quiche/http2/test_tools/http2_random.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { enum class TestEnumClass32 { kValue1 = 1, kValue99 = 99, kValue1M = 1000000, }; enum class TestEnumClass8 { kValue1 = 1, kValue2 = 1, kValue99 = 99, kValue255 = 255, }; enum TestEnum8 { kMaskLo = 0x01, kMaskHi = 0x80, }; struct TestStruct { uint8_t f1; uint16_t f2; uint32_t f3; uint32_t f4; uint32_t f5; TestEnumClass32 f6; TestEnumClass8 f7; TestEnum8 f8; }; class DecodeBufferTest : public quiche::test::QuicheTest { protected: Http2Random random_; uint32_t decode_offset_; }; TEST_F(DecodeBufferTest, DecodesFixedInts) { const char data[] = "\x01\x12\x23\x34\x45\x56\x67\x78\x89\x9a"; DecodeBuffer b1(data, strlen(data)); EXPECT_EQ(1, b1.DecodeUInt8()); EXPECT_EQ(0x1223u, b1.DecodeUInt16()); EXPECT_EQ(0x344556u, b1.DecodeUInt24()); EXPECT_EQ(0x6778899Au, b1.DecodeUInt32()); } TEST_F(DecodeBufferTest, HasNotCopiedInput) { const char data[] = "ab"; DecodeBuffer b1(data, 2); EXPECT_EQ(2u, b1.Remaining()); EXPECT_EQ(0u, b1.Offset()); EXPECT_FALSE(b1.Empty()); EXPECT_EQ(data, b1.cursor()); EXPECT_TRUE(b1.HasData()); b1.AdvanceCursor(1); EXPECT_EQ(1u, b1.Remaining()); EXPECT_EQ(1u, b1.Offset()); EXPECT_FALSE(b1.Empty()); EXPECT_EQ(&data[1], b1.cursor()); EXPECT_TRUE(b1.HasData()); b1.AdvanceCursor(1); EXPECT_EQ(0u, b1.Remaining()); EXPECT_EQ(2u, b1.Offset()); EXPECT_TRUE(b1.Empty()); EXPECT_EQ(&data[2], b1.cursor()); EXPECT_FALSE(b1.HasData()); DecodeBuffer b2(data, 0); EXPECT_EQ(0u, b2.Remaining()); EXPECT_EQ(0u, b2.Offset()); EXPECT_TRUE(b2.Empty()); EXPECT_EQ(data, b2.cursor()); EXPECT_FALSE(b2.HasData()); } TEST_F(DecodeBufferTest, DecodeBufferSubsetLimited) { const char data[] = "abc"; DecodeBuffer base(data, 3); base.AdvanceCursor(1); DecodeBufferSubset subset(&base, 100); EXPECT_EQ(2u, subset.FullSize()); } TEST_F(DecodeBufferTest, DecodeBufferSubsetAdvancesCursor) { const char data[] = "abc"; const size_t size = sizeof(data) - 1; EXPECT_EQ(3u, size); DecodeBuffer base(data, size); { DecodeBufferSubset subset(&base, size + 100); EXPECT_EQ(size, subset.FullSize()); EXPECT_EQ(base.FullSize(), subset.FullSize()); EXPECT_EQ(0u, subset.Offset()); } EXPECT_EQ(0u, base.Offset()); EXPECT_EQ(size, base.Remaining()); } #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) TEST(DecodeBufferDeathTest, NonNullBufferRequired) { EXPECT_QUICHE_DEBUG_DEATH({ DecodeBuffer b(nullptr, 3); }, "nullptr"); } TEST(DecodeBufferDeathTest, ModestBufferSizeRequired) { EXPECT_QUICHE_DEBUG_DEATH( { constexpr size_t kLength = DecodeBuffer::kMaxDecodeBufferLength + 1; auto data = std::make_unique<char[]>(kLength); DecodeBuffer b(data.get(), kLength); }, "Max.*Length"); } TEST(DecodeBufferDeathTest, LimitedAdvance) { { const char data[] = "abc"; DecodeBuffer b(data, 3); b.AdvanceCursor(3); EXPECT_TRUE(b.Empty()); } EXPECT_QUICHE_DEBUG_DEATH( { const char data[] = "abc"; DecodeBuffer b(data, 3); b.AdvanceCursor(4); }, "Remaining"); } TEST(DecodeBufferDeathTest, DecodeUInt8PastEnd) { const char data[] = {0x12, 0x23}; DecodeBuffer b(data, sizeof data); EXPECT_EQ(2u, b.FullSize()); EXPECT_EQ(0x1223, b.DecodeUInt16()); EXPECT_QUICHE_DEBUG_DEATH({ b.DecodeUInt8(); }, "Remaining"); } TEST(DecodeBufferDeathTest, DecodeUInt16OverEnd) { const char data[] = {0x12, 0x23, 0x34}; DecodeBuffer b(data, sizeof data); EXPECT_EQ(3u, b.FullSize()); EXPECT_EQ(0x1223, b.DecodeUInt16()); EXPECT_QUICHE_DEBUG_DEATH({ b.DecodeUInt16(); }, "Remaining"); } TEST(DecodeBufferSubsetDeathTest, TwoSubsets) { const char data[] = "abc"; DecodeBuffer base(data, 3); DecodeBufferSubset subset1(&base, 1); EXPECT_QUICHE_DEBUG_DEATH({ DecodeBufferSubset subset2(&base, 1); }, "There is already a subset"); } TEST(DecodeBufferSubsetDeathTest, BaseCursorAdvanced) { const char data[] = "abc"; DecodeBuffer base(data, 3); base.AdvanceCursor(1); EXPECT_QUICHE_DEBUG_DEATH( { DecodeBufferSubset subset1(&base, 2); base.AdvanceCursor(1); }, "Access via subset only when present"); } #endif } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/decode_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/decode_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2ebf9c9f-22ed-4452-a3c0-afb2763d6313
cpp
google/quiche
http2_structure_decoder
quiche/http2/decoder/http2_structure_decoder.cc
quiche/http2/decoder/http2_structure_decoder_test.cc
#include "quiche/http2/decoder/http2_structure_decoder.h" #include <algorithm> #include <cstring> #include "quiche/common/platform/api/quiche_bug_tracker.h" namespace http2 { uint32_t Http2StructureDecoder::IncompleteStart(DecodeBuffer* db, uint32_t target_size) { if (target_size > sizeof buffer_) { QUICHE_BUG(http2_bug_154_1) << "target_size too large for buffer: " << target_size; return 0; } const uint32_t num_to_copy = db->MinLengthRemaining(target_size); memcpy(buffer_, db->cursor(), num_to_copy); offset_ = num_to_copy; db->AdvanceCursor(num_to_copy); return num_to_copy; } DecodeStatus Http2StructureDecoder::IncompleteStart(DecodeBuffer* db, uint32_t* remaining_payload, uint32_t target_size) { QUICHE_DVLOG(1) << "IncompleteStart@" << this << ": *remaining_payload=" << *remaining_payload << "; target_size=" << target_size << "; db->Remaining=" << db->Remaining(); *remaining_payload -= IncompleteStart(db, std::min(target_size, *remaining_payload)); if (*remaining_payload > 0 && db->Empty()) { return DecodeStatus::kDecodeInProgress; } QUICHE_DVLOG(1) << "IncompleteStart: kDecodeError"; return DecodeStatus::kDecodeError; } bool Http2StructureDecoder::ResumeFillingBuffer(DecodeBuffer* db, uint32_t target_size) { QUICHE_DVLOG(2) << "ResumeFillingBuffer@" << this << ": target_size=" << target_size << "; offset_=" << offset_ << "; db->Remaining=" << db->Remaining(); if (target_size < offset_) { QUICHE_BUG(http2_bug_154_2) << "Already filled buffer_! target_size=" << target_size << " offset_=" << offset_; return false; } const uint32_t needed = target_size - offset_; const uint32_t num_to_copy = db->MinLengthRemaining(needed); QUICHE_DVLOG(2) << "ResumeFillingBuffer num_to_copy=" << num_to_copy; memcpy(&buffer_[offset_], db->cursor(), num_to_copy); db->AdvanceCursor(num_to_copy); offset_ += num_to_copy; return needed == num_to_copy; } bool Http2StructureDecoder::ResumeFillingBuffer(DecodeBuffer* db, uint32_t* remaining_payload, uint32_t target_size) { QUICHE_DVLOG(2) << "ResumeFillingBuffer@" << this << ": target_size=" << target_size << "; offset_=" << offset_ << "; *remaining_payload=" << *remaining_payload << "; db->Remaining=" << db->Remaining(); if (target_size < offset_) { QUICHE_BUG(http2_bug_154_3) << "Already filled buffer_! target_size=" << target_size << " offset_=" << offset_; return false; } const uint32_t needed = target_size - offset_; const uint32_t num_to_copy = db->MinLengthRemaining(std::min(needed, *remaining_payload)); QUICHE_DVLOG(2) << "ResumeFillingBuffer num_to_copy=" << num_to_copy; memcpy(&buffer_[offset_], db->cursor(), num_to_copy); db->AdvanceCursor(num_to_copy); offset_ += num_to_copy; *remaining_payload -= num_to_copy; return needed == num_to_copy; } }
#include "quiche/http2/decoder/http2_structure_decoder.h" #include <stddef.h> #include <cstdint> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" using ::testing::AssertionSuccess; namespace http2 { namespace test { namespace { const bool kMayReturnZeroOnFirst = false; template <class S> class Http2StructureDecoderTest : public RandomDecoderTest { protected: typedef S Structure; Http2StructureDecoderTest() { stop_decode_on_done_ = true; } DecodeStatus StartDecoding(DecodeBuffer* b) override { structure_ = std::make_unique<S>(); uint32_t old_remaining = b->Remaining(); if (structure_decoder_.Start(structure_.get(), b)) { EXPECT_EQ(old_remaining - S::EncodedSize(), b->Remaining()); ++fast_decode_count_; return DecodeStatus::kDecodeDone; } else { EXPECT_LT(structure_decoder_.offset(), S::EncodedSize()); EXPECT_EQ(0u, b->Remaining()); EXPECT_EQ(old_remaining - structure_decoder_.offset(), b->Remaining()); ++incomplete_start_count_; return DecodeStatus::kDecodeInProgress; } } DecodeStatus ResumeDecoding(DecodeBuffer* b) override { uint32_t old_offset = structure_decoder_.offset(); EXPECT_LT(old_offset, S::EncodedSize()); uint32_t avail = b->Remaining(); if (structure_decoder_.Resume(structure_.get(), b)) { EXPECT_LE(S::EncodedSize(), old_offset + avail); EXPECT_EQ(b->Remaining(), avail - (S::EncodedSize() - old_offset)); ++slow_decode_count_; return DecodeStatus::kDecodeDone; } else { EXPECT_LT(structure_decoder_.offset(), S::EncodedSize()); EXPECT_EQ(0u, b->Remaining()); EXPECT_GT(S::EncodedSize(), old_offset + avail); ++incomplete_resume_count_; return DecodeStatus::kDecodeInProgress; } } AssertionResult DecodeLeadingStructure(const S* expected, absl::string_view data) { HTTP2_VERIFY_LE(S::EncodedSize(), data.size()); DecodeBuffer original(data); Validator validator; if (expected != nullptr) { validator = [expected, this](const DecodeBuffer& , DecodeStatus ) -> AssertionResult { HTTP2_VERIFY_EQ(*expected, *structure_); return AssertionSuccess(); }; } validator = ValidateDoneAndOffset(S::EncodedSize(), std::move(validator)); fast_decode_count_ = 0; slow_decode_count_ = 0; incomplete_start_count_ = 0; incomplete_resume_count_ = 0; HTTP2_VERIFY_SUCCESS(DecodeAndValidateSeveralWays( &original, kMayReturnZeroOnFirst, validator)); HTTP2_VERIFY_FALSE(HasFailure()); HTTP2_VERIFY_EQ(S::EncodedSize(), structure_decoder_.offset()); HTTP2_VERIFY_EQ(S::EncodedSize(), original.Offset()); HTTP2_VERIFY_LT(0u, fast_decode_count_); HTTP2_VERIFY_LT(0u, slow_decode_count_); HTTP2_VERIFY_LT(0u, incomplete_start_count_); if (S::EncodedSize() >= 2) { HTTP2_VERIFY_LE(0u, incomplete_resume_count_); } else { HTTP2_VERIFY_EQ(0u, incomplete_resume_count_); } if (expected != nullptr) { QUICHE_DVLOG(1) << "DecodeLeadingStructure expected: " << *expected; QUICHE_DVLOG(1) << "DecodeLeadingStructure actual: " << *structure_; HTTP2_VERIFY_EQ(*expected, *structure_); } return AssertionSuccess(); } template <size_t N> AssertionResult DecodeLeadingStructure(const char (&data)[N]) { return DecodeLeadingStructure(nullptr, absl::string_view(data, N)); } template <size_t N> AssertionResult DecodeLeadingStructure(const unsigned char (&data)[N]) { return DecodeLeadingStructure(nullptr, ToStringPiece(data)); } AssertionResult EncodeThenDecode(const S& in_s) { std::string bytes = SerializeStructure(in_s); HTTP2_VERIFY_EQ(S::EncodedSize(), bytes.size()); return DecodeLeadingStructure(&in_s, bytes); } AssertionResult TestDecodingRandomizedStructures(size_t count) { for (size_t i = 0; i < count; ++i) { Structure input; Randomize(&input, RandomPtr()); HTTP2_VERIFY_SUCCESS(EncodeThenDecode(input)); } return AssertionSuccess(); } AssertionResult TestDecodingRandomizedStructures() { HTTP2_VERIFY_SUCCESS(TestDecodingRandomizedStructures(100)); return AssertionSuccess(); } uint32_t decode_offset_ = 0; std::unique_ptr<S> structure_; Http2StructureDecoder structure_decoder_; size_t fast_decode_count_ = 0; size_t slow_decode_count_ = 0; size_t incomplete_start_count_ = 0; size_t incomplete_resume_count_ = 0; }; class Http2FrameHeaderDecoderTest : public Http2StructureDecoderTest<Http2FrameHeader> {}; TEST_F(Http2FrameHeaderDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x00, 0x05, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(5u, structure_->payload_length); EXPECT_EQ(Http2FrameType::HEADERS, structure_->type); EXPECT_EQ(Http2FrameFlag::PADDED, structure_->flags); EXPECT_EQ(1u, structure_->stream_id); } { const unsigned char kData[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ((1u << 24) - 1u, structure_->payload_length); EXPECT_EQ(static_cast<Http2FrameType>(255), structure_->type); EXPECT_EQ(255, structure_->flags); EXPECT_EQ(0x7FFFFFFFu, structure_->stream_id); } } TEST_F(Http2FrameHeaderDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2PriorityFieldsDecoderTest : public Http2StructureDecoderTest<Http2PriorityFields> {}; TEST_F(Http2PriorityFieldsDecoderTest, DecodesLiteral) { { const unsigned char kData[] = { 0x80, 0x00, 0x00, 0x05, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(5u, structure_->stream_dependency); EXPECT_EQ(256u, structure_->weight); EXPECT_EQ(true, structure_->is_exclusive); } { const unsigned char kData[] = { 0x7f, 0xff, 0xff, 0xff, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(StreamIdMask(), structure_->stream_dependency); EXPECT_EQ(1u, structure_->weight); EXPECT_FALSE(structure_->is_exclusive); } } TEST_F(Http2PriorityFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2RstStreamFieldsDecoderTest : public Http2StructureDecoderTest<Http2RstStreamFields> {}; TEST_F(Http2RstStreamFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x00, 0x00, 0x01, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_TRUE(structure_->IsSupportedErrorCode()); EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_->error_code); } { const unsigned char kData[] = { 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_FALSE(structure_->IsSupportedErrorCode()); EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_->error_code); } } TEST_F(Http2RstStreamFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2SettingFieldsDecoderTest : public Http2StructureDecoderTest<Http2SettingFields> {}; TEST_F(Http2SettingFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_TRUE(structure_->IsSupportedParameter()); EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE, structure_->parameter); EXPECT_EQ(1u << 14, structure_->value); } { const unsigned char kData[] = { 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_FALSE(structure_->IsSupportedParameter()); EXPECT_EQ(static_cast<Http2SettingsParameter>(0), structure_->parameter); } } TEST_F(Http2SettingFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2PushPromiseFieldsDecoderTest : public Http2StructureDecoderTest<Http2PushPromiseFields> {}; TEST_F(Http2PushPromiseFieldsDecoderTest, DecodesLiteral) { { const unsigned char kData[] = { 0x00, 0x01, 0x8a, 0x92, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(101010u, structure_->promised_stream_id); } { const unsigned char kData[] = { 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(StreamIdMask(), structure_->promised_stream_id); } } TEST_F(Http2PushPromiseFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2PingFieldsDecoderTest : public Http2StructureDecoderTest<Http2PingFields> {}; TEST_F(Http2PingFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes)); } { const char kData[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes)); } { const unsigned char kData[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes)); } } TEST_F(Http2PingFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2GoAwayFieldsDecoderTest : public Http2StructureDecoderTest<Http2GoAwayFields> {}; TEST_F(Http2GoAwayFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(0u, structure_->last_stream_id); EXPECT_TRUE(structure_->IsSupportedErrorCode()); EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_->error_code); } { const char kData[] = { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0d, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(1u, structure_->last_stream_id); EXPECT_TRUE(structure_->IsSupportedErrorCode()); EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_->error_code); } { const unsigned char kData[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(StreamIdMask(), structure_->last_stream_id); EXPECT_FALSE(structure_->IsSupportedErrorCode()); EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_->error_code); } } TEST_F(Http2GoAwayFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2WindowUpdateFieldsDecoderTest : public Http2StructureDecoderTest<Http2WindowUpdateFields> {}; TEST_F(Http2WindowUpdateFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x01, 0x00, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(1u << 16, structure_->window_size_increment); } { const char kData[] = { 0x00, 0x00, 0x00, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(0u, structure_->window_size_increment); } { const unsigned char kData[] = { 0xff, 0xff, 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(StreamIdMask(), structure_->window_size_increment); } } TEST_F(Http2WindowUpdateFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } class Http2AltSvcFieldsDecoderTest : public Http2StructureDecoderTest<Http2AltSvcFields> {}; TEST_F(Http2AltSvcFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { 0x00, 0x00, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(0, structure_->origin_length); } { const char kData[] = { 0x00, 0x14, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(20, structure_->origin_length); } { const unsigned char kData[] = { 0xff, 0xff, }; ASSERT_TRUE(DecodeLeadingStructure(kData)); EXPECT_EQ(65535, structure_->origin_length); } } TEST_F(Http2AltSvcFieldsDecoderTest, DecodesRandomized) { EXPECT_TRUE(TestDecodingRandomizedStructures()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/http2_structure_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/http2_structure_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8ed8fe03-8fe6-41ff-86a0-f7f2a159a47c
cpp
google/quiche
decode_http2_structures
quiche/http2/decoder/decode_http2_structures.cc
quiche/http2/decoder/decode_http2_structures_test.cc
#include "quiche/http2/decoder/decode_http2_structures.h" #include <cstdint> #include <cstring> #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { void DoDecode(Http2FrameHeader* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2FrameHeader::EncodedSize(), b->Remaining()); out->payload_length = b->DecodeUInt24(); out->type = static_cast<Http2FrameType>(b->DecodeUInt8()); out->flags = static_cast<Http2FrameFlag>(b->DecodeUInt8()); out->stream_id = b->DecodeUInt31(); } void DoDecode(Http2PriorityFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2PriorityFields::EncodedSize(), b->Remaining()); uint32_t stream_id_and_flag = b->DecodeUInt32(); out->stream_dependency = stream_id_and_flag & StreamIdMask(); if (out->stream_dependency == stream_id_and_flag) { out->is_exclusive = false; } else { out->is_exclusive = true; } out->weight = b->DecodeUInt8() + 1; } void DoDecode(Http2RstStreamFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2RstStreamFields::EncodedSize(), b->Remaining()); out->error_code = static_cast<Http2ErrorCode>(b->DecodeUInt32()); } void DoDecode(Http2SettingFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2SettingFields::EncodedSize(), b->Remaining()); out->parameter = static_cast<Http2SettingsParameter>(b->DecodeUInt16()); out->value = b->DecodeUInt32(); } void DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2PushPromiseFields::EncodedSize(), b->Remaining()); out->promised_stream_id = b->DecodeUInt31(); } void DoDecode(Http2PingFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2PingFields::EncodedSize(), b->Remaining()); memcpy(out->opaque_bytes, b->cursor(), Http2PingFields::EncodedSize()); b->AdvanceCursor(Http2PingFields::EncodedSize()); } void DoDecode(Http2GoAwayFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2GoAwayFields::EncodedSize(), b->Remaining()); out->last_stream_id = b->DecodeUInt31(); out->error_code = static_cast<Http2ErrorCode>(b->DecodeUInt32()); } void DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2WindowUpdateFields::EncodedSize(), b->Remaining()); out->window_size_increment = b->DecodeUInt31(); } void DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2PriorityUpdateFields::EncodedSize(), b->Remaining()); out->prioritized_stream_id = b->DecodeUInt31(); } void DoDecode(Http2AltSvcFields* out, DecodeBuffer* b) { QUICHE_DCHECK_NE(nullptr, out); QUICHE_DCHECK_NE(nullptr, b); QUICHE_DCHECK_LE(Http2AltSvcFields::EncodedSize(), b->Remaining()); out->origin_length = b->DecodeUInt16(); } }
#include "quiche/http2/decoder/decode_http2_structures.h" #include <stddef.h> #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { template <typename T, size_t N> absl::string_view ToStringPiece(T (&data)[N]) { return absl::string_view(reinterpret_cast<const char*>(data), N * sizeof(T)); } template <class S> std::string SerializeStructure(const S& s) { Http2FrameBuilder fb; fb.Append(s); EXPECT_EQ(S::EncodedSize(), fb.size()); return fb.buffer(); } template <class S> class StructureDecoderTest : public quiche::test::QuicheTest { protected: typedef S Structure; StructureDecoderTest() : random_(), random_decode_count_(100) {} void Randomize(S* p) { ::http2::test::Randomize(p, &random_); } void DecodeLeadingStructure(const S* expected, absl::string_view data) { ASSERT_LE(S::EncodedSize(), data.size()); DecodeBuffer db(data); Randomize(&structure_); DoDecode(&structure_, &db); EXPECT_EQ(db.Offset(), S::EncodedSize()); if (expected != nullptr) { EXPECT_EQ(structure_, *expected); } } template <size_t N> void DecodeLeadingStructure(const char (&data)[N]) { DecodeLeadingStructure(nullptr, absl::string_view(data, N)); } void EncodeThenDecode(const S& in_s) { std::string bytes = SerializeStructure(in_s); EXPECT_EQ(S::EncodedSize(), bytes.size()); DecodeLeadingStructure(&in_s, bytes); } void TestDecodingRandomizedStructures(size_t count) { for (size_t i = 0; i < count && !HasFailure(); ++i) { Structure input; Randomize(&input); EncodeThenDecode(input); } } void TestDecodingRandomizedStructures() { TestDecodingRandomizedStructures(random_decode_count_); } Http2Random random_; const size_t random_decode_count_; uint32_t decode_offset_ = 0; S structure_; size_t fast_decode_count_ = 0; size_t slow_decode_count_ = 0; }; class FrameHeaderDecoderTest : public StructureDecoderTest<Http2FrameHeader> {}; TEST_F(FrameHeaderDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x00', '\x05', '\x01', '\x08', '\x00', '\x00', '\x00', '\x01', '\x04', '\x00', '\x00', '\x00', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(5u, structure_.payload_length); EXPECT_EQ(Http2FrameType::HEADERS, structure_.type); EXPECT_EQ(Http2FrameFlag::PADDED, structure_.flags); EXPECT_EQ(1u, structure_.stream_id); } } { const char kData[] = { '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ((1u << 24) - 1, structure_.payload_length); EXPECT_EQ(static_cast<Http2FrameType>(255), structure_.type); EXPECT_EQ(255, structure_.flags); EXPECT_EQ(0x7FFFFFFFu, structure_.stream_id); } } } TEST_F(FrameHeaderDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class PriorityFieldsDecoderTest : public StructureDecoderTest<Http2PriorityFields> {}; TEST_F(PriorityFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x80', '\x00', '\x00', '\x05', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(5u, structure_.stream_dependency); EXPECT_EQ(256u, structure_.weight); EXPECT_EQ(true, structure_.is_exclusive); } } { const char kData[] = { '\x7f', '\xff', '\xff', '\xff', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(StreamIdMask(), structure_.stream_dependency); EXPECT_EQ(1u, structure_.weight); EXPECT_FALSE(structure_.is_exclusive); } } } TEST_F(PriorityFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class RstStreamFieldsDecoderTest : public StructureDecoderTest<Http2RstStreamFields> {}; TEST_F(RstStreamFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x00', '\x00', '\x01', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_TRUE(structure_.IsSupportedErrorCode()); EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_.error_code); } } { const char kData[] = { '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_FALSE(structure_.IsSupportedErrorCode()); EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_.error_code); } } } TEST_F(RstStreamFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class SettingFieldsDecoderTest : public StructureDecoderTest<Http2SettingFields> {}; TEST_F(SettingFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x01', '\x00', '\x00', '\x40', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_TRUE(structure_.IsSupportedParameter()); EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE, structure_.parameter); EXPECT_EQ(1u << 14, structure_.value); } } { const char kData[] = { '\x00', '\x00', '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_FALSE(structure_.IsSupportedParameter()); EXPECT_EQ(static_cast<Http2SettingsParameter>(0), structure_.parameter); } } } TEST_F(SettingFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class PushPromiseFieldsDecoderTest : public StructureDecoderTest<Http2PushPromiseFields> {}; TEST_F(PushPromiseFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x01', '\x8a', '\x92', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(101010u, structure_.promised_stream_id); } } { const char kData[] = { '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(StreamIdMask(), structure_.promised_stream_id); } } } TEST_F(PushPromiseFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class PingFieldsDecoderTest : public StructureDecoderTest<Http2PingFields> {}; TEST_F(PingFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(absl::string_view(kData, 8), ToStringPiece(structure_.opaque_bytes)); } } { const char kData[] = { '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(absl::string_view(kData, 8), ToStringPiece(structure_.opaque_bytes)); } } { const char kData[] = { '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(absl::string_view(kData, 8), ToStringPiece(structure_.opaque_bytes)); } } } TEST_F(PingFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class GoAwayFieldsDecoderTest : public StructureDecoderTest<Http2GoAwayFields> { }; TEST_F(GoAwayFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(0u, structure_.last_stream_id); EXPECT_TRUE(structure_.IsSupportedErrorCode()); EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_.error_code); } } { const char kData[] = { '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', '\x0d', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(1u, structure_.last_stream_id); EXPECT_TRUE(structure_.IsSupportedErrorCode()); EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_.error_code); } } { const char kData[] = { '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(StreamIdMask(), structure_.last_stream_id); EXPECT_FALSE(structure_.IsSupportedErrorCode()); EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_.error_code); } } } TEST_F(GoAwayFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class WindowUpdateFieldsDecoderTest : public StructureDecoderTest<Http2WindowUpdateFields> {}; TEST_F(WindowUpdateFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x01', '\x00', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(1u << 16, structure_.window_size_increment); } } { const char kData[] = { '\x00', '\x00', '\x00', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(0u, structure_.window_size_increment); } } { const char kData[] = { '\xff', '\xff', '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(StreamIdMask(), structure_.window_size_increment); } } } TEST_F(WindowUpdateFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } class AltSvcFieldsDecoderTest : public StructureDecoderTest<Http2AltSvcFields> { }; TEST_F(AltSvcFieldsDecoderTest, DecodesLiteral) { { const char kData[] = { '\x00', '\x00', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(0, structure_.origin_length); } } { const char kData[] = { '\x00', '\x14', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(20, structure_.origin_length); } } { const char kData[] = { '\xff', '\xff', }; DecodeLeadingStructure(kData); if (!HasFailure()) { EXPECT_EQ(65535, structure_.origin_length); } } } TEST_F(AltSvcFieldsDecoderTest, DecodesRandomized) { TestDecodingRandomizedStructures(); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/decode_http2_structures.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/decode_http2_structures_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b34100b3-f345-49db-a7b0-5d4f8ad618ea
cpp
google/quiche
http2_frame_decoder
quiche/http2/decoder/http2_frame_decoder.cc
quiche/http2/decoder/http2_frame_decoder_test.cc
#include "quiche/http2/decoder/http2_frame_decoder.h" #include <ostream> #include "quiche/http2/decoder/decode_status.h" #include "quiche/http2/hpack/varint/hpack_varint_decoder.h" #include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, Http2FrameDecoder::State v) { switch (v) { case Http2FrameDecoder::State::kStartDecodingHeader: return out << "kStartDecodingHeader"; case Http2FrameDecoder::State::kResumeDecodingHeader: return out << "kResumeDecodingHeader"; case Http2FrameDecoder::State::kResumeDecodingPayload: return out << "kResumeDecodingPayload"; case Http2FrameDecoder::State::kDiscardPayload: return out << "kDiscardPayload"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_155_1) << "Http2FrameDecoder::State " << unknown; return out << "Http2FrameDecoder::State(" << unknown << ")"; } Http2FrameDecoder::Http2FrameDecoder(Http2FrameDecoderListener* listener) : state_(State::kStartDecodingHeader), maximum_payload_size_(Http2SettingsInfo::DefaultMaxFrameSize()) { set_listener(listener); } void Http2FrameDecoder::set_listener(Http2FrameDecoderListener* listener) { if (listener == nullptr) { listener = &no_op_listener_; } frame_decoder_state_.set_listener(listener); } Http2FrameDecoderListener* Http2FrameDecoder::listener() const { return frame_decoder_state_.listener(); } DecodeStatus Http2FrameDecoder::DecodeFrame(DecodeBuffer* db) { QUICHE_DVLOG(2) << "Http2FrameDecoder::DecodeFrame state=" << state_; switch (state_) { case State::kStartDecodingHeader: if (frame_decoder_state_.StartDecodingFrameHeader(db)) { return StartDecodingPayload(db); } state_ = State::kResumeDecodingHeader; return DecodeStatus::kDecodeInProgress; case State::kResumeDecodingHeader: if (frame_decoder_state_.ResumeDecodingFrameHeader(db)) { return StartDecodingPayload(db); } return DecodeStatus::kDecodeInProgress; case State::kResumeDecodingPayload: return ResumeDecodingPayload(db); case State::kDiscardPayload: return DiscardPayload(db); } QUICHE_NOTREACHED(); return DecodeStatus::kDecodeError; } size_t Http2FrameDecoder::remaining_payload() const { return frame_decoder_state_.remaining_payload(); } uint32_t Http2FrameDecoder::remaining_padding() const { return frame_decoder_state_.remaining_padding(); } DecodeStatus Http2FrameDecoder::StartDecodingPayload(DecodeBuffer* db) { const Http2FrameHeader& header = frame_header(); if (!listener()->OnFrameHeader(header)) { QUICHE_DVLOG(2) << "OnFrameHeader rejected the frame, will discard; header: " << header; state_ = State::kDiscardPayload; frame_decoder_state_.InitializeRemainders(); return DecodeStatus::kDecodeError; } if (header.payload_length > maximum_payload_size_) { QUICHE_DVLOG(2) << "Payload length is greater than allowed: " << header.payload_length << " > " << maximum_payload_size_ << "\n header: " << header; state_ = State::kDiscardPayload; frame_decoder_state_.InitializeRemainders(); listener()->OnFrameSizeError(header); return DecodeStatus::kDecodeError; } DecodeBufferSubset subset(db, header.payload_length); DecodeStatus status; switch (header.type) { case Http2FrameType::DATA: status = StartDecodingDataPayload(&subset); break; case Http2FrameType::HEADERS: status = StartDecodingHeadersPayload(&subset); break; case Http2FrameType::PRIORITY: status = StartDecodingPriorityPayload(&subset); break; case Http2FrameType::RST_STREAM: status = StartDecodingRstStreamPayload(&subset); break; case Http2FrameType::SETTINGS: status = StartDecodingSettingsPayload(&subset); break; case Http2FrameType::PUSH_PROMISE: status = StartDecodingPushPromisePayload(&subset); break; case Http2FrameType::PING: status = StartDecodingPingPayload(&subset); break; case Http2FrameType::GOAWAY: status = StartDecodingGoAwayPayload(&subset); break; case Http2FrameType::WINDOW_UPDATE: status = StartDecodingWindowUpdatePayload(&subset); break; case Http2FrameType::CONTINUATION: status = StartDecodingContinuationPayload(&subset); break; case Http2FrameType::ALTSVC: status = StartDecodingAltSvcPayload(&subset); break; case Http2FrameType::PRIORITY_UPDATE: status = StartDecodingPriorityUpdatePayload(&subset); break; default: status = StartDecodingUnknownPayload(&subset); break; } if (status == DecodeStatus::kDecodeDone) { state_ = State::kStartDecodingHeader; return status; } else if (status == DecodeStatus::kDecodeInProgress) { state_ = State::kResumeDecodingPayload; return status; } else { state_ = State::kDiscardPayload; return status; } } DecodeStatus Http2FrameDecoder::ResumeDecodingPayload(DecodeBuffer* db) { size_t remaining = frame_decoder_state_.remaining_total_payload(); QUICHE_DCHECK_LE(remaining, frame_header().payload_length); DecodeBufferSubset subset(db, remaining); DecodeStatus status; switch (frame_header().type) { case Http2FrameType::DATA: status = ResumeDecodingDataPayload(&subset); break; case Http2FrameType::HEADERS: status = ResumeDecodingHeadersPayload(&subset); break; case Http2FrameType::PRIORITY: status = ResumeDecodingPriorityPayload(&subset); break; case Http2FrameType::RST_STREAM: status = ResumeDecodingRstStreamPayload(&subset); break; case Http2FrameType::SETTINGS: status = ResumeDecodingSettingsPayload(&subset); break; case Http2FrameType::PUSH_PROMISE: status = ResumeDecodingPushPromisePayload(&subset); break; case Http2FrameType::PING: status = ResumeDecodingPingPayload(&subset); break; case Http2FrameType::GOAWAY: status = ResumeDecodingGoAwayPayload(&subset); break; case Http2FrameType::WINDOW_UPDATE: status = ResumeDecodingWindowUpdatePayload(&subset); break; case Http2FrameType::CONTINUATION: status = ResumeDecodingContinuationPayload(&subset); break; case Http2FrameType::ALTSVC: status = ResumeDecodingAltSvcPayload(&subset); break; case Http2FrameType::PRIORITY_UPDATE: status = ResumeDecodingPriorityUpdatePayload(&subset); break; default: status = ResumeDecodingUnknownPayload(&subset); break; } if (status == DecodeStatus::kDecodeDone) { state_ = State::kStartDecodingHeader; return status; } else if (status == DecodeStatus::kDecodeInProgress) { return status; } else { state_ = State::kDiscardPayload; return status; } } void Http2FrameDecoder::RetainFlags(uint8_t valid_flags) { frame_decoder_state_.RetainFlags(valid_flags); } void Http2FrameDecoder::ClearFlags() { frame_decoder_state_.ClearFlags(); } DecodeStatus Http2FrameDecoder::StartDecodingAltSvcPayload(DecodeBuffer* db) { ClearFlags(); return altsvc_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingAltSvcPayload(DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return altsvc_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingContinuationPayload( DecodeBuffer* db) { RetainFlags(Http2FrameFlag::END_HEADERS); return continuation_payload_decoder_.StartDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingContinuationPayload( DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return continuation_payload_decoder_.ResumeDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingDataPayload(DecodeBuffer* db) { RetainFlags(Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED); return data_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingDataPayload(DecodeBuffer* db) { return data_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingGoAwayPayload(DecodeBuffer* db) { ClearFlags(); return goaway_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingGoAwayPayload(DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return goaway_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingHeadersPayload(DecodeBuffer* db) { RetainFlags(Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY); return headers_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingHeadersPayload(DecodeBuffer* db) { QUICHE_DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(), frame_header().payload_length); return headers_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingPingPayload(DecodeBuffer* db) { RetainFlags(Http2FrameFlag::ACK); return ping_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingPingPayload(DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return ping_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingPriorityPayload(DecodeBuffer* db) { ClearFlags(); return priority_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingPriorityPayload( DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return priority_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingPriorityUpdatePayload( DecodeBuffer* db) { ClearFlags(); return priority_payload_update_decoder_.StartDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingPriorityUpdatePayload( DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return priority_payload_update_decoder_.ResumeDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingPushPromisePayload( DecodeBuffer* db) { RetainFlags(Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED); return push_promise_payload_decoder_.StartDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingPushPromisePayload( DecodeBuffer* db) { QUICHE_DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(), frame_header().payload_length); return push_promise_payload_decoder_.ResumeDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingRstStreamPayload( DecodeBuffer* db) { ClearFlags(); return rst_stream_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingRstStreamPayload( DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return rst_stream_payload_decoder_.ResumeDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingSettingsPayload(DecodeBuffer* db) { RetainFlags(Http2FrameFlag::ACK); return settings_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingSettingsPayload( DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return settings_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingUnknownPayload(DecodeBuffer* db) { return unknown_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingUnknownPayload(DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return unknown_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::StartDecodingWindowUpdatePayload( DecodeBuffer* db) { ClearFlags(); return window_update_payload_decoder_.StartDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::ResumeDecodingWindowUpdatePayload( DecodeBuffer* db) { QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), frame_decoder_state_.remaining_payload()); return window_update_payload_decoder_.ResumeDecodingPayload( &frame_decoder_state_, db); } DecodeStatus Http2FrameDecoder::DiscardPayload(DecodeBuffer* db) { QUICHE_DVLOG(2) << "remaining_payload=" << frame_decoder_state_.remaining_payload_ << "; remaining_padding=" << frame_decoder_state_.remaining_padding_; frame_decoder_state_.remaining_payload_ += frame_decoder_state_.remaining_padding_; frame_decoder_state_.remaining_padding_ = 0; const size_t avail = frame_decoder_state_.AvailablePayload(db); QUICHE_DVLOG(2) << "avail=" << avail; if (avail > 0) { frame_decoder_state_.ConsumePayload(avail); db->AdvanceCursor(avail); } if (frame_decoder_state_.remaining_payload_ == 0) { state_ = State::kStartDecodingHeader; return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; } }
#include "quiche/http2/decoder/http2_frame_decoder.h" #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector_listener.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_logging.h" using ::testing::AssertionSuccess; namespace http2 { namespace test { class Http2FrameDecoderPeer { public: static size_t remaining_total_payload(Http2FrameDecoder* decoder) { return decoder->frame_decoder_state_.remaining_total_payload(); } }; namespace { class Http2FrameDecoderTest : public RandomDecoderTest { protected: DecodeStatus StartDecoding(DecodeBuffer* db) override { QUICHE_DVLOG(2) << "StartDecoding, db->Remaining=" << db->Remaining(); collector_.Reset(); PrepareDecoder(); DecodeStatus status = decoder_->DecodeFrame(db); if (status != DecodeStatus::kDecodeInProgress) { ++fast_decode_count_; if (status == DecodeStatus::kDecodeError) { ConfirmDiscardsRemainingPayload(); } } return status; } DecodeStatus ResumeDecoding(DecodeBuffer* db) override { QUICHE_DVLOG(2) << "ResumeDecoding, db->Remaining=" << db->Remaining(); DecodeStatus status = decoder_->DecodeFrame(db); if (status != DecodeStatus::kDecodeInProgress) { ++slow_decode_count_; if (status == DecodeStatus::kDecodeError) { ConfirmDiscardsRemainingPayload(); } } return status; } void ConfirmDiscardsRemainingPayload() { ASSERT_TRUE(decoder_->IsDiscardingPayload()); size_t remaining = Http2FrameDecoderPeer::remaining_total_payload(decoder_.get()); size_t extra = 10; std::string junk(remaining + extra, '0'); DecodeBuffer tmp(junk); EXPECT_EQ(DecodeStatus::kDecodeDone, decoder_->DecodeFrame(&tmp)); EXPECT_EQ(remaining, tmp.Offset()); EXPECT_EQ(extra, tmp.Remaining()); EXPECT_FALSE(decoder_->IsDiscardingPayload()); } void PrepareDecoder() { decoder_ = std::make_unique<Http2FrameDecoder>(&collector_); decoder_->set_maximum_payload_size(maximum_payload_size_); } void ResetDecodeSpeedCounters() { fast_decode_count_ = 0; slow_decode_count_ = 0; } AssertionResult VerifyCollected(const FrameParts& expected) { HTTP2_VERIFY_FALSE(collector_.IsInProgress()); HTTP2_VERIFY_EQ(1u, collector_.size()); return expected.VerifyEquals(*collector_.frame(0)); } AssertionResult DecodePayloadAndValidateSeveralWays(absl::string_view payload, Validator validator) { DecodeBuffer db(payload); bool start_decoding_requires_non_empty = false; return DecodeAndValidateSeveralWays(&db, start_decoding_requires_non_empty, validator); } AssertionResult DecodePayloadAndValidateSeveralWays( absl::string_view payload, const FrameParts& expected) { auto validator = [&expected, this](const DecodeBuffer& , DecodeStatus status) -> AssertionResult { HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone); return VerifyCollected(expected); }; ResetDecodeSpeedCounters(); HTTP2_VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays( payload, ValidateDoneAndEmpty(validator))); HTTP2_VERIFY_GT(fast_decode_count_, 0u); HTTP2_VERIFY_GT(slow_decode_count_, 0u); std::string next_frame = Random().RandString(10); std::string input(payload.data(), payload.size()); input += next_frame; ResetDecodeSpeedCounters(); HTTP2_VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays( payload, ValidateDoneAndOffset(payload.size(), validator))); HTTP2_VERIFY_GT(fast_decode_count_, 0u); HTTP2_VERIFY_GT(slow_decode_count_, 0u); return AssertionSuccess(); } template <size_t N> AssertionResult DecodePayloadAndValidateSeveralWays( const char (&buf)[N], const FrameParts& expected) { return DecodePayloadAndValidateSeveralWays(absl::string_view(buf, N), expected); } template <size_t N> AssertionResult DecodePayloadAndValidateSeveralWays( const char (&buf)[N], const Http2FrameHeader& header) { return DecodePayloadAndValidateSeveralWays(absl::string_view(buf, N), FrameParts(header)); } template <size_t N> AssertionResult DecodePayloadExpectingError(const char (&buf)[N], const FrameParts& expected) { auto validator = [&expected, this](const DecodeBuffer& , DecodeStatus status) -> AssertionResult { HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeError); return VerifyCollected(expected); }; ResetDecodeSpeedCounters(); EXPECT_TRUE( DecodePayloadAndValidateSeveralWays(ToStringPiece(buf), validator)); EXPECT_GT(fast_decode_count_, 0u); EXPECT_GT(slow_decode_count_, 0u); return AssertionSuccess(); } template <size_t N> AssertionResult DecodePayloadExpectingFrameSizeError(const char (&buf)[N], FrameParts expected) { expected.SetHasFrameSizeError(true); return DecodePayloadExpectingError(buf, expected); } template <size_t N> AssertionResult DecodePayloadExpectingFrameSizeError( const char (&buf)[N], const Http2FrameHeader& header) { return DecodePayloadExpectingFrameSizeError(buf, FrameParts(header)); } size_t fast_decode_count_ = 0; size_t slow_decode_count_ = 0; uint32_t maximum_payload_size_ = Http2SettingsInfo::DefaultMaxFrameSize(); FramePartsCollectorListener collector_; std::unique_ptr<Http2FrameDecoder> decoder_; }; TEST_F(Http2FrameDecoderTest, DataEmpty) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(0, Http2FrameType::DATA, 0, 0); FrameParts expected(header, ""); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeadersEmpty) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x01', }; Http2FrameHeader header(0, Http2FrameType::HEADERS, 0, 1); FrameParts expected(header, ""); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, Priority) { const char kFrameData[] = { '\x00', '\x00', '\x05', '\x02', '\x00', '\x00', '\x00', '\x00', '\x02', '\x80', '\x00', '\x00', '\x01', '\x10', }; Http2FrameHeader header(5, Http2FrameType::PRIORITY, 0, 2); FrameParts expected(header); expected.SetOptPriority(Http2PriorityFields(1, 17, true)); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, RstStream) { const char kFrameData[] = { '\x00', '\x00', '\x04', '\x03', '\x00', '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', '\x01', }; Http2FrameHeader header(4, Http2FrameType::RST_STREAM, 0, 1); FrameParts expected(header); expected.SetOptRstStreamErrorCode(Http2ErrorCode::PROTOCOL_ERROR); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, SettingsEmpty) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x04', '\x00', '\x00', '\x00', '\x00', '\x01', }; Http2FrameHeader header(0, Http2FrameType::SETTINGS, 0, 1); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, SettingsAck) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x04', '\x01', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(0, Http2FrameType::SETTINGS, Http2FrameFlag::ACK, 0); FrameParts expected(header); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, PushPromiseMinimal) { const char kFrameData[] = { '\x00', '\x00', '\x04', '\x05', '\x04', '\x00', '\x00', '\x00', '\x02', '\x00', '\x00', '\x00', '\x01', }; Http2FrameHeader header(4, Http2FrameType::PUSH_PROMISE, Http2FrameFlag::END_HEADERS, 2); FrameParts expected(header, ""); expected.SetOptPushPromise(Http2PushPromiseFields{1}); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, Ping) { const char kFrameData[] = { '\x00', '\x00', '\x08', '\x06', '\xfe', '\x00', '\x00', '\x00', '\x00', 's', 'o', 'm', 'e', 'd', 'a', 't', 'a', }; Http2FrameHeader header(8, Http2FrameType::PING, 0, 0); FrameParts expected(header); expected.SetOptPing( Http2PingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}}); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, PingAck) { const char kFrameData[] = { '\x00', '\x00', '\x08', '\x06', '\xff', '\x00', '\x00', '\x00', '\x00', 's', 'o', 'm', 'e', 'd', 'a', 't', 'a', }; Http2FrameHeader header(8, Http2FrameType::PING, Http2FrameFlag::ACK, 0); FrameParts expected(header); expected.SetOptPing( Http2PingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}}); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, GoAwayMinimal) { const char kFrameData[] = { '\x00', '\x00', '\x08', '\x07', '\xff', '\x00', '\x00', '\x00', '\x01', '\x80', '\x00', '\x00', '\xff', '\x00', '\x00', '\x00', '\x09', }; Http2FrameHeader header(8, Http2FrameType::GOAWAY, 0, 1); FrameParts expected(header); expected.SetOptGoaway( Http2GoAwayFields(255, Http2ErrorCode::COMPRESSION_ERROR)); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, WindowUpdate) { const char kFrameData[] = { '\x00', '\x00', '\x04', '\x08', '\x0f', '\x00', '\x00', '\x00', '\x01', '\x80', '\x00', '\x04', '\x00', }; Http2FrameHeader header(4, Http2FrameType::WINDOW_UPDATE, 0, 1); FrameParts expected(header); expected.SetOptWindowUpdateIncrement(1024); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, ContinuationEmpty) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x09', '\x00', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(0, Http2FrameType::CONTINUATION, 0, 0); FrameParts expected(header); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, AltSvcMinimal) { const char kFrameData[] = { '\x00', '\x00', '\x02', '\x0a', '\xff', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(2, Http2FrameType::ALTSVC, 0, 0); FrameParts expected(header); expected.SetOptAltsvcOriginLength(0); expected.SetOptAltsvcValueLength(0); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, UnknownEmpty) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x20', '\xff', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(0, static_cast<Http2FrameType>(32), 0xff, 0); FrameParts expected(header); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, DataPayload) { const char kFrameData[] = { '\x00', '\x00', '\x03', '\x00', '\x80', '\x00', '\x00', '\x02', '\x02', 'a', 'b', 'c', }; Http2FrameHeader header(3, Http2FrameType::DATA, 0, 514); FrameParts expected(header, "abc"); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeadersPayload) { const char kFrameData[] = { '\x00', '\x00', '\x03', '\x01', '\x05', '\x00', '\x00', '\x00', '\x02', 'a', 'b', 'c', }; Http2FrameHeader header( 3, Http2FrameType::HEADERS, Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS, 2); FrameParts expected(header, "abc"); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeadersPriority) { const char kFrameData[] = { '\x00', '\x00', '\x05', '\x01', '\x20', '\x00', '\x00', '\x00', '\x02', '\x00', '\x00', '\x00', '\x01', '\xff', }; Http2FrameHeader header(5, Http2FrameType::HEADERS, Http2FrameFlag::PRIORITY, 2); FrameParts expected(header); expected.SetOptPriority(Http2PriorityFields(1, 256, false)); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, Settings) { const char kFrameData[] = { '\x00', '\x00', '\x0c', '\x04', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x04', '\x0a', '\x0b', '\x0c', '\x0d', '\x00', '\x02', '\x00', '\x00', '\x00', '\x03', }; Http2FrameHeader header(12, Http2FrameType::SETTINGS, 0, 0); FrameParts expected(header); expected.AppendSetting(Http2SettingFields( Http2SettingsParameter::INITIAL_WINDOW_SIZE, 168496141)); expected.AppendSetting( Http2SettingFields(Http2SettingsParameter::ENABLE_PUSH, 3)); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, PushPromisePayload) { const char kFrameData[] = { '\x00', '\x00', 7, '\x05', '\x04', '\x00', '\x00', '\x00', '\xff', '\x00', '\x00', '\x01', '\x00', 'a', 'b', 'c', }; Http2FrameHeader header(7, Http2FrameType::PUSH_PROMISE, Http2FrameFlag::END_HEADERS, 255); FrameParts expected(header, "abc"); expected.SetOptPushPromise(Http2PushPromiseFields{256}); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, GoAwayOpaqueData) { const char kFrameData[] = { '\x00', '\x00', '\x0e', '\x07', '\xff', '\x80', '\x00', '\x00', '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x03', 'o', 'p', 'a', 'q', 'u', 'e', }; Http2FrameHeader header(14, Http2FrameType::GOAWAY, 0, 0); FrameParts expected(header, "opaque"); expected.SetOptGoaway( Http2GoAwayFields(256, Http2ErrorCode::FLOW_CONTROL_ERROR)); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, ContinuationPayload) { const char kFrameData[] = { '\x00', '\x00', '\x03', '\x09', '\xff', '\x00', '\x00', '\x00', '\x02', 'a', 'b', 'c', }; Http2FrameHeader header(3, Http2FrameType::CONTINUATION, Http2FrameFlag::END_HEADERS, 2); FrameParts expected(header, "abc"); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, AltSvcPayload) { const char kFrameData[] = { '\x00', '\x00', '\x08', '\x0a', '\x00', '\x00', '\x00', '\x00', '\x02', '\x00', '\x03', 'a', 'b', 'c', 'd', 'e', 'f', }; Http2FrameHeader header(8, Http2FrameType::ALTSVC, 0, 2); FrameParts expected(header); expected.SetAltSvcExpected("abc", "def"); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, PriorityUpdatePayload) { const char kFrameData[] = { '\x00', '\x00', '\x07', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x05', 'a', 'b', 'c', }; Http2FrameHeader header(7, Http2FrameType::PRIORITY_UPDATE, 0, 0); FrameParts expected(header, "abc"); expected.SetOptPriorityUpdate(Http2PriorityUpdateFields{5}); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, UnknownPayload) { const char kFrameData[] = { '\x00', '\x00', '\x03', '\x30', '\x00', '\x00', '\x00', '\x00', '\x02', 'a', 'b', 'c', }; Http2FrameHeader header(3, static_cast<Http2FrameType>(48), 0, 2); FrameParts expected(header, "abc"); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, DataPayloadAndPadding) { const char kFrameData[] = { '\x00', '\x00', '\x07', '\x00', '\x09', '\x00', '\x00', '\x00', '\x02', '\x03', 'a', 'b', 'c', '\x00', '\x00', '\x00', }; Http2FrameHeader header(7, Http2FrameType::DATA, Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED, 2); size_t total_pad_length = 4; FrameParts expected(header, "abc", total_pad_length); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeadersPayloadAndPadding) { const char kFrameData[] = { '\x00', '\x00', '\x07', '\x01', '\x08', '\x00', '\x00', '\x00', '\x02', '\x03', 'a', 'b', 'c', '\x00', '\x00', '\x00', }; Http2FrameHeader header(7, Http2FrameType::HEADERS, Http2FrameFlag::PADDED, 2); size_t total_pad_length = 4; FrameParts expected(header, "abc", total_pad_length); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeadersPayloadPriorityAndPadding) { const char kFrameData[] = { '\x00', '\x00', '\x0c', '\x01', '\xff', '\x00', '\x00', '\x00', '\x02', '\x03', '\x80', '\x00', '\x00', '\x01', '\x10', 'a', 'b', 'c', '\x00', '\x00', '\x00', }; Http2FrameHeader header(12, Http2FrameType::HEADERS, Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY, 2); size_t total_pad_length = 4; FrameParts expected(header, "abc", total_pad_length); expected.SetOptPriority(Http2PriorityFields(1, 17, true)); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, PushPromisePayloadAndPadding) { const char kFrameData[] = { '\x00', '\x00', 11, '\x05', '\xff', '\x00', '\x00', '\x00', '\x01', '\x03', '\x00', '\x00', '\x00', '\x02', 'a', 'b', 'c', '\x00', '\x00', '\x00', }; Http2FrameHeader header(11, Http2FrameType::PUSH_PROMISE, Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED, 1); size_t total_pad_length = 4; FrameParts expected(header, "abc", total_pad_length); expected.SetOptPushPromise(Http2PushPromiseFields{2}); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, DataMissingPadLengthField) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x00', '\x08', '\x00', '\x00', '\x00', '\x01', }; Http2FrameHeader header(0, Http2FrameType::DATA, Http2FrameFlag::PADDED, 1); FrameParts expected(header); expected.SetOptMissingLength(1); EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeaderPaddingTooLong) { const char kFrameData[] = { '\x00', '\x00', '\x02', '\x01', '\x08', '\x00', '\x01', '\x00', '\x00', '\xff', '\x00', }; Http2FrameHeader header(2, Http2FrameType::HEADERS, Http2FrameFlag::PADDED, 65536); FrameParts expected(header); expected.SetOptMissingLength(254); EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, HeaderMissingPriority) { const char kFrameData[] = { '\x00', '\x00', '\x04', '\x01', '\x20', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(4, Http2FrameType::HEADERS, Http2FrameFlag::PRIORITY, 65536); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, PriorityTooShort) { const char kFrameData[] = { '\x00', '\x00', '\x04', '\x02', '\x00', '\x00', '\x00', '\x00', '\x02', '\x80', '\x00', '\x00', '\x01', }; Http2FrameHeader header(4, Http2FrameType::PRIORITY, 0, 2); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, RstStreamTooShort) { const char kFrameData[] = { '\x00', '\x00', '\x03', '\x03', '\x00', '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', }; Http2FrameHeader header(3, Http2FrameType::RST_STREAM, 0, 1); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, SettingsWrongSize) { const char kFrameData[] = { '\x00', '\x00', '\x09', '\x04', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x02', '\x00', '\x00', '\x00', '\x03', '\x00', '\x04', '\x00', }; Http2FrameHeader header(9, Http2FrameType::SETTINGS, 0, 0); FrameParts expected(header); expected.AppendSetting( Http2SettingFields(Http2SettingsParameter::ENABLE_PUSH, 3)); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, expected)); } TEST_F(Http2FrameDecoderTest, PushPromiseTooShort) { const char kFrameData[] = { '\x00', '\x00', 3, '\x05', '\x00', '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', }; Http2FrameHeader header(3, Http2FrameType::PUSH_PROMISE, 0, 1); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, PushPromisePaddedTruncatedPromise) { const char kFrameData[] = { '\x00', '\x00', 4, '\x05', '\x08', '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(4, Http2FrameType::PUSH_PROMISE, Http2FrameFlag::PADDED, 1); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, PingTooShort) { const char kFrameData[] = { '\x00', '\x00', '\x07', '\x06', '\xfe', '\x00', '\x00', '\x00', '\x00', 's', 'o', 'm', 'e', 'd', 'a', 't', }; Http2FrameHeader header(7, Http2FrameType::PING, 0, 0); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, GoAwayTooShort) { const char kFrameData[] = { '\x00', '\x00', '\x00', '\x07', '\xff', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(0, Http2FrameType::GOAWAY, 0, 0); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, WindowUpdateTooShort) { const char kFrameData[] = { '\x00', '\x00', '\x03', '\x08', '\x0f', '\x00', '\x00', '\x00', '\x01', '\x80', '\x00', '\x04', }; Http2FrameHeader header(3, Http2FrameType::WINDOW_UPDATE, 0, 1); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, AltSvcTruncatedOriginLength) { const char kFrameData[] = { '\x00', '\x00', '\x01', '\x0a', '\x00', '\x00', '\x00', '\x00', '\x02', '\x00', }; Http2FrameHeader header(1, Http2FrameType::ALTSVC, 0, 2); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, AltSvcTruncatedOrigin) { const char kFrameData[] = { '\x00', '\x00', '\x05', '\x0a', '\x00', '\x00', '\x00', '\x00', '\x02', '\x00', '\x04', 'a', 'b', 'c', }; Http2FrameHeader header(5, Http2FrameType::ALTSVC, 0, 2); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, BeyondMaximum) { maximum_payload_size_ = 2; const char kFrameData[] = { '\x00', '\x00', '\x07', '\x00', '\x09', '\x00', '\x00', '\x00', '\x02', '\x03', 'a', 'b', 'c', '\x00', '\x00', '\x00', }; Http2FrameHeader header(7, Http2FrameType::DATA, Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED, 2); FrameParts expected(header); expected.SetHasFrameSizeError(true); auto validator = [&expected, this](const DecodeBuffer& input, DecodeStatus status) -> AssertionResult { HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeError); HTTP2_VERIFY_EQ(input.Offset(), Http2FrameHeader::EncodedSize()); return VerifyCollected(expected); }; ResetDecodeSpeedCounters(); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(ToStringPiece(kFrameData), validator)); EXPECT_GT(fast_decode_count_, 0u); EXPECT_GT(slow_decode_count_, 0u); } TEST_F(Http2FrameDecoderTest, PriorityTooLong) { const char kFrameData[] = { '\x00', '\x00', '\x06', '\x02', '\x00', '\x00', '\x00', '\x00', '\x02', '\x80', '\x00', '\x00', '\x01', '\x10', '\x00', }; Http2FrameHeader header(6, Http2FrameType::PRIORITY, 0, 2); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, RstStreamTooLong) { const char kFrameData[] = { '\x00', '\x00', '\x05', '\x03', '\x00', '\x00', '\x00', '\x00', '\x01', '\x00', '\x00', '\x00', '\x01', '\x00', }; Http2FrameHeader header(5, Http2FrameType::RST_STREAM, 0, 1); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, SettingsAckTooLong) { const char kFrameData[] = { '\x00', '\x00', '\x06', '\x04', '\x01', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', }; Http2FrameHeader header(6, Http2FrameType::SETTINGS, Http2FrameFlag::ACK, 0); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, PingAckTooLong) { const char kFrameData[] = { '\x00', '\x00', '\x09', '\x06', '\xff', '\x00', '\x00', '\x00', '\x00', 's', 'o', 'm', 'e', 'd', 'a', 't', 'a', '\x00', }; Http2FrameHeader header(9, Http2FrameType::PING, Http2FrameFlag::ACK, 0); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } TEST_F(Http2FrameDecoderTest, WindowUpdateTooLong) { const char kFrameData[] = { '\x00', '\x00', '\x05', '\x08', '\x0f', '\x00', '\x00', '\x00', '\x01', '\x80', '\x00', '\x04', '\x00', '\x00', }; Http2FrameHeader header(5, Http2FrameType::WINDOW_UPDATE, 0, 1); EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/http2_frame_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/http2_frame_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1845ed00-285e-4dc8-82c8-8c2389d5ebe9
cpp
google/quiche
data_payload_decoder
quiche/http2/decoder/payload_decoders/data_payload_decoder.cc
quiche/http2/decoder/payload_decoders/data_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/data_payload_decoder.h" #include <stddef.h> #include <ostream> #include "absl/base/macros.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, DataPayloadDecoder::PayloadState v) { switch (v) { case DataPayloadDecoder::PayloadState::kReadPadLength: return out << "kReadPadLength"; case DataPayloadDecoder::PayloadState::kReadPayload: return out << "kReadPayload"; case DataPayloadDecoder::PayloadState::kSkipPadding: return out << "kSkipPadding"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_174_1) << "Invalid DataPayloadDecoder::PayloadState: " << unknown; return out << "DataPayloadDecoder::PayloadState(" << unknown << ")"; } DecodeStatus DataPayloadDecoder::StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "DataPayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::DATA, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED)); QUICHE_DVLOG(2) << "StartDecodingPayload total_length=" << total_length; if (!frame_header.IsPadded()) { QUICHE_DVLOG(2) << "StartDecodingPayload !IsPadded"; if (db->Remaining() == total_length) { QUICHE_DVLOG(2) << "StartDecodingPayload all present"; state->listener()->OnDataStart(frame_header); if (total_length > 0) { state->listener()->OnDataPayload(db->cursor(), total_length); db->AdvanceCursor(total_length); } state->listener()->OnDataEnd(); return DecodeStatus::kDecodeDone; } payload_state_ = PayloadState::kReadPayload; } else { payload_state_ = PayloadState::kReadPadLength; } state->InitializeRemainders(); state->listener()->OnDataStart(frame_header); return ResumeDecodingPayload(state, db); } DecodeStatus DataPayloadDecoder::ResumeDecodingPayload(FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "DataPayloadDecoder::ResumeDecodingPayload payload_state_=" << payload_state_; const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::DATA, frame_header.type); QUICHE_DCHECK_LE(state->remaining_payload_and_padding(), frame_header.payload_length); QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding()); DecodeStatus status; size_t avail; switch (payload_state_) { case PayloadState::kReadPadLength: status = state->ReadPadLength(db, true); if (status != DecodeStatus::kDecodeDone) { return status; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kReadPayload: avail = state->AvailablePayload(db); if (avail > 0) { state->listener()->OnDataPayload(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() > 0) { payload_state_ = PayloadState::kReadPayload; return DecodeStatus::kDecodeInProgress; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kSkipPadding: if (state->SkipPadding(db)) { state->listener()->OnDataEnd(); return DecodeStatus::kDecodeDone; } payload_state_ = PayloadState::kSkipPadding; return DecodeStatus::kDecodeInProgress; } QUICHE_BUG(http2_bug_174_2) << "PayloadState: " << payload_state_; return DecodeStatus::kDecodeError; } }
#include "quiche/http2/decoder/payload_decoders/data_payload_decoder.h" #include <stddef.h> #include <string> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class DataPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::DATA; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return Http2FrameFlag::PADDED; } }; namespace { struct Listener : public FramePartsCollector { void OnDataStart(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnDataStart: " << header; StartFrame(header)->OnDataStart(header); } void OnDataPayload(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnDataPayload: len=" << len; CurrentFrame()->OnDataPayload(data, len); } void OnDataEnd() override { QUICHE_VLOG(1) << "OnDataEnd"; EndFrame()->OnDataEnd(); } void OnPadLength(size_t pad_length) override { QUICHE_VLOG(1) << "OnPadLength: " << pad_length; CurrentFrame()->OnPadLength(pad_length); } void OnPadding(const char* padding, size_t skipped_length) override { QUICHE_VLOG(1) << "OnPadding: " << skipped_length; CurrentFrame()->OnPadding(padding, skipped_length); } void OnPaddingTooLong(const Http2FrameHeader& header, size_t missing_length) override { QUICHE_VLOG(1) << "OnPaddingTooLong: " << header << " missing_length: " << missing_length; EndFrame()->OnPaddingTooLong(header, missing_length); } }; class DataPayloadDecoderTest : public AbstractPaddablePayloadDecoderTest< DataPayloadDecoder, DataPayloadDecoderPeer, Listener> { protected: AssertionResult CreateAndDecodeDataOfSize(size_t data_size) { Reset(); uint8_t flags = RandFlags(); std::string data_payload = Random().RandString(data_size); frame_builder_.Append(data_payload); MaybeAppendTrailingPadding(); Http2FrameHeader frame_header(frame_builder_.size(), Http2FrameType::DATA, flags, RandStreamId()); set_frame_header(frame_header); ScrubFlagsOfHeader(&frame_header); FrameParts expected(frame_header, data_payload, total_pad_length_); return DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected); } }; INSTANTIATE_TEST_SUITE_P(VariousPadLengths, DataPayloadDecoderTest, ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256)); TEST_P(DataPayloadDecoderTest, VariousDataPayloadSizes) { for (size_t data_size : {0, 1, 2, 3, 255, 256, 1024}) { EXPECT_TRUE(CreateAndDecodeDataOfSize(data_size)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/data_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/data_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6