diff options
150 files changed, 1187 insertions, 1352 deletions
diff --git a/cast/common/certificate/cast_cert_validator.cc b/cast/common/certificate/cast_cert_validator.cc index 6fe95821..5645c9d6 100644 --- a/cast/common/certificate/cast_cert_validator.cc +++ b/cast/common/certificate/cast_cert_validator.cc @@ -18,12 +18,10 @@ #include "cast/common/certificate/cast_cert_validator_internal.h" #include "cast/common/certificate/cast_crl.h" +namespace openscreen { namespace cast { -namespace certificate { namespace { -using CastCertError = openscreen::Error::Code; - // ------------------------------------------------------------------------- // Cast trust anchors. // ------------------------------------------------------------------------- @@ -49,8 +47,8 @@ const ConstDataSpan& AudioOnlyPolicyOid() { class CertVerificationContextImpl final : public CertVerificationContext { public: - CertVerificationContextImpl(bssl::UniquePtr<EVP_PKEY>&& cert, - std::string&& common_name) + CertVerificationContextImpl(bssl::UniquePtr<EVP_PKEY> cert, + std::string common_name) : public_key_{std::move(cert)}, common_name_(std::move(common_name)) {} ~CertVerificationContextImpl() override = default; @@ -164,33 +162,31 @@ class CastTrustStore { OSP_DISALLOW_COPY_AND_ASSIGN(CastTrustStore); }; -openscreen::Error VerifyDeviceCert( - const std::vector<std::string>& der_certs, - const DateTime& time, - std::unique_ptr<CertVerificationContext>* context, - CastDeviceCertPolicy* policy, - const CastCRL* crl, - CRLPolicy crl_policy, - TrustStore* trust_store) { +Error VerifyDeviceCert(const std::vector<std::string>& der_certs, + const DateTime& time, + std::unique_ptr<CertVerificationContext>* context, + CastDeviceCertPolicy* policy, + const CastCRL* crl, + CRLPolicy crl_policy, + TrustStore* trust_store) { if (!trust_store) { trust_store = CastTrustStore::GetInstance()->trust_store(); } // Fail early if CRL is required but not provided. if (!crl && crl_policy == CRLPolicy::kCrlRequired) { - return CastCertError::kErrCrlInvalid; + return Error::Code::kErrCrlInvalid; } CertificatePathResult result_path = {}; - openscreen::Error error = - FindCertificatePath(der_certs, time, &result_path, trust_store); + Error error = FindCertificatePath(der_certs, time, &result_path, trust_store); if (!error.ok()) { return error; } if (crl_policy == CRLPolicy::kCrlRequired && !crl->CheckRevocation(result_path.path, time)) { - return CastCertError::kErrCertsRevoked; + return Error::Code::kErrCertsRevoked; } *policy = GetAudioPolicy(result_path.path); @@ -203,7 +199,7 @@ openscreen::Error VerifyDeviceCert( int len = X509_NAME_get_text_by_NID(target_subject, NID_commonName, &common_name[0], common_name.size()); if (len == 0) { - return CastCertError::kErrCertsRestrictions; + return Error::Code::kErrCertsRestrictions; } common_name.resize(len); @@ -211,8 +207,8 @@ openscreen::Error VerifyDeviceCert( bssl::UniquePtr<EVP_PKEY>{X509_get_pubkey(result_path.target_cert.get())}, std::move(common_name))); - return CastCertError::kNone; + return Error::Code::kNone; } -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/cast_cert_validator.h b/cast/common/certificate/cast_cert_validator.h index e39632c4..c20e42db 100644 --- a/cast/common/certificate/cast_cert_validator.h +++ b/cast/common/certificate/cast_cert_validator.h @@ -13,8 +13,8 @@ #include "platform/base/error.h" #include "platform/base/macros.h" +namespace openscreen { namespace cast { -namespace certificate { class CastCRL; @@ -95,16 +95,15 @@ class CertVerificationContext { // // Outputs: // -// Returns openscreen::Error::Code::kNone on success. Otherwise, the -// corresponding openscreen::Error::Code. On success, the output parameters are -// filled with more details: +// Returns Error::Code::kNone on success. Otherwise, the corresponding +// Error::Code. On success, the output parameters are filled with more details: // // * |context| is filled with an object that can be used to verify signatures // using the device certificate's public key, as well as to extract other // properties from the device certificate (Common Name). // * |policy| is filled with an indication of the device certificate's policy // (i.e. is it for audio-only devices or is it unrestricted?) -[[nodiscard]] openscreen::Error VerifyDeviceCert( +[[nodiscard]] Error VerifyDeviceCert( const std::vector<std::string>& der_certs, const DateTime& time, std::unique_ptr<CertVerificationContext>* context, @@ -113,7 +112,7 @@ class CertVerificationContext { CRLPolicy crl_policy, TrustStore* trust_store = nullptr); -} // namespace certificate } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CERTIFICATE_CAST_CERT_VALIDATOR_H_ diff --git a/cast/common/certificate/cast_cert_validator_internal.cc b/cast/common/certificate/cast_cert_validator_internal.cc index 331e7125..7e43e02c 100644 --- a/cast/common/certificate/cast_cert_validator_internal.cc +++ b/cast/common/certificate/cast_cert_validator_internal.cc @@ -15,14 +15,12 @@ #include "cast/common/certificate/types.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace certificate { namespace { constexpr static int32_t kMinRsaModulusLengthBits = 2048; -using CastCertError = openscreen::Error::Code; - // Stores intermediate state while attempting to find a valid certificate chain // from a set of trusted certificates to a target certificate. Together, a // sequence of these forms a certificate chain to be verified as well as a stack @@ -63,16 +61,16 @@ uint8_t ParseAsn1TimeDoubleDigit(ASN1_GENERALIZEDTIME* time, int index) { return (time->data[index] - '0') * 10 + (time->data[index + 1] - '0'); } -CastCertError VerifyCertTime(X509* cert, const DateTime& time) { +Error::Code VerifyCertTime(X509* cert, const DateTime& time) { DateTime not_before; DateTime not_after; if (!GetCertValidTimeRange(cert, ¬_before, ¬_after)) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } if ((time < not_before) || (not_after < time)) { - return CastCertError::kErrCertsDateInvalid; + return Error::Code::kErrCertsDateInvalid; } - return CastCertError::kNone; + return Error::Code::kNone; } bool VerifyPublicKeyLength(EVP_PKEY* public_key) { @@ -94,27 +92,27 @@ bssl::UniquePtr<ASN1_BIT_STRING> GetKeyUsage(X509* cert) { return bssl::UniquePtr<ASN1_BIT_STRING>{key_usage_bit_string}; } -CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, - uint32_t step_index, - const DateTime& time) { +Error::Code VerifyCertificateChain(const std::vector<CertPathStep>& path, + uint32_t step_index, + const DateTime& time) { // Default max path length is the number of intermediate certificates. int max_pathlen = path.size() - 2; std::vector<NAME_CONSTRAINTS*> path_name_constraints; - CastCertError error = CastCertError::kNone; + Error::Code error = Error::Code::kNone; uint32_t i = step_index; for (; i < path.size() - 1; ++i) { X509* subject = path[i + 1].cert; X509* issuer = path[i].cert; bool is_root = (i == step_index); if (!is_root) { - if ((error = VerifyCertTime(issuer, time)) != CastCertError::kNone) { + if ((error = VerifyCertTime(issuer, time)) != Error::Code::kNone) { return error; } if (X509_NAME_cmp(X509_get_subject_name(issuer), X509_get_issuer_name(issuer)) != 0) { if (max_pathlen == 0) { - return CastCertError::kErrCertsPathlen; + return Error::Code::kErrCertsPathlen; } --max_pathlen; } else { @@ -129,7 +127,7 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, const int bit = ASN1_BIT_STRING_get_bit(key_usage.get(), KeyUsageBits::kKeyCertSign); if (bit == 0) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } } @@ -138,7 +136,7 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, const int basic_constraints_index = X509_get_ext_by_NID(issuer, NID_basic_constraints, -1); if (basic_constraints_index == -1) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } X509_EXTENSION* const basic_constraints_extension = X509_get_ext(issuer, basic_constraints_index); @@ -147,16 +145,16 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, X509V3_EXT_d2i(basic_constraints_extension))}; if (!basic_constraints || !basic_constraints->ca) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } if (basic_constraints->pathlen) { if (basic_constraints->pathlen->length != 1) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } else { const int pathlen = *basic_constraints->pathlen->data; if (pathlen < 0) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } if (pathlen < max_pathlen) { max_pathlen = pathlen; @@ -165,12 +163,12 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, } if (X509_ALGOR_cmp(issuer->sig_alg, issuer->cert_info->signature) != 0) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } bssl::UniquePtr<EVP_PKEY> public_key{X509_get_pubkey(issuer)}; if (!VerifyPublicKeyLength(public_key.get())) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } // NOTE: (!self-issued || target) -> verify name constraints. Target case @@ -179,7 +177,7 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, if (!is_self_issued) { for (NAME_CONSTRAINTS* name_constraints : path_name_constraints) { if (NAME_CONSTRAINTS_check(subject, name_constraints) != X509_V_OK) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } } } @@ -195,7 +193,7 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, issuer->nc = nc; path_name_constraints.push_back(nc); } else { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } } } @@ -220,12 +218,12 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, ((OBJ_cmp(policy_mapping->issuerDomainPolicy, any_policy) == 0) || (OBJ_cmp(policy_mapping->subjectDomainPolicy, any_policy) == 0)); if (either_matches) { - error = CastCertError::kErrCertsVerifyGeneric; + error = Error::Code::kErrCertsVerifyGeneric; break; } } sk_POLICY_MAPPING_free(policy_mappings); - if (error != CastCertError::kNone) { + if (error != Error::Code::kNone) { return error; } } @@ -238,7 +236,7 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, const int nid = OBJ_obj2nid(extension->object); if (nid != NID_name_constraints && nid != NID_basic_constraints && nid != NID_key_usage) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } } } @@ -259,7 +257,7 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, digest = EVP_sha512(); break; default: - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } if (!VerifySignedData( digest, public_key.get(), @@ -267,14 +265,14 @@ CastCertError VerifyCertificateChain(const std::vector<CertPathStep>& path, static_cast<uint32_t>(subject->cert_info->enc.len)}, {subject->signature->data, static_cast<uint32_t>(subject->signature->length)})) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } } // NOTE: Other half of ((!self-issued || target) -> check name constraints). for (NAME_CONSTRAINTS* name_constraints : path_name_constraints) { if (NAME_CONSTRAINTS_check(path.back().cert, name_constraints) != X509_V_OK) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } } return error; @@ -370,12 +368,12 @@ bool VerifySignedData(const EVP_MD* digest, data.data, data.length) == 1); } -openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, - const DateTime& time, - CertificatePathResult* result_path, - TrustStore* trust_store) { +Error FindCertificatePath(const std::vector<std::string>& der_certs, + const DateTime& time, + CertificatePathResult* result_path, + TrustStore* trust_store) { if (der_certs.empty()) { - return CastCertError::kErrCertsMissing; + return Error::Code::kErrCertsMissing; } bssl::UniquePtr<X509>& target_cert = result_path->target_cert; @@ -383,36 +381,36 @@ openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, result_path->intermediate_certs; target_cert.reset(ParseX509Der(der_certs[0])); if (!target_cert) { - return CastCertError::kErrCertsParse; + return Error::Code::kErrCertsParse; } for (size_t i = 1; i < der_certs.size(); ++i) { intermediate_certs.emplace_back(ParseX509Der(der_certs[i])); if (!intermediate_certs.back()) { - return CastCertError::kErrCertsParse; + return Error::Code::kErrCertsParse; } } // Basic checks on the target certificate. - CastCertError error = VerifyCertTime(target_cert.get(), time); - if (error != CastCertError::kNone) { + Error::Code error = VerifyCertTime(target_cert.get(), time); + if (error != Error::Code::kNone) { return error; } bssl::UniquePtr<EVP_PKEY> public_key{X509_get_pubkey(target_cert.get())}; if (!VerifyPublicKeyLength(public_key.get())) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } if (X509_ALGOR_cmp(target_cert.get()->sig_alg, target_cert.get()->cert_info->signature) != 0) { - return CastCertError::kErrCertsVerifyGeneric; + return Error::Code::kErrCertsVerifyGeneric; } bssl::UniquePtr<ASN1_BIT_STRING> key_usage = GetKeyUsage(target_cert.get()); if (!key_usage) { - return CastCertError::kErrCertsRestrictions; + return Error::Code::kErrCertsRestrictions; } int bit = ASN1_BIT_STRING_get_bit(key_usage.get(), KeyUsageBits::kDigitalSignature); if (bit == 0) { - return CastCertError::kErrCertsRestrictions; + return Error::Code::kErrCertsRestrictions; } X509* path_head = target_cert.get(); @@ -442,7 +440,7 @@ openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, // returned is whatever the last error was from the last path tried. uint32_t trust_store_index = 0; uint32_t intermediate_cert_index = 0; - CastCertError last_error = CastCertError::kNone; + Error::Code last_error = Error::Code::kNone; for (;;) { X509_NAME* target_issuer_name = X509_get_issuer_name(path_head); @@ -486,8 +484,8 @@ openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, if (!next_issuer) { if (path_index == first_index) { // There are no more paths to try. Ensure an error is returned. - if (last_error == CastCertError::kNone) { - return CastCertError::kErrCertsVerifyGeneric; + if (last_error == Error::Code::kNone) { + return Error::Code::kErrCertsVerifyGeneric; } return last_error; } else { @@ -500,7 +498,7 @@ openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, if (path_cert_in_trust_store) { last_error = VerifyCertificateChain(path, path_index, time); - if (last_error != CastCertError::kNone) { + if (last_error != Error::Code::kNone) { CertPathStep& last_step = path[path_index++]; trust_store_index = last_step.trust_store_index; intermediate_cert_index = last_step.intermediate_cert_index; @@ -517,8 +515,8 @@ openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, result_path->path.push_back(path[i].cert); } - return CastCertError::kNone; + return Error::Code::kNone; } -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/cast_cert_validator_internal.h b/cast/common/certificate/cast_cert_validator_internal.h index 1c127e72..c5b383ff 100644 --- a/cast/common/certificate/cast_cert_validator_internal.h +++ b/cast/common/certificate/cast_cert_validator_internal.h @@ -11,8 +11,8 @@ #include "platform/base/error.h" +namespace openscreen { namespace cast { -namespace certificate { struct TrustStore { std::vector<bssl::UniquePtr<X509>> certs; @@ -47,12 +47,12 @@ struct CertificatePathResult { std::vector<X509*> path; }; -openscreen::Error FindCertificatePath(const std::vector<std::string>& der_certs, - const DateTime& time, - CertificatePathResult* result_path, - TrustStore* trust_store); +Error FindCertificatePath(const std::vector<std::string>& der_certs, + const DateTime& time, + CertificatePathResult* result_path, + TrustStore* trust_store); -} // namespace certificate } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CERTIFICATE_CAST_CERT_VALIDATOR_INTERNAL_H_ diff --git a/cast/common/certificate/cast_cert_validator_unittest.cc b/cast/common/certificate/cast_cert_validator_unittest.cc index c29de9cc..e3f698cf 100644 --- a/cast/common/certificate/cast_cert_validator_unittest.cc +++ b/cast/common/certificate/cast_cert_validator_unittest.cc @@ -12,12 +12,10 @@ #include "gtest/gtest.h" #include "openssl/pem.h" +namespace openscreen { namespace cast { -namespace certificate { namespace { -using CastCertError = openscreen::Error::Code; - enum TrustStoreDependency { // Uses the built-in trust store for Cast. This is how certificates are // verified in production. @@ -45,7 +43,7 @@ enum TrustStoreDependency { // * |optional_signed_data_file_name| - optional path to a PEM file containing // a valid signature generated by the device certificate. // -void RunTest(CastCertError expected_result, +void RunTest(Error::Code expected_result, const std::string& expected_common_name, CastDeviceCertPolicy expected_policy, const std::string& certs_file_name, @@ -82,12 +80,11 @@ void RunTest(CastCertError expected_result, std::unique_ptr<CertVerificationContext> context; CastDeviceCertPolicy policy; - openscreen::Error result = - VerifyDeviceCert(certs, time, &context, &policy, nullptr, - CRLPolicy::kCrlOptional, trust_store); + Error result = VerifyDeviceCert(certs, time, &context, &policy, nullptr, + CRLPolicy::kCrlOptional, trust_store); ASSERT_EQ(expected_result, result.code()); - if (expected_result != CastCertError::kNone) + if (expected_result != Error::Code::kNone) return; EXPECT_EQ(expected_policy, policy); @@ -166,7 +163,7 @@ DateTime MarchFirst2037() { // Chains to trust anchor: // Eureka Root CA (built-in trust store) TEST(VerifyCastDeviceCertTest, ChromecastGen1) { - RunTest(CastCertError::kNone, "2ZZBG9 FA8FCA3EF91A", + RunTest(Error::Code::kNone, "2ZZBG9 FA8FCA3EF91A", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/chromecast_gen1.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, @@ -181,7 +178,7 @@ TEST(VerifyCastDeviceCertTest, ChromecastGen1) { // Chains to trust anchor: // Cast Root CA (built-in trust store) TEST(VerifyCastDeviceCertTest, ChromecastGen1Reissue) { - RunTest(CastCertError::kNone, "2ZZBG9 FA8FCA3EF91A", + RunTest(Error::Code::kNone, "2ZZBG9 FA8FCA3EF91A", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/chromecast_gen1_reissue.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, @@ -196,7 +193,7 @@ TEST(VerifyCastDeviceCertTest, ChromecastGen1Reissue) { // Chains to trust anchor: // Cast Root CA (built-in trust store) TEST(VerifyCastDeviceCertTest, ChromecastGen2) { - RunTest(CastCertError::kNone, "3ZZAK6 FA8FCA3F0D35", + RunTest(Error::Code::kNone, "3ZZAK6 FA8FCA3F0D35", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/chromecast_gen2.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -211,7 +208,7 @@ TEST(VerifyCastDeviceCertTest, ChromecastGen2) { // Chains to trust anchor: // Cast Root CA (built-in trust store) TEST(VerifyCastDeviceCertTest, Fugu) { - RunTest(CastCertError::kNone, "-6394818897508095075", + RunTest(Error::Code::kNone, "-6394818897508095075", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/fugu.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -226,7 +223,7 @@ TEST(VerifyCastDeviceCertTest, Fugu) { // // This is invalid because it does not chain to a trust anchor. TEST(VerifyCastDeviceCertTest, Unchained) { - RunTest(CastCertError::kErrCertsVerifyGeneric, "", + RunTest(Error::Code::kErrCertsVerifyGeneric, "", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/unchained.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -243,7 +240,7 @@ TEST(VerifyCastDeviceCertTest, Unchained) { // trust anchors after all) it fails the test as it is not a *device // certificate*. TEST(VerifyCastDeviceCertTest, CastRootCa) { - RunTest(CastCertError::kErrCertsRestrictions, "", + RunTest(Error::Code::kErrCertsRestrictions, "", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/cast_root_ca.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -260,7 +257,7 @@ TEST(VerifyCastDeviceCertTest, CastRootCa) { // This device certificate has a policy that means it is valid only for audio // devices. TEST(VerifyCastDeviceCertTest, ChromecastAudio) { - RunTest(CastCertError::kNone, "4ZZDZJ FA8FCA7EFE3C", + RunTest(Error::Code::kNone, "4ZZDZJ FA8FCA7EFE3C", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/chromecast_audio.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -278,7 +275,7 @@ TEST(VerifyCastDeviceCertTest, ChromecastAudio) { // This device certificate has a policy that means it is valid only for audio // devices. TEST(VerifyCastDeviceCertTest, MtkAudioDev) { - RunTest(CastCertError::kNone, "MediaTek Audio Dev Test", + RunTest(Error::Code::kNone, "MediaTek Audio Dev Test", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/mtk_audio_dev.pem", JanuaryFirst2015(), TRUST_STORE_BUILTIN, ""); @@ -292,7 +289,7 @@ TEST(VerifyCastDeviceCertTest, MtkAudioDev) { // Chains to trust anchor: // Cast Root CA (built-in trust store) TEST(VerifyCastDeviceCertTest, Vizio) { - RunTest(CastCertError::kNone, "9V0000VB FA8FCA784D01", + RunTest(Error::Code::kNone, "9V0000VB FA8FCA784D01", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/vizio.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -305,17 +302,17 @@ TEST(VerifyCastDeviceCertTest, ChromecastGen2InvalidTime) { // Control test - certificate should be valid at some time otherwise // this test is pointless. - RunTest(CastCertError::kNone, "3ZZAK6 FA8FCA3F0D35", + RunTest(Error::Code::kNone, "3ZZAK6 FA8FCA3F0D35", CastDeviceCertPolicy::kUnrestricted, kCertsFile, AprilFirst2016(), TRUST_STORE_BUILTIN, ""); // Use a time before notBefore. - RunTest(CastCertError::kErrCertsDateInvalid, "", + RunTest(Error::Code::kErrCertsDateInvalid, "", CastDeviceCertPolicy::kUnrestricted, kCertsFile, JanuaryFirst2015(), TRUST_STORE_BUILTIN, ""); // Use a time after notAfter. - RunTest(CastCertError::kErrCertsDateInvalid, "", + RunTest(Error::Code::kErrCertsDateInvalid, "", CastDeviceCertPolicy::kUnrestricted, kCertsFile, MarchFirst2037(), TRUST_STORE_BUILTIN, ""); } @@ -332,7 +329,7 @@ TEST(VerifyCastDeviceCertTest, ChromecastGen2InvalidTime) { // This device certificate has a policy that means it is valid only for audio // devices. TEST(VerifyCastDeviceCertTest, AudioRefDevTestChain3) { - RunTest(CastCertError::kNone, "Audio Reference Dev Test", + RunTest(Error::Code::kNone, "Audio Reference Dev Test", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/audio_ref_dev_test_chain_3.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, @@ -359,7 +356,7 @@ TEST(VerifyCastDeviceCertTest, AudioRefDevTestChain3) { // This device certificate has a policy that means it is valid only for audio // devices. TEST(VerifyCastDeviceCertTest, IntermediateSerialNumberTooLong) { - RunTest(CastCertError::kNone, "8C579B806FFC8A9DFFFF F8:8F:CA:6B:E6:DA", + RunTest(Error::Code::kNone, "8C579B806FFC8A9DFFFF F8:8F:CA:6B:E6:DA", CastDeviceCertPolicy::AUDIO_ONLY, "certificates/intermediate_serialnumber_toolong.pem", AprilFirst2016(), TRUST_STORE_BUILTIN, ""); @@ -378,8 +375,7 @@ TEST(VerifyCastDeviceCertTest, IntermediateSerialNumberTooLong) { TEST(VerifyCastDeviceCertTest, ExpiredTrustAnchor) { // The root certificate is only valid in 2015, so validating with a time in // 2016 means it is expired. - RunTest(CastCertError::kNone, "CastDevice", - CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "CastDevice", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/expired_root.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -399,7 +395,7 @@ TEST(VerifyCastDeviceCertTest, ExpiredTrustAnchor) { // Root (provided by test data; has pathlen=1 constraint) TEST(VerifyCastDeviceCertTest, ViolatesPathlenTrustAnchorConstraint) { // Test that the chain verification fails due to the pathlen constraint. - RunTest(CastCertError::kErrCertsPathlen, "Target", + RunTest(Error::Code::kErrCertsPathlen, "Target", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/violates_root_pathlen_constraint.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); @@ -411,7 +407,7 @@ TEST(VerifyCastDeviceCertTest, ViolatesPathlenTrustAnchorConstraint) { // Intermediate: policies={anyPolicy} // Leaf: policies={anyPolicy} TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafAnypolicy) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/policies_ica_anypolicy_leaf_anypolicy.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); @@ -423,7 +419,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafAnypolicy) { // Intermediate: policies={anyPolicy} // Leaf: policies={audioOnly} TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafAudioonly) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/policies_ica_anypolicy_leaf_audioonly.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); @@ -435,7 +431,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafAudioonly) { // Intermediate: policies={anyPolicy} // Leaf: policies={foo} TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafFoo) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/policies_ica_anypolicy_leaf_foo.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -446,7 +442,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafFoo) { // Intermediate: policies={anyPolicy} // Leaf: policies={} TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafNone) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/policies_ica_anypolicy_leaf_none.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -457,7 +453,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAnypolicyLeafNone) { // Intermediate: policies={audioOnly} // Leaf: policies={anyPolicy} TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafAnypolicy) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/policies_ica_audioonly_leaf_anypolicy.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); @@ -469,7 +465,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafAnypolicy) { // Intermediate: policies={audioOnly} // Leaf: policies={audioOnly} TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafAudioonly) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/policies_ica_audioonly_leaf_audioonly.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); @@ -481,7 +477,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafAudioonly) { // Intermediate: policies={audioOnly} // Leaf: policies={foo} TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafFoo) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/policies_ica_audioonly_leaf_foo.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -492,7 +488,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafFoo) { // Intermediate: policies={audioOnly} // Leaf: policies={} TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafNone) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/policies_ica_audioonly_leaf_none.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -503,7 +499,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaAudioonlyLeafNone) { // Intermediate: policies={} // Leaf: policies={anyPolicy} TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafAnypolicy) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/policies_ica_none_leaf_anypolicy.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -514,7 +510,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafAnypolicy) { // Intermediate: policies={} // Leaf: policies={audioOnly} TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafAudioonly) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kAudioOnly, TEST_DATA_PREFIX "certificates/policies_ica_none_leaf_audioonly.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -525,7 +521,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafAudioonly) { // Intermediate: policies={} // Leaf: policies={foo} TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafFoo) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/policies_ica_none_leaf_foo.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -536,7 +532,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafFoo) { // Intermediate: policies={} // Leaf: policies={} TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafNone) { - RunTest(CastCertError::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Leaf", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/policies_ica_none_leaf_none.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -545,7 +541,7 @@ TEST(VerifyCastDeviceCertTest, PoliciesIcaNoneLeafNone) { // 1024-bit RSA key. Verification should fail since the target's key is // too weak. TEST(VerifyCastDeviceCertTest, DeviceCertHas1024BitRsaKey) { - RunTest(CastCertError::kErrCertsVerifyGeneric, "RSA 1024 Device Cert", + RunTest(Error::Code::kErrCertsVerifyGeneric, "RSA 1024 Device Cert", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/rsa1024_device_cert.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, ""); @@ -555,7 +551,7 @@ TEST(VerifyCastDeviceCertTest, DeviceCertHas1024BitRsaKey) { // 2048-bit RSA key, and then verifying signed data (both SHA1 and SHA256) // for it. TEST(VerifyCastDeviceCertTest, DeviceCertHas2048BitRsaKey) { - RunTest(CastCertError::kNone, "RSA 2048 Device Cert", + RunTest(Error::Code::kNone, "RSA 2048 Device Cert", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/rsa2048_device_cert.pem", AprilFirst2016(), TRUST_STORE_FROM_TEST_FILE, @@ -566,7 +562,7 @@ TEST(VerifyCastDeviceCertTest, DeviceCertHas2048BitRsaKey) { // nameConstraints extension but the leaf certificate is still permitted under // these constraints. TEST(VerifyCastDeviceCertTest, NameConstraintsObeyed) { - RunTest(CastCertError::kNone, "Device", CastDeviceCertPolicy::kUnrestricted, + RunTest(Error::Code::kNone, "Device", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/nc.pem", AprilFirst2020(), TRUST_STORE_FROM_TEST_FILE, ""); } @@ -575,12 +571,12 @@ TEST(VerifyCastDeviceCertTest, NameConstraintsObeyed) { // nameConstraints extension and the leaf certificate is not permitted under // these constraints. TEST(VerifyCastDeviceCertTest, NameConstraintsViolated) { - RunTest(CastCertError::kErrCertsVerifyGeneric, "Device", + RunTest(Error::Code::kErrCertsVerifyGeneric, "Device", CastDeviceCertPolicy::kUnrestricted, TEST_DATA_PREFIX "certificates/nc_fail.pem", AprilFirst2020(), TRUST_STORE_FROM_TEST_FILE, ""); } } // namespace -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/cast_crl.cc b/cast/common/certificate/cast_crl.cc index 587fdb55..03ed1487 100644 --- a/cast/common/certificate/cast_crl.cc +++ b/cast/common/certificate/cast_crl.cc @@ -17,8 +17,8 @@ #include "util/crypto/sha2.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace certificate { namespace { enum CrlVersion { @@ -77,7 +77,7 @@ bool VerifyCRL(const Crl& crl, TrustStore* trust_store, DateTime* overall_not_after) { CertificatePathResult result_path = {}; - openscreen::Error error = + Error error = FindCertificatePath({crl.signer_cert()}, time, &result_path, trust_store); if (!error.ok()) { return false; @@ -179,13 +179,12 @@ bool CastCRL::CheckRevocation(const std::vector<X509*>& trusted_chain, // Check revocation. This loop iterates over both certificates AND then the // trust anchor after exhausting the certs. for (size_t i = 0; i < trusted_chain.size(); ++i) { - std::string spki_tlv = openscreen::GetSpkiTlv(trusted_chain[i]); + std::string spki_tlv = GetSpkiTlv(trusted_chain[i]); if (spki_tlv.empty()) { return false; } - openscreen::ErrorOr<std::string> spki_hash = - openscreen::SHA256HashString(spki_tlv); + ErrorOr<std::string> spki_hash = SHA256HashString(spki_tlv); if (spki_hash.is_error() || (revoked_hashes_.find(spki_hash.value()) != revoked_hashes_.end())) { return false; @@ -200,8 +199,8 @@ bool CastCRL::CheckRevocation(const std::vector<X509*>& trusted_chain, // Only Google generated device certificates will be revoked by range. // These will always be less than 64 bits in length. - openscreen::ErrorOr<uint64_t> maybe_serial = - openscreen::ParseDerUint64(subordinate->cert_info->serialNumber); + ErrorOr<uint64_t> maybe_serial = + ParseDerUint64(subordinate->cert_info->serialNumber); if (!maybe_serial) { continue; } @@ -249,5 +248,5 @@ std::unique_ptr<CastCRL> ParseAndVerifyCRL(const std::string& crl_proto, return nullptr; } -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/cast_crl.h b/cast/common/certificate/cast_crl.h index 51b8fa51..4de685d7 100644 --- a/cast/common/certificate/cast_crl.h +++ b/cast/common/certificate/cast_crl.h @@ -17,8 +17,8 @@ #include "cast/common/certificate/proto/revocation.pb.h" #include "platform/base/macros.h" +namespace openscreen { namespace cast { -namespace certificate { // This class represents the certificate revocation list information parsed from // the binary in a protobuf message. @@ -81,7 +81,7 @@ std::unique_ptr<CastCRL> ParseAndVerifyCRL(const std::string& crl_proto, const DateTime& time, TrustStore* trust_store = nullptr); -} // namespace certificate } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CERTIFICATE_CAST_CRL_H_ diff --git a/cast/common/certificate/cast_crl_unittest.cc b/cast/common/certificate/cast_crl_unittest.cc index b6660537..c172205d 100644 --- a/cast/common/certificate/cast_crl_unittest.cc +++ b/cast/common/certificate/cast_crl_unittest.cc @@ -12,12 +12,10 @@ #include "testing/util/read_file.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace certificate { namespace { -using CastCertError = openscreen::Error::Code; - // Indicates the expected result of test step's verification. enum TestStepResult { kResultSuccess, @@ -32,10 +30,9 @@ bool TestVerifyCertificate(TestStepResult expected_result, TrustStore* cast_trust_store) { std::unique_ptr<CertVerificationContext> context; CastDeviceCertPolicy policy; - openscreen::Error result = - VerifyDeviceCert(der_certs, time, &context, &policy, nullptr, - CRLPolicy::kCrlOptional, cast_trust_store); - bool success = (result.code() == CastCertError::kNone) == + Error result = VerifyDeviceCert(der_certs, time, &context, &policy, nullptr, + CRLPolicy::kCrlOptional, cast_trust_store); + bool success = (result.code() == Error::Code::kNone) == (expected_result == kResultSuccess); EXPECT_TRUE(success); return success; @@ -61,7 +58,7 @@ bool TestVerifyCRL(TestStepResult expected_result, // The provided CRL is verified at |crl_time|. // If |crl_required| is set, then a valid Cast CRL must be provided. // Otherwise, a missing CRL is be ignored. -bool TestVerifyRevocation(CastCertError expected_result, +bool TestVerifyRevocation(Error::Code expected_result, const std::vector<std::string>& der_certs, const std::string& crl_bundle, const DateTime& crl_time, @@ -79,9 +76,8 @@ bool TestVerifyRevocation(CastCertError expected_result, CastDeviceCertPolicy policy; CRLPolicy crl_policy = crl_required ? CRLPolicy::kCrlRequired : CRLPolicy::kCrlOptional; - openscreen::Error result = - VerifyDeviceCert(der_certs, cert_time, &context, &policy, crl.get(), - crl_policy, cast_trust_store); + Error result = VerifyDeviceCert(der_certs, cert_time, &context, &policy, + crl.get(), crl_policy, cast_trust_store); EXPECT_EQ(expected_result, result.code()); return expected_result == result.code(); } @@ -133,7 +129,7 @@ bool RunTest(const DeviceCertTest& test_case) { TestVerifyCRL(kResultFail, crl_bundle, crl_verification_time, crl_trust_store.get()) && TestVerifyRevocation( - CastCertError::kErrCrlInvalid, der_cert_path, crl_bundle, + Error::Code::kErrCrlInvalid, der_cert_path, crl_bundle, crl_verification_time, cert_verification_time, true, cast_trust_store.get(), crl_trust_store.get()); case CRL_EXPIRED_AFTER_INITIAL_VERIFICATION: // fallthrough @@ -144,7 +140,7 @@ bool RunTest(const DeviceCertTest& test_case) { TestVerifyCRL(kResultSuccess, crl_bundle, crl_verification_time, crl_trust_store.get()) && TestVerifyRevocation( - CastCertError::kErrCertsRevoked, der_cert_path, crl_bundle, + Error::Code::kErrCertsRevoked, der_cert_path, crl_bundle, crl_verification_time, cert_verification_time, true, cast_trust_store.get(), crl_trust_store.get()); case SUCCESS: @@ -154,10 +150,9 @@ bool RunTest(const DeviceCertTest& test_case) { TestVerifyCertificate(kResultSuccess, der_cert_path, cert_verification_time, cast_trust_store.get()) && - TestVerifyRevocation(CastCertError::kNone, der_cert_path, - crl_bundle, crl_verification_time, - cert_verification_time, !crl_bundle.empty(), - cast_trust_store.get(), + TestVerifyRevocation(Error::Code::kNone, der_cert_path, crl_bundle, + crl_verification_time, cert_verification_time, + !crl_bundle.empty(), cast_trust_store.get(), crl_trust_store.get()); case UNSPECIFIED: return false; @@ -170,8 +165,7 @@ bool RunTest(const DeviceCertTest& test_case) { // To see the description of the test, execute the test. // These tests are generated by a test generator in google3. void RunTestSuite(const std::string& test_suite_file_name) { - std::string testsuite_raw = - openscreen::ReadEntireFileToString(test_suite_file_name); + std::string testsuite_raw = ReadEntireFileToString(test_suite_file_name); ASSERT_FALSE(testsuite_raw.empty()); DeviceCertTestSuite test_suite; ASSERT_TRUE(test_suite.ParseFromString(testsuite_raw)); @@ -192,5 +186,5 @@ TEST(CastCertificateTest, TestSuite1) { } } // namespace -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/proto/revocation.proto b/cast/common/certificate/proto/revocation.proto index cc0b0ada..ad60f35a 100644 --- a/cast/common/certificate/proto/revocation.proto +++ b/cast/common/certificate/proto/revocation.proto @@ -8,7 +8,7 @@ syntax = "proto2"; -package cast.certificate; +package openscreen.cast; option optimize_for = LITE_RUNTIME; diff --git a/cast/common/certificate/proto/test_suite.proto b/cast/common/certificate/proto/test_suite.proto index 8a883d94..b4bd3afc 100644 --- a/cast/common/certificate/proto/test_suite.proto +++ b/cast/common/certificate/proto/test_suite.proto @@ -4,7 +4,7 @@ syntax = "proto2"; -package cast.certificate; +package openscreen.cast; option optimize_for = LITE_RUNTIME; diff --git a/cast/common/certificate/test_helpers.cc b/cast/common/certificate/test_helpers.cc index 3ede95e4..ae8b4c0b 100644 --- a/cast/common/certificate/test_helpers.cc +++ b/cast/common/certificate/test_helpers.cc @@ -13,8 +13,8 @@ #include "absl/strings/match.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace certificate { namespace testing { std::vector<std::string> ReadCertificatesFromPemFile( @@ -126,5 +126,5 @@ std::unique_ptr<TrustStore> CreateTrustStoreFromPemFile( } } // namespace testing -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/test_helpers.h b/cast/common/certificate/test_helpers.h index 558e60e8..5f095517 100644 --- a/cast/common/certificate/test_helpers.h +++ b/cast/common/certificate/test_helpers.h @@ -14,8 +14,8 @@ #include "cast/common/certificate/cast_cert_validator_internal.h" #include "cast/common/certificate/types.h" +namespace openscreen { namespace cast { -namespace certificate { namespace testing { std::vector<std::string> ReadCertificatesFromPemFile( @@ -38,7 +38,7 @@ std::unique_ptr<TrustStore> CreateTrustStoreFromPemFile( absl::string_view filename); } // namespace testing -} // namespace certificate } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CERTIFICATE_TEST_HELPERS_H_ diff --git a/cast/common/certificate/types.cc b/cast/common/certificate/types.cc index a6f297a2..507a033e 100644 --- a/cast/common/certificate/types.cc +++ b/cast/common/certificate/types.cc @@ -6,8 +6,8 @@ #include "util/logging.h" +namespace openscreen { namespace cast { -namespace certificate { bool operator<(const DateTime& a, const DateTime& b) { if (a.year < b.year) { @@ -83,5 +83,5 @@ std::chrono::seconds DateTimeToSeconds(const DateTime& time) { return std::chrono::seconds(mktime(&tm)); } -} // namespace certificate } // namespace cast +} // namespace openscreen diff --git a/cast/common/certificate/types.h b/cast/common/certificate/types.h index 40c83276..c3cf7efe 100644 --- a/cast/common/certificate/types.h +++ b/cast/common/certificate/types.h @@ -9,8 +9,8 @@ #include <chrono> +namespace openscreen { namespace cast { -namespace certificate { struct ConstDataSpan { const uint8_t* data; @@ -33,7 +33,7 @@ bool DateTimeFromSeconds(uint64_t seconds, DateTime* time); // |time| is assumed to be valid. std::chrono::seconds DateTimeToSeconds(const DateTime& time); -} // namespace certificate } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CERTIFICATE_TYPES_H_ diff --git a/cast/common/channel/cast_message_handler.h b/cast/common/channel/cast_message_handler.h index 9754b0c8..cd0d13e6 100644 --- a/cast/common/channel/cast_message_handler.h +++ b/cast/common/channel/cast_message_handler.h @@ -5,11 +5,12 @@ #ifndef CAST_COMMON_CHANNEL_CAST_MESSAGE_HANDLER_H_ #define CAST_COMMON_CHANNEL_CAST_MESSAGE_HANDLER_H_ +#include "cast/common/channel/proto/cast_channel.pb.h" + +namespace openscreen { namespace cast { -namespace channel { class CastSocket; -class CastMessage; class VirtualConnectionRouter; class CastMessageHandler { @@ -18,10 +19,10 @@ class CastMessageHandler { virtual void OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) = 0; + ::cast::channel::CastMessage message) = 0; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_CAST_MESSAGE_HANDLER_H_ diff --git a/cast/common/channel/cast_socket.cc b/cast/common/channel/cast_socket.cc index 214b50a8..8a5f81af 100644 --- a/cast/common/channel/cast_socket.cc +++ b/cast/common/channel/cast_socket.cc @@ -9,13 +9,11 @@ #include "cast/common/channel/message_framer.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { +using ::cast::channel::CastMessage; using message_serialization::DeserializeResult; -using openscreen::Error; -using openscreen::ErrorOr; -using openscreen::TlsConnection; uint32_t GetNextSocketId() { static std::atomic<uint32_t> id(1); @@ -62,7 +60,7 @@ void CastSocket::SetClient(Client* client) { } std::array<uint8_t, 2> CastSocket::GetSanitizedIpAddress() { - openscreen::IPEndpoint remote = connection_->GetRemoteEndpoint(); + IPEndpoint remote = connection_->GetRemoteEndpoint(); std::array<uint8_t, 2> result; uint8_t bytes[16]; if (remote.address.IsV4()) { @@ -118,5 +116,5 @@ void CastSocket::OnRead(TlsConnection* connection, std::vector<uint8_t> block) { client_->OnMessage(this, std::move(message_or_error.value().message)); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/cast_socket.h b/cast/common/channel/cast_socket.h index 1e5dc699..d8df45a8 100644 --- a/cast/common/channel/cast_socket.h +++ b/cast/common/channel/cast_socket.h @@ -9,31 +9,31 @@ #include <memory> #include <vector> +#include "cast/common/channel/proto/cast_channel.pb.h" #include "platform/api/tls_connection.h" +namespace openscreen { namespace cast { -namespace channel { - -class CastMessage; uint32_t GetNextSocketId(); // Represents a simple message-oriented socket for communicating with the Cast // V2 protocol. It isn't thread-safe, so it should only be used on the same // TaskRunner thread as its TlsConnection. -class CastSocket : public openscreen::TlsConnection::Client { +class CastSocket : public TlsConnection::Client { public: class Client { public: virtual ~Client() = default; // Called when a terminal error on |socket| has occurred. - virtual void OnError(CastSocket* socket, openscreen::Error error) = 0; + virtual void OnError(CastSocket* socket, Error error) = 0; - virtual void OnMessage(CastSocket* socket, CastMessage message) = 0; + virtual void OnMessage(CastSocket* socket, + ::cast::channel::CastMessage message) = 0; }; - CastSocket(std::unique_ptr<openscreen::TlsConnection> connection, + CastSocket(std::unique_ptr<TlsConnection> connection, Client* client, uint32_t socket_id); ~CastSocket(); @@ -42,7 +42,7 @@ class CastSocket : public openscreen::TlsConnection::Client { // write-blocked, in which case |message| will be queued. An error will be // returned if |message| cannot be serialized for any reason, even while // write-blocked. - openscreen::Error SendMessage(const CastMessage& message); + Error SendMessage(const ::cast::channel::CastMessage& message); void SetClient(Client* client); @@ -50,13 +50,11 @@ class CastSocket : public openscreen::TlsConnection::Client { uint32_t socket_id() const { return socket_id_; } - // openscreen::TlsConnection::Client overrides. - void OnWriteBlocked(openscreen::TlsConnection* connection) override; - void OnWriteUnblocked(openscreen::TlsConnection* connection) override; - void OnError(openscreen::TlsConnection* connection, - openscreen::Error error) override; - void OnRead(openscreen::TlsConnection* connection, - std::vector<uint8_t> block) override; + // TlsConnection::Client overrides. + void OnWriteBlocked(TlsConnection* connection) override; + void OnWriteUnblocked(TlsConnection* connection) override; + void OnError(TlsConnection* connection, Error error) override; + void OnRead(TlsConnection* connection, std::vector<uint8_t> block) override; private: enum class State { @@ -66,14 +64,14 @@ class CastSocket : public openscreen::TlsConnection::Client { }; Client* client_; // May never be null. - const std::unique_ptr<openscreen::TlsConnection> connection_; + const std::unique_ptr<TlsConnection> connection_; std::vector<uint8_t> read_buffer_; const uint32_t socket_id_; State state_ = State::kOpen; std::vector<std::vector<uint8_t>> message_queue_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_CAST_SOCKET_H_ diff --git a/cast/common/channel/cast_socket_unittest.cc b/cast/common/channel/cast_socket_unittest.cc index e9df607e..b13fc2ed 100644 --- a/cast/common/channel/cast_socket_unittest.cc +++ b/cast/common/channel/cast_socket_unittest.cc @@ -10,15 +10,16 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace channel { + +using ::cast::channel::CastMessage; + namespace { using ::testing::_; using ::testing::Invoke; -using openscreen::ErrorOr; - class CastSocketTest : public ::testing::Test { public: void SetUp() override { @@ -35,9 +36,7 @@ class CastSocketTest : public ::testing::Test { } protected: - openscreen::MockTlsConnection& connection() { - return *fake_socket_.connection; - } + MockTlsConnection& connection() { return *fake_socket_.connection; } MockCastSocketClient& mock_client() { return fake_socket_.mock_client; } CastSocket& socket() { return fake_socket_.socket; } @@ -131,7 +130,7 @@ TEST_F(CastSocketTest, ErrorWhileEmptyingQueue) { frame_serial_, std::vector<uint8_t>(reinterpret_cast<const uint8_t*>(data), reinterpret_cast<const uint8_t*>(data) + len)); - connection().OnError(openscreen::Error::Code::kUnknownError); + connection().OnError(Error::Code::kUnknownError); })); connection().OnWriteUnblocked(); @@ -144,15 +143,14 @@ TEST_F(CastSocketTest, SanitizedAddress) { EXPECT_EQ(result1[0], 1u); EXPECT_EQ(result1[1], 9u); - FakeCastSocket v6_socket( - openscreen::IPEndpoint{{1, 2, 3, 4}, 1025}, - openscreen::IPEndpoint{ - {0x1819, 0x1a1b, 0x1c1d, 0x1e1f, 0x207b, 0x7c7d, 0x7e7f, 0x8081}, - 4321}); + FakeCastSocket v6_socket(IPEndpoint{{1, 2, 3, 4}, 1025}, + IPEndpoint{{0x1819, 0x1a1b, 0x1c1d, 0x1e1f, 0x207b, + 0x7c7d, 0x7e7f, 0x8081}, + 4321}); std::array<uint8_t, 2> result2 = v6_socket.socket.GetSanitizedIpAddress(); EXPECT_EQ(result2[0], 128); EXPECT_EQ(result2[1], 129); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/connection_namespace_handler.cc b/cast/common/channel/connection_namespace_handler.cc index d15ae39b..40b2b840 100644 --- a/cast/common/channel/connection_namespace_handler.cc +++ b/cast/common/channel/connection_namespace_handler.cc @@ -17,15 +17,16 @@ #include "util/json/json_value.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { -using openscreen::ErrorOr; +using ::cast::channel::CastMessage; +using ::cast::channel::CastMessage_PayloadType; namespace { bool IsValidProtocolVersion(int version) { - return CastMessage_ProtocolVersion_IsValid(version); + return ::cast::channel::CastMessage_ProtocolVersion_IsValid(version); } absl::optional<int> FindMaxProtocolVersion(const Json::Value* version, @@ -35,7 +36,7 @@ absl::optional<int> FindMaxProtocolVersion(const Json::Value* version, "Assuming ArrayIndex is integral"); absl::optional<int> max_version; if (version_list && version_list->isArray()) { - max_version = CastMessage_ProtocolVersion_CASTV2_1_0; + max_version = ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0; for (auto it = version_list->begin(), end = version_list->end(); it != end; ++it) { if (it->isInt()) { @@ -50,7 +51,7 @@ absl::optional<int> FindMaxProtocolVersion(const Json::Value* version, int version_int = version->asInt(); if (IsValidProtocolVersion(version_int)) { if (!max_version) { - max_version = CastMessage_ProtocolVersion_CASTV2_1_0; + max_version = ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0; } if (version_int > max_version) { max_version = version_int; @@ -64,7 +65,7 @@ VirtualConnection::CloseReason GetCloseReason( const Json::Value& parsed_message) { VirtualConnection::CloseReason reason = VirtualConnection::CloseReason::kClosedByPeer; - absl::optional<int> reason_code = openscreen::MaybeGetInt( + absl::optional<int> reason_code = MaybeGetInt( parsed_message, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyReasonCode)); if (reason_code) { int code = reason_code.value(); @@ -90,12 +91,12 @@ ConnectionNamespaceHandler::~ConnectionNamespaceHandler() = default; void ConnectionNamespaceHandler::OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) { + CastMessage message) { if (message.payload_type() != CastMessage_PayloadType::CastMessage_PayloadType_STRING) { return; } - ErrorOr<Json::Value> result = openscreen::json::Parse(message.payload_utf8()); + ErrorOr<Json::Value> result = json::Parse(message.payload_utf8()); if (result.is_error()) { return; } @@ -105,8 +106,8 @@ void ConnectionNamespaceHandler::OnMessage(VirtualConnectionRouter* router, return; } - absl::optional<absl::string_view> type = openscreen::MaybeGetString( - value, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyType)); + absl::optional<absl::string_view> type = + MaybeGetString(value, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyType)); if (!type) { // TODO(btolsch): Some of these paths should have error reporting. One // possibility is to pass errors back through |router| so higher-level code @@ -128,8 +129,8 @@ void ConnectionNamespaceHandler::OnMessage(VirtualConnectionRouter* router, void ConnectionNamespaceHandler::HandleConnect(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message, - Json::Value&& parsed_message) { + CastMessage message, + Json::Value parsed_message) { if (message.destination_id() == kBroadcastId || message.source_id() == kBroadcastId) { return; @@ -143,7 +144,7 @@ void ConnectionNamespaceHandler::HandleConnect(VirtualConnectionRouter* router, return; } - absl::optional<int> maybe_conn_type = openscreen::MaybeGetInt( + absl::optional<int> maybe_conn_type = MaybeGetInt( parsed_message, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyConnType)); VirtualConnection::Type conn_type = VirtualConnection::Type::kStrong; if (maybe_conn_type) { @@ -160,7 +161,7 @@ void ConnectionNamespaceHandler::HandleConnect(VirtualConnectionRouter* router, data.type = conn_type; - absl::optional<absl::string_view> user_agent = openscreen::MaybeGetString( + absl::optional<absl::string_view> user_agent = MaybeGetString( parsed_message, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyUserAgent)); if (user_agent) { data.user_agent = std::string(user_agent.value()); @@ -203,8 +204,8 @@ void ConnectionNamespaceHandler::HandleConnect(VirtualConnectionRouter* router, void ConnectionNamespaceHandler::HandleClose(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message, - Json::Value&& parsed_message) { + CastMessage message, + Json::Value parsed_message) { VirtualConnection virtual_conn{std::move(message.destination_id()), std::move(message.source_id()), socket->socket_id()}; @@ -221,11 +222,11 @@ void ConnectionNamespaceHandler::HandleClose(VirtualConnectionRouter* router, } void ConnectionNamespaceHandler::SendClose(VirtualConnectionRouter* router, - VirtualConnection&& virtual_conn) { + VirtualConnection virtual_conn) { Json::Value close_message(Json::ValueType::objectValue); close_message[kMessageKeyType] = kMessageTypeClose; - ErrorOr<std::string> result = openscreen::json::Stringify(close_message); + ErrorOr<std::string> result = json::Stringify(close_message); if (result.is_error()) { return; } @@ -244,7 +245,7 @@ void ConnectionNamespaceHandler::SendConnectedResponse( connected_message[kMessageKeyProtocolVersion] = static_cast<int>(max_protocol_version); - ErrorOr<std::string> result = openscreen::json::Stringify(connected_message); + ErrorOr<std::string> result = json::Stringify(connected_message); if (result.is_error()) { return; } @@ -254,5 +255,5 @@ void ConnectionNamespaceHandler::SendConnectedResponse( MakeSimpleUTF8Message(kConnectionNamespace, std::move(result.value()))); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/connection_namespace_handler.h b/cast/common/channel/connection_namespace_handler.h index be0a138f..5307e896 100644 --- a/cast/common/channel/connection_namespace_handler.h +++ b/cast/common/channel/connection_namespace_handler.h @@ -6,10 +6,11 @@ #define CAST_COMMON_CHANNEL_CONNECTION_NAMESPACE_HANDLER_H_ #include "cast/common/channel/cast_message_handler.h" +#include "cast/common/channel/proto/cast_channel.pb.h" #include "util/json/json_serialization.h" +namespace openscreen { namespace cast { -namespace channel { struct VirtualConnection; class VirtualConnectionManager; @@ -35,20 +36,20 @@ class ConnectionNamespaceHandler final : public CastMessageHandler { // CastMessageHandler overrides. void OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) override; + ::cast::channel::CastMessage message) override; private: void HandleConnect(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message, - Json::Value&& parsed_message); + ::cast::channel::CastMessage message, + Json::Value parsed_message); void HandleClose(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message, - Json::Value&& parsed_message); + ::cast::channel::CastMessage message, + Json::Value parsed_message); void SendClose(VirtualConnectionRouter* router, - VirtualConnection&& virtual_conn); + VirtualConnection virtual_conn); void SendConnectedResponse(VirtualConnectionRouter* router, const VirtualConnection& virtual_conn, int max_protocol_version); @@ -57,7 +58,7 @@ class ConnectionNamespaceHandler final : public CastMessageHandler { VirtualConnectionPolicy* const vc_policy_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_CONNECTION_NAMESPACE_HANDLER_H_ diff --git a/cast/common/channel/connection_namespace_handler_unittest.cc b/cast/common/channel/connection_namespace_handler_unittest.cc index ce7ea3f6..4913b275 100644 --- a/cast/common/channel/connection_namespace_handler_unittest.cc +++ b/cast/common/channel/connection_namespace_handler_unittest.cc @@ -17,15 +17,16 @@ #include "util/json/json_value.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { namespace { using ::testing::_; using ::testing::Invoke; using ::testing::NiceMock; -using openscreen::ErrorOr; +using ::cast::channel::CastMessage; +using ::cast::channel::CastMessage_ProtocolVersion; class MockVirtualConnectionPolicy : public ConnectionNamespaceHandler::VirtualConnectionPolicy { @@ -38,13 +39,12 @@ class MockVirtualConnectionPolicy (const, override)); }; -CastMessage MakeConnectMessage( +CastMessage MakeVersionedConnectMessage( const std::string& source_id, const std::string& destination_id, absl::optional<CastMessage_ProtocolVersion> version, std::vector<CastMessage_ProtocolVersion> version_list) { - CastMessage connect_message = - channel::MakeConnectMessage(source_id, destination_id); + CastMessage connect_message = MakeConnectMessage(source_id, destination_id); Json::Value message(Json::ValueType::objectValue); message[kMessageKeyType] = kMessageTypeConnect; if (version) { @@ -57,7 +57,7 @@ CastMessage MakeConnectMessage( } message[kMessageKeyProtocolVersionList] = std::move(list); } - ErrorOr<std::string> result = openscreen::json::Stringify(message); + ErrorOr<std::string> result = json::Stringify(message); OSP_DCHECK(result); connect_message.set_payload_utf8(std::move(result.value())); return connect_message; @@ -69,11 +69,12 @@ void VerifyConnectionMessage(const CastMessage& message, EXPECT_EQ(message.source_id(), source_id); EXPECT_EQ(message.destination_id(), destination_id); EXPECT_EQ(message.namespace_(), kConnectionNamespace); - ASSERT_EQ(message.payload_type(), CastMessage_PayloadType_STRING); + ASSERT_EQ(message.payload_type(), + ::cast::channel::CastMessage_PayloadType_STRING); } Json::Value ParseConnectionMessage(const CastMessage& message) { - ErrorOr<Json::Value> result = openscreen::json::Parse(message.payload_utf8()); + ErrorOr<Json::Value> result = json::Parse(message.payload_utf8()); OSP_CHECK(result) << message.payload_utf8(); return result.value(); } @@ -101,7 +102,7 @@ class ConnectionNamespaceHandlerTest : public ::testing::Test { CastMessage message) { VerifyConnectionMessage(message, source_id, destination_id); Json::Value value = ParseConnectionMessage(message); - absl::optional<absl::string_view> type = openscreen::MaybeGetString( + absl::optional<absl::string_view> type = MaybeGetString( value, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyType)); ASSERT_TRUE(type) << message.payload_utf8(); EXPECT_EQ(type.value(), kMessageTypeClose) << message.payload_utf8(); @@ -118,13 +119,13 @@ class ConnectionNamespaceHandlerTest : public ::testing::Test { CastSocket* socket, CastMessage message) { VerifyConnectionMessage(message, source_id, destination_id); Json::Value value = ParseConnectionMessage(message); - absl::optional<absl::string_view> type = openscreen::MaybeGetString( + absl::optional<absl::string_view> type = MaybeGetString( value, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyType)); ASSERT_TRUE(type) << message.payload_utf8(); EXPECT_EQ(type.value(), kMessageTypeConnected) << message.payload_utf8(); if (version) { - absl::optional<int> message_version = openscreen::MaybeGetInt( + absl::optional<int> message_version = MaybeGetInt( value, JSON_EXPAND_FIND_CONSTANT_ARGS(kMessageKeyProtocolVersion)); ASSERT_TRUE(message_version) << message.payload_utf8(); @@ -170,25 +171,29 @@ TEST_F(ConnectionNamespaceHandlerTest, PolicyDeniesConnection) { } TEST_F(ConnectionNamespaceHandlerTest, ConnectWithVersion) { - ExpectConnectedMessage(&fake_cast_socket_pair_.mock_peer_client, receiver_id_, - sender_id_, CastMessage_ProtocolVersion_CASTV2_1_2); + ExpectConnectedMessage( + &fake_cast_socket_pair_.mock_peer_client, receiver_id_, sender_id_, + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_2); connection_namespace_handler_.OnMessage( &router_, socket_, - MakeConnectMessage(sender_id_, receiver_id_, - CastMessage_ProtocolVersion_CASTV2_1_2, {})); + MakeVersionedConnectMessage( + sender_id_, receiver_id_, + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_2, {})); EXPECT_TRUE(vc_manager_.GetConnectionData( VirtualConnection{receiver_id_, sender_id_, socket_->socket_id()})); } TEST_F(ConnectionNamespaceHandlerTest, ConnectWithVersionList) { - ExpectConnectedMessage(&fake_cast_socket_pair_.mock_peer_client, receiver_id_, - sender_id_, CastMessage_ProtocolVersion_CASTV2_1_3); + ExpectConnectedMessage( + &fake_cast_socket_pair_.mock_peer_client, receiver_id_, sender_id_, + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_3); connection_namespace_handler_.OnMessage( &router_, socket_, - MakeConnectMessage(sender_id_, receiver_id_, - CastMessage_ProtocolVersion_CASTV2_1_2, - {CastMessage_ProtocolVersion_CASTV2_1_3, - CastMessage_ProtocolVersion_CASTV2_1_0})); + MakeVersionedConnectMessage( + sender_id_, receiver_id_, + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_2, + {::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_3, + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0})); EXPECT_TRUE(vc_manager_.GetConnectionData( VirtualConnection{receiver_id_, sender_id_, socket_->socket_id()})); } @@ -217,5 +222,5 @@ TEST_F(ConnectionNamespaceHandlerTest, CloseUnknown) { VirtualConnection{receiver_id_, sender_id_, socket_->socket_id()})); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/message_framer.cc b/cast/common/channel/message_framer.cc index 2494a6ea..bc0c144b 100644 --- a/cast/common/channel/message_framer.cc +++ b/cast/common/channel/message_framer.cc @@ -13,12 +13,10 @@ #include "util/big_endian.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { namespace message_serialization { -using openscreen::Error; - namespace { static constexpr size_t kHeaderSize = sizeof(uint32_t); @@ -28,13 +26,14 @@ static constexpr size_t kMaxBodySize = 65536; } // namespace -ErrorOr<std::vector<uint8_t>> Serialize(const CastMessage& message) { +ErrorOr<std::vector<uint8_t>> Serialize( + const ::cast::channel::CastMessage& message) { const size_t message_size = message.ByteSizeLong(); if (message_size > kMaxBodySize || message_size == 0) { return Error::Code::kCastV2InvalidMessage; } std::vector<uint8_t> out(message_size + kHeaderSize, 0); - openscreen::WriteBigEndian<uint32_t>(message_size, out.data()); + WriteBigEndian<uint32_t>(message_size, out.data()); if (!message.SerializeToArray(&out[kHeaderSize], message_size)) { return Error::Code::kCastV2InvalidMessage; } @@ -46,8 +45,7 @@ ErrorOr<DeserializeResult> TryDeserialize(absl::Span<uint8_t> input) { return Error::Code::kInsufficientBuffer; } - const uint32_t message_size = - openscreen::ReadBigEndian<uint32_t>(input.data()); + const uint32_t message_size = ReadBigEndian<uint32_t>(input.data()); if (message_size > kMaxBodySize) { return Error::Code::kCastV2InvalidMessage; } @@ -67,5 +65,5 @@ ErrorOr<DeserializeResult> TryDeserialize(absl::Span<uint8_t> input) { } } // namespace message_serialization -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/message_framer.h b/cast/common/channel/message_framer.h index c092487c..570b499a 100644 --- a/cast/common/channel/message_framer.h +++ b/cast/common/channel/message_framer.h @@ -15,18 +15,17 @@ #include "cast/common/channel/proto/cast_channel.pb.h" #include "platform/base/error.h" +namespace openscreen { namespace cast { -namespace channel { namespace message_serialization { -using openscreen::ErrorOr; - // Serializes |message_proto| into |message_data|. // Returns true if the message was serialized successfully, false otherwise. -ErrorOr<std::vector<uint8_t>> Serialize(const CastMessage& message); +ErrorOr<std::vector<uint8_t>> Serialize( + const ::cast::channel::CastMessage& message); struct DeserializeResult { - CastMessage message; + ::cast::channel::CastMessage message; size_t length; }; @@ -37,7 +36,7 @@ struct DeserializeResult { ErrorOr<DeserializeResult> TryDeserialize(absl::Span<uint8_t> input); } // namespace message_serialization -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_MESSAGE_FRAMER_H_ diff --git a/cast/common/channel/message_framer_unittest.cc b/cast/common/channel/message_framer_unittest.cc index ae2ff33e..e70459e6 100644 --- a/cast/common/channel/message_framer_unittest.cc +++ b/cast/common/channel/message_framer_unittest.cc @@ -14,11 +14,11 @@ #include "util/big_endian.h" #include "util/std_util.h" +namespace openscreen { namespace cast { -namespace channel { namespace message_serialization { -using openscreen::Error; +using ::cast::channel::CastMessage; namespace { @@ -149,5 +149,5 @@ TEST_F(CastFramerTest, TestUnparsableBodyProto) { } } // namespace message_serialization -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/message_util.cc b/cast/common/channel/message_util.cc index 77396abd..b4a7f9f6 100644 --- a/cast/common/channel/message_util.cc +++ b/cast/common/channel/message_util.cc @@ -4,10 +4,12 @@ #include "cast/common/channel/message_util.h" +namespace openscreen { namespace cast { -namespace channel { namespace { +using ::cast::channel::CastMessage; + CastMessage MakeConnectionMessage(const std::string& source_id, const std::string& destination_id) { CastMessage connect_message; @@ -25,7 +27,7 @@ CastMessage MakeSimpleUTF8Message(const std::string& namespace_, CastMessage message; message.set_protocol_version(kDefaultOutgoingMessageVersion); message.set_namespace_(namespace_); - message.set_payload_type(CastMessage_PayloadType_STRING); + message.set_payload_type(::cast::channel::CastMessage_PayloadType_STRING); message.set_payload_utf8(std::move(payload)); return message; } @@ -34,7 +36,8 @@ CastMessage MakeConnectMessage(const std::string& source_id, const std::string& destination_id) { CastMessage connect_message = MakeConnectionMessage(source_id, destination_id); - connect_message.set_payload_type(CastMessage_PayloadType_STRING); + connect_message.set_payload_type( + ::cast::channel::CastMessage_PayloadType_STRING); connect_message.set_payload_utf8(R"!({"type": "CONNECT"})!"); return connect_message; } @@ -42,10 +45,11 @@ CastMessage MakeConnectMessage(const std::string& source_id, CastMessage MakeCloseMessage(const std::string& source_id, const std::string& destination_id) { CastMessage close_message = MakeConnectionMessage(source_id, destination_id); - close_message.set_payload_type(CastMessage_PayloadType_STRING); + close_message.set_payload_type( + ::cast::channel::CastMessage_PayloadType_STRING); close_message.set_payload_utf8(R"!({"type": "CLOSE"})!"); return close_message; } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/message_util.h b/cast/common/channel/message_util.h index 6cf4b7b2..b9177e87 100644 --- a/cast/common/channel/message_util.h +++ b/cast/common/channel/message_util.h @@ -8,8 +8,8 @@ #include "absl/strings/string_view.h" #include "cast/common/channel/proto/cast_channel.pb.h" +namespace openscreen { namespace cast { -namespace channel { // Reserved message namespaces for internal messages. static constexpr char kCastInternalNamespacePrefix[] = @@ -34,8 +34,9 @@ static constexpr char kPlatformReceiverId[] = "receiver-0"; static constexpr char kBroadcastId[] = "*"; -static constexpr CastMessage_ProtocolVersion kDefaultOutgoingMessageVersion = - CastMessage_ProtocolVersion_CASTV2_1_0; +static constexpr ::cast::channel::CastMessage_ProtocolVersion + kDefaultOutgoingMessageVersion = + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0; // JSON message key strings. static constexpr char kMessageKeyType[] = "type"; @@ -51,7 +52,7 @@ static constexpr char kMessageTypeConnect[] = "CONNECT"; static constexpr char kMessageTypeClose[] = "CLOSE"; static constexpr char kMessageTypeConnected[] = "CONNECTED"; -inline bool IsAuthMessage(const CastMessage& message) { +inline bool IsAuthMessage(const ::cast::channel::CastMessage& message) { return message.namespace_() == kAuthNamespace; } @@ -60,15 +61,18 @@ inline bool IsTransportNamespace(absl::string_view namespace_) { (namespace_.find_first_of(kTransportNamespacePrefix) == 0); } -CastMessage MakeSimpleUTF8Message(const std::string& namespace_, - std::string payload); +::cast::channel::CastMessage MakeSimpleUTF8Message( + const std::string& namespace_, + std::string payload); -CastMessage MakeConnectMessage(const std::string& source_id, - const std::string& destination_id); -CastMessage MakeCloseMessage(const std::string& source_id, - const std::string& destination_id); +::cast::channel::CastMessage MakeConnectMessage( + const std::string& source_id, + const std::string& destination_id); +::cast::channel::CastMessage MakeCloseMessage( + const std::string& source_id, + const std::string& destination_id); -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_MESSAGE_UTIL_H_ diff --git a/cast/common/channel/namespace_router.cc b/cast/common/channel/namespace_router.cc index 00be17d3..041d8f3f 100644 --- a/cast/common/channel/namespace_router.cc +++ b/cast/common/channel/namespace_router.cc @@ -6,8 +6,8 @@ #include "cast/common/channel/proto/cast_channel.pb.h" +namespace openscreen { namespace cast { -namespace channel { NamespaceRouter::NamespaceRouter() = default; NamespaceRouter::~NamespaceRouter() = default; @@ -23,7 +23,7 @@ void NamespaceRouter::RemoveNamespaceHandler(const std::string& namespace_) { void NamespaceRouter::OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) { + ::cast::channel::CastMessage message) { const std::string& ns = message.namespace_(); auto it = handlers_.find(ns); if (it != handlers_.end()) { @@ -31,5 +31,5 @@ void NamespaceRouter::OnMessage(VirtualConnectionRouter* router, } } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/namespace_router.h b/cast/common/channel/namespace_router.h index 12940a3a..0b6b581c 100644 --- a/cast/common/channel/namespace_router.h +++ b/cast/common/channel/namespace_router.h @@ -9,9 +9,10 @@ #include <string> #include "cast/common/channel/cast_message_handler.h" +#include "cast/common/channel/proto/cast_channel.pb.h" +namespace openscreen { namespace cast { -namespace channel { class NamespaceRouter final : public CastMessageHandler { public: @@ -24,13 +25,13 @@ class NamespaceRouter final : public CastMessageHandler { // CastMessageHandler overrides. void OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) override; + ::cast::channel::CastMessage message) override; private: std::map<std::string /* namespace */, CastMessageHandler*> handlers_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_NAMESPACE_ROUTER_H_ diff --git a/cast/common/channel/namespace_router_unittest.cc b/cast/common/channel/namespace_router_unittest.cc index 5b35cd4e..a4126ddf 100644 --- a/cast/common/channel/namespace_router_unittest.cc +++ b/cast/common/channel/namespace_router_unittest.cc @@ -13,10 +13,11 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace channel { namespace { +using ::cast::channel::CastMessage; using ::testing::_; using ::testing::Invoke; @@ -51,12 +52,12 @@ TEST_F(NamespaceRouterTest, MultipleHandlers) { EXPECT_CALL(media_handler, OnMessage(_, _, _)).Times(0); EXPECT_CALL(auth_handler, OnMessage(_, _, _)) .WillOnce(Invoke([](VirtualConnectionRouter* router, CastSocket*, - CastMessage&& message) { + CastMessage message) { EXPECT_EQ(message.namespace_(), "auth"); })); EXPECT_CALL(connection_handler, OnMessage(_, _, _)) .WillOnce(Invoke([](VirtualConnectionRouter* router, CastSocket*, - CastMessage&& message) { + CastMessage message) { EXPECT_EQ(message.namespace_(), "connection"); })); @@ -80,10 +81,9 @@ TEST_F(NamespaceRouterTest, RemoveHandler) { EXPECT_CALL(handler1, OnMessage(_, _, _)).Times(0); EXPECT_CALL(handler2, OnMessage(_, _, _)) - .WillOnce(Invoke([](VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) { - EXPECT_EQ("two", message.namespace_()); - })); + .WillOnce(Invoke( + [](VirtualConnectionRouter* router, CastSocket* socket, + CastMessage message) { EXPECT_EQ("two", message.namespace_()); })); CastMessage message1; message1.set_namespace_("one"); @@ -94,5 +94,5 @@ TEST_F(NamespaceRouterTest, RemoveHandler) { router_.OnMessage(&vc_router_, socket(), std::move(message2)); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/proto/authority_keys.proto b/cast/common/channel/proto/authority_keys.proto index 5689e364..1b99b8ee 100644 --- a/cast/common/channel/proto/authority_keys.proto +++ b/cast/common/channel/proto/authority_keys.proto @@ -6,7 +6,11 @@ syntax = "proto2"; option optimize_for = LITE_RUNTIME; -package cast_channel.proto; +// TODO(crbug.com/openscreen/90): Rename to openscreen.cast, to update to the +// current namespacing of the library. Also, this file should probably be moved +// to the public directory. And, all of this will have to be coordinated with a +// DEPS roll in Chromium (since Chromium code depends on this). +package cast.channel; message AuthorityKeys { message Key { diff --git a/cast/common/channel/proto/cast_channel.proto b/cast/common/channel/proto/cast_channel.proto index 3714e360..58fb6c4d 100644 --- a/cast/common/channel/proto/cast_channel.proto +++ b/cast/common/channel/proto/cast_channel.proto @@ -6,6 +6,10 @@ syntax = "proto2"; option optimize_for = LITE_RUNTIME; +// TODO(crbug.com/openscreen/90): Rename to openscreen.cast, to update to the +// current namespacing of the library. Also, this file should probably be moved +// to the public directory. And, all of this will have to be coordinated with a +// DEPS roll in Chromium (since Chromium code depends on this). package cast.channel; message CastMessage { diff --git a/cast/common/channel/test/fake_cast_socket.h b/cast/common/channel/test/fake_cast_socket.h index 105bfe70..4259d8cd 100644 --- a/cast/common/channel/test/fake_cast_socket.h +++ b/cast/common/channel/test/fake_cast_socket.h @@ -8,42 +8,38 @@ #include <memory> #include "cast/common/channel/cast_socket.h" +#include "cast/common/channel/proto/cast_channel.pb.h" #include "gmock/gmock.h" #include "platform/test/mock_tls_connection.h" +namespace openscreen { namespace cast { -namespace channel { class MockCastSocketClient final : public CastSocket::Client { public: ~MockCastSocketClient() override = default; - MOCK_METHOD(void, - OnError, - (CastSocket * socket, openscreen::Error error), - (override)); + MOCK_METHOD(void, OnError, (CastSocket * socket, Error error), (override)); MOCK_METHOD(void, OnMessage, - (CastSocket * socket, CastMessage message), + (CastSocket * socket, ::cast::channel::CastMessage message), (override)); }; struct FakeCastSocket { FakeCastSocket() : FakeCastSocket({{10, 0, 1, 7}, 1234}, {{10, 0, 1, 9}, 4321}) {} - FakeCastSocket(const openscreen::IPEndpoint& local, - const openscreen::IPEndpoint& remote) + FakeCastSocket(const IPEndpoint& local, const IPEndpoint& remote) : local(local), remote(remote), - moved_connection( - std::make_unique<openscreen::MockTlsConnection>(local, remote)), + moved_connection(std::make_unique<MockTlsConnection>(local, remote)), connection(moved_connection.get()), socket(std::move(moved_connection), &mock_client, 1) {} - openscreen::IPEndpoint local; - openscreen::IPEndpoint remote; - std::unique_ptr<openscreen::MockTlsConnection> moved_connection; - openscreen::MockTlsConnection* connection; + IPEndpoint local; + IPEndpoint remote; + std::unique_ptr<MockTlsConnection> moved_connection; + MockTlsConnection* connection; MockCastSocketClient mock_client; CastSocket socket; }; @@ -58,15 +54,13 @@ struct FakeCastSocketPair { using ::testing::Invoke; auto moved_connection = - std::make_unique<::testing::NiceMock<openscreen::MockTlsConnection>>( - local, remote); + std::make_unique<::testing::NiceMock<MockTlsConnection>>(local, remote); connection = moved_connection.get(); socket = std::make_unique<CastSocket>(std::move(moved_connection), &mock_client, 1); auto moved_peer = - std::make_unique<::testing::NiceMock<openscreen::MockTlsConnection>>( - remote, local); + std::make_unique<::testing::NiceMock<MockTlsConnection>>(remote, local); peer_connection = moved_peer.get(); peer_socket = std::make_unique<CastSocket>(std::move(moved_peer), &mock_peer_client, 2); @@ -86,19 +80,19 @@ struct FakeCastSocketPair { } ~FakeCastSocketPair() = default; - openscreen::IPEndpoint local{{10, 0, 1, 7}, 1234}; - openscreen::IPEndpoint remote{{10, 0, 1, 9}, 4321}; + IPEndpoint local{{10, 0, 1, 7}, 1234}; + IPEndpoint remote{{10, 0, 1, 9}, 4321}; - ::testing::NiceMock<openscreen::MockTlsConnection>* connection; + ::testing::NiceMock<MockTlsConnection>* connection; MockCastSocketClient mock_client; std::unique_ptr<CastSocket> socket; - ::testing::NiceMock<openscreen::MockTlsConnection>* peer_connection; + ::testing::NiceMock<MockTlsConnection>* peer_connection; MockCastSocketClient mock_peer_client; std::unique_ptr<CastSocket> peer_socket; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_TEST_FAKE_CAST_SOCKET_H_ diff --git a/cast/common/channel/test/mock_cast_message_handler.h b/cast/common/channel/test/mock_cast_message_handler.h index d35c002f..c725ebdc 100644 --- a/cast/common/channel/test/mock_cast_message_handler.h +++ b/cast/common/channel/test/mock_cast_message_handler.h @@ -6,10 +6,11 @@ #define CAST_COMMON_CHANNEL_TEST_MOCK_CAST_MESSAGE_HANDLER_H_ #include "cast/common/channel/cast_message_handler.h" +#include "cast/common/channel/proto/cast_channel.pb.h" #include "gmock/gmock.h" +namespace openscreen { namespace cast { -namespace channel { class MockCastMessageHandler final : public CastMessageHandler { public: @@ -17,11 +18,11 @@ class MockCastMessageHandler final : public CastMessageHandler { OnMessage, (VirtualConnectionRouter * router, CastSocket* socket, - CastMessage&& message), + ::cast::channel::CastMessage message), (override)); }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_TEST_MOCK_CAST_MESSAGE_HANDLER_H_ diff --git a/cast/common/channel/test/mock_socket_error_handler.h b/cast/common/channel/test/mock_socket_error_handler.h index 0e32f8c9..c7612169 100644 --- a/cast/common/channel/test/mock_socket_error_handler.h +++ b/cast/common/channel/test/mock_socket_error_handler.h @@ -9,10 +9,8 @@ #include "gmock/gmock.h" #include "platform/base/error.h" -using openscreen::Error; - +namespace openscreen { namespace cast { -namespace channel { class MockSocketErrorHandler : public VirtualConnectionRouter::SocketErrorHandler { @@ -21,7 +19,7 @@ class MockSocketErrorHandler MOCK_METHOD(void, OnError, (CastSocket * socket, Error error), (override)); }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_TEST_MOCK_SOCKET_ERROR_HANDLER_H_ diff --git a/cast/common/channel/virtual_connection.h b/cast/common/channel/virtual_connection.h index 69945708..a4045c92 100644 --- a/cast/common/channel/virtual_connection.h +++ b/cast/common/channel/virtual_connection.h @@ -9,8 +9,8 @@ #include <cstdint> #include <string> +namespace openscreen { namespace cast { -namespace channel { // Transport system on top of CastSocket that allows routing messages over a // single socket to different virtual endpoints (e.g. system messages vs. @@ -111,7 +111,7 @@ inline bool operator!=(const VirtualConnection& a, const VirtualConnection& b) { return !(a == b); } -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_VIRTUAL_CONNECTION_H_ diff --git a/cast/common/channel/virtual_connection_manager.cc b/cast/common/channel/virtual_connection_manager.cc index 8bac25e2..cda15ab8 100644 --- a/cast/common/channel/virtual_connection_manager.cc +++ b/cast/common/channel/virtual_connection_manager.cc @@ -6,8 +6,8 @@ #include <type_traits> +namespace openscreen { namespace cast { -namespace channel { VirtualConnectionManager::VirtualConnectionManager() = default; @@ -15,7 +15,7 @@ VirtualConnectionManager::~VirtualConnectionManager() = default; void VirtualConnectionManager::AddConnection( VirtualConnection virtual_connection, - VirtualConnection::AssociatedData&& associated_data) { + VirtualConnection::AssociatedData associated_data) { auto& socket_map = connections_[virtual_connection.socket_id]; auto local_entries = socket_map.equal_range(virtual_connection.local_id); auto it = std::find_if( @@ -115,5 +115,5 @@ VirtualConnectionManager::GetConnectionData( return absl::nullopt; } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/virtual_connection_manager.h b/cast/common/channel/virtual_connection_manager.h index 5bb5fdb1..a4d1823b 100644 --- a/cast/common/channel/virtual_connection_manager.h +++ b/cast/common/channel/virtual_connection_manager.h @@ -12,8 +12,8 @@ #include "absl/types/optional.h" #include "cast/common/channel/virtual_connection.h" +namespace openscreen { namespace cast { -namespace channel { // Maintains a collection of open VirtualConnections and associated data. class VirtualConnectionManager { @@ -22,7 +22,7 @@ class VirtualConnectionManager { ~VirtualConnectionManager(); void AddConnection(VirtualConnection virtual_connection, - VirtualConnection::AssociatedData&& associated_data); + VirtualConnection::AssociatedData associated_data); // Returns true if a connection matching |virtual_connection| was found and // removed. @@ -55,7 +55,7 @@ class VirtualConnectionManager { connections_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_VIRTUAL_CONNECTION_MANAGER_H_ diff --git a/cast/common/channel/virtual_connection_manager_unittest.cc b/cast/common/channel/virtual_connection_manager_unittest.cc index d14d8606..963fcac7 100644 --- a/cast/common/channel/virtual_connection_manager_unittest.cc +++ b/cast/common/channel/virtual_connection_manager_unittest.cc @@ -8,20 +8,20 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace channel { namespace { -static_assert(CastMessage_ProtocolVersion_CASTV2_1_0 == +static_assert(::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0 == static_cast<int>(VirtualConnection::ProtocolVersion::kV2_1_0), "V2 1.0 constants must be equal"); -static_assert(CastMessage_ProtocolVersion_CASTV2_1_1 == +static_assert(::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_1 == static_cast<int>(VirtualConnection::ProtocolVersion::kV2_1_1), "V2 1.1 constants must be equal"); -static_assert(CastMessage_ProtocolVersion_CASTV2_1_2 == +static_assert(::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_2 == static_cast<int>(VirtualConnection::ProtocolVersion::kV2_1_2), "V2 1.2 constants must be equal"); -static_assert(CastMessage_ProtocolVersion_CASTV2_1_3 == +static_assert(::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_3 == static_cast<int>(VirtualConnection::ProtocolVersion::kV2_1_3), "V2 1.3 constants must be equal"); @@ -138,5 +138,5 @@ TEST_F(VirtualConnectionManagerTest, RemoveConnectionsByIds) { EXPECT_FALSE(manager_.GetConnectionData(vc3_)); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/virtual_connection_router.cc b/cast/common/channel/virtual_connection_router.cc index 99fd05f2..fbec2054 100644 --- a/cast/common/channel/virtual_connection_router.cc +++ b/cast/common/channel/virtual_connection_router.cc @@ -11,10 +11,10 @@ #include "cast/common/channel/virtual_connection_manager.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { -using openscreen::Error; +using ::cast::channel::CastMessage; VirtualConnectionRouter::VirtualConnectionRouter( VirtualConnectionManager* vc_manager) @@ -53,7 +53,7 @@ void VirtualConnectionRouter::CloseSocket(uint32_t id) { } Error VirtualConnectionRouter::SendMessage(VirtualConnection virtual_conn, - CastMessage&& message) { + CastMessage message) { // TODO(btolsch): Check for broadcast message. if (!IsTransportNamespace(message.namespace_()) && !vc_manager_->GetConnectionData(virtual_conn)) { @@ -95,5 +95,5 @@ void VirtualConnectionRouter::OnMessage(CastSocket* socket, } } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/common/channel/virtual_connection_router.h b/cast/common/channel/virtual_connection_router.h index 745995cc..57ddf904 100644 --- a/cast/common/channel/virtual_connection_router.h +++ b/cast/common/channel/virtual_connection_router.h @@ -11,9 +11,10 @@ #include <string> #include "cast/common/channel/cast_socket.h" +#include "cast/common/channel/proto/cast_channel.pb.h" +namespace openscreen { namespace cast { -namespace channel { class CastMessageHandler; struct VirtualConnection; @@ -43,7 +44,7 @@ class VirtualConnectionRouter final : public CastSocket::Client { class SocketErrorHandler { public: virtual void OnClose(CastSocket* socket) = 0; - virtual void OnError(CastSocket* socket, openscreen::Error error) = 0; + virtual void OnError(CastSocket* socket, Error error) = 0; }; explicit VirtualConnectionRouter(VirtualConnectionManager* vc_manager); @@ -58,12 +59,13 @@ class VirtualConnectionRouter final : public CastSocket::Client { std::unique_ptr<CastSocket> socket); void CloseSocket(uint32_t id); - openscreen::Error SendMessage(VirtualConnection virtual_conn, - CastMessage&& message); + Error SendMessage(VirtualConnection virtual_conn, + ::cast::channel::CastMessage message); // CastSocket::Client overrides. - void OnError(CastSocket* socket, openscreen::Error error) override; - void OnMessage(CastSocket* socket, CastMessage message) override; + void OnError(CastSocket* socket, Error error) override; + void OnMessage(CastSocket* socket, + ::cast::channel::CastMessage message) override; private: struct SocketWithHandler { @@ -76,7 +78,7 @@ class VirtualConnectionRouter final : public CastSocket::Client { std::map<std::string /* local_id */, CastMessageHandler*> endpoints_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_COMMON_CHANNEL_VIRTUAL_CONNECTION_ROUTER_H_ diff --git a/cast/common/channel/virtual_connection_router_unittest.cc b/cast/common/channel/virtual_connection_router_unittest.cc index 40394805..936f4e41 100644 --- a/cast/common/channel/virtual_connection_router_unittest.cc +++ b/cast/common/channel/virtual_connection_router_unittest.cc @@ -12,10 +12,11 @@ #include "cast/common/channel/virtual_connection_manager.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace channel { namespace { +using ::cast::channel::CastMessage; using ::testing::_; using ::testing::Invoke; @@ -49,7 +50,8 @@ TEST_F(VirtualConnectionRouterTest, LocalIdHandler) { {}); CastMessage message; - message.set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0); + message.set_protocol_version( + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0); message.set_namespace_("zrqvn"); message.set_source_id("sender-9873"); message.set_destination_id("receiver-1234"); @@ -73,7 +75,8 @@ TEST_F(VirtualConnectionRouterTest, RemoveLocalIdHandler) { {}); CastMessage message; - message.set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0); + message.set_protocol_version( + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0); message.set_namespace_("zrqvn"); message.set_source_id("sender-9873"); message.set_destination_id("receiver-1234"); @@ -94,7 +97,8 @@ TEST_F(VirtualConnectionRouterTest, SendMessage) { {}); CastMessage message; - message.set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0); + message.set_protocol_version( + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0); message.set_namespace_("zrqvn"); message.set_source_id("receiver-1234"); message.set_destination_id("sender-4321"); @@ -105,7 +109,8 @@ TEST_F(VirtualConnectionRouterTest, SendMessage) { EXPECT_EQ(message.namespace_(), "zrqvn"); EXPECT_EQ(message.source_id(), "receiver-1234"); EXPECT_EQ(message.destination_id(), "sender-4321"); - ASSERT_EQ(message.payload_type(), CastMessage_PayloadType_STRING); + ASSERT_EQ(message.payload_type(), + ::cast::channel::CastMessage_PayloadType_STRING); EXPECT_EQ(message.payload_utf8(), "cnlybnq"); })); router_.SendMessage( @@ -113,5 +118,5 @@ TEST_F(VirtualConnectionRouterTest, SendMessage) { std::move(message)); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/receiver/BUILD.gn b/cast/receiver/BUILD.gn index e0a62eba..865b0ab1 100644 --- a/cast/receiver/BUILD.gn +++ b/cast/receiver/BUILD.gn @@ -38,6 +38,7 @@ source_set("test_helpers") { ] deps = [ "../../third_party/googletest:gtest", + "../common/channel/proto:channel_proto", ] } diff --git a/cast/receiver/channel/device_auth_namespace_handler.cc b/cast/receiver/channel/device_auth_namespace_handler.cc index a12a5b6c..9e9d5e3f 100644 --- a/cast/receiver/channel/device_auth_namespace_handler.cc +++ b/cast/receiver/channel/device_auth_namespace_handler.cc @@ -14,8 +14,17 @@ #include "platform/base/tls_credentials.h" #include "util/crypto/digest_sign.h" +using ::cast::channel::AuthChallenge; +using ::cast::channel::AuthError; +using ::cast::channel::AuthResponse; +using ::cast::channel::CastMessage; +using ::cast::channel::DeviceAuthMessage; +using ::cast::channel::HashAlgorithm; +using ::cast::channel::SignatureAlgorithm; + +namespace openscreen { namespace cast { -namespace channel { + namespace { CastMessage GenerateErrorMessage(AuthError::ErrorType error_type) { @@ -26,9 +35,10 @@ CastMessage GenerateErrorMessage(AuthError::ErrorType error_type) { message.SerializeToString(&payload); CastMessage response; - response.set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0); + response.set_protocol_version( + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0); response.set_namespace_(kAuthNamespace); - response.set_payload_type(CastMessage_PayloadType_BINARY); + response.set_payload_type(::cast::channel::CastMessage_PayloadType_BINARY); response.set_payload_binary(std::move(payload)); return response; } @@ -43,8 +53,9 @@ DeviceAuthNamespaceHandler::~DeviceAuthNamespaceHandler() = default; void DeviceAuthNamespaceHandler::OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) { - if (message.payload_type() != CastMessage_PayloadType_BINARY) { + CastMessage message) { + if (message.payload_type() != + ::cast::channel::CastMessage_PayloadType_BINARY) { return; } const std::string& payload = message.payload_binary(); @@ -70,14 +81,17 @@ void DeviceAuthNamespaceHandler::OnMessage(VirtualConnectionRouter* router, HashAlgorithm hash_alg = challenge.hash_algorithm(); // TODO(btolsch): Reconsider supporting SHA1 after further metrics // investigation. - if ((sig_alg != UNSPECIFIED && sig_alg != RSASSA_PKCS1v15) || - (hash_alg != SHA1 && hash_alg != SHA256)) { + if ((sig_alg != ::cast::channel::UNSPECIFIED && + sig_alg != ::cast::channel::RSASSA_PKCS1v15) || + (hash_alg != ::cast::channel::SHA1 && + hash_alg != ::cast::channel::SHA256)) { router->SendMessage( virtual_conn, GenerateErrorMessage(AuthError::SIGNATURE_ALGORITHM_UNAVAILABLE)); return; } - const EVP_MD* digest = hash_alg == SHA256 ? EVP_sha256() : EVP_sha1(); + const EVP_MD* digest = + hash_alg == ::cast::channel::SHA256 ? EVP_sha256() : EVP_sha1(); const absl::Span<const uint8_t> tls_cert_der = creds_provider_->GetCurrentTlsCertAsDer(); @@ -97,7 +111,7 @@ void DeviceAuthNamespaceHandler::OnMessage(VirtualConnectionRouter* router, ++it) { auth_response->add_intermediate_certificate(*it); } - auth_response->set_signature_algorithm(RSASSA_PKCS1v15); + auth_response->set_signature_algorithm(::cast::channel::RSASSA_PKCS1v15); auth_response->set_hash_algorithm(hash_alg); std::string sender_nonce; if (challenge.has_sender_nonce()) { @@ -114,8 +128,8 @@ void DeviceAuthNamespaceHandler::OnMessage(VirtualConnectionRouter* router, to_be_signed.insert(to_be_signed.end(), tls_cert_der.begin(), tls_cert_der.end()); - openscreen::ErrorOr<std::string> signature = openscreen::SignData( - digest, device_creds.private_key.get(), to_be_signed); + ErrorOr<std::string> signature = + SignData(digest, device_creds.private_key.get(), to_be_signed); if (!signature) { router->SendMessage(virtual_conn, GenerateErrorMessage(AuthError::INTERNAL_ERROR)); @@ -129,12 +143,13 @@ void DeviceAuthNamespaceHandler::OnMessage(VirtualConnectionRouter* router, std::string response_string; response_auth_message.SerializeToString(&response_string); CastMessage response; - response.set_protocol_version(CastMessage_ProtocolVersion_CASTV2_1_0); + response.set_protocol_version( + ::cast::channel::CastMessage_ProtocolVersion_CASTV2_1_0); response.set_namespace_(kAuthNamespace); - response.set_payload_type(CastMessage_PayloadType_BINARY); + response.set_payload_type(::cast::channel::CastMessage_PayloadType_BINARY); response.set_payload_binary(std::move(response_string)); router->SendMessage(virtual_conn, std::move(response)); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/receiver/channel/device_auth_namespace_handler.h b/cast/receiver/channel/device_auth_namespace_handler.h index e5e867cd..ec918e33 100644 --- a/cast/receiver/channel/device_auth_namespace_handler.h +++ b/cast/receiver/channel/device_auth_namespace_handler.h @@ -13,8 +13,8 @@ #include "absl/types/span.h" #include "cast/common/channel/cast_message_handler.h" +namespace openscreen { namespace cast { -namespace channel { struct DeviceCredentials { // The device's certificate chain in DER form, where |certs[0]| is the @@ -45,13 +45,13 @@ class DeviceAuthNamespaceHandler final : public CastMessageHandler { // CastMessageHandler overrides. void OnMessage(VirtualConnectionRouter* router, CastSocket* socket, - CastMessage&& message) override; + ::cast::channel::CastMessage message) override; private: CredentialsProvider* const creds_provider_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_RECEIVER_CHANNEL_DEVICE_AUTH_NAMESPACE_HANDLER_H_ diff --git a/cast/receiver/channel/device_auth_namespace_handler_unittest.cc b/cast/receiver/channel/device_auth_namespace_handler_unittest.cc index e3eb022d..9da260ce 100644 --- a/cast/receiver/channel/device_auth_namespace_handler_unittest.cc +++ b/cast/receiver/channel/device_auth_namespace_handler_unittest.cc @@ -16,10 +16,15 @@ #include "gtest/gtest.h" #include "testing/util/read_file.h" +namespace openscreen { namespace cast { -namespace channel { namespace { +using ::cast::channel::AuthResponse; +using ::cast::channel::CastMessage; +using ::cast::channel::DeviceAuthMessage; +using ::cast::channel::SignatureAlgorithm; + using ::testing::_; using ::testing::ElementsAreArray; using ::testing::Invoke; @@ -44,8 +49,6 @@ class DeviceAuthNamespaceHandlerTest : public ::testing::Test { DeviceAuthNamespaceHandler auth_handler_{&creds_}; }; -} // namespace - #define TEST_DATA_PREFIX OPENSCREEN_TEST_DATA_DIR "cast/receiver/channel/" // The tests in this file use a pre-recorded AuthChallenge as input and a @@ -73,7 +76,7 @@ TEST_F(DeviceAuthNamespaceHandlerTest, AuthResponse) { // |router_| and we will catch the result in |challenge_reply|. CastMessage auth_challenge; const std::string auth_challenge_string = - openscreen::ReadEntireFileToString(TEST_DATA_PREFIX "auth_challenge.pb"); + ReadEntireFileToString(TEST_DATA_PREFIX "auth_challenge.pb"); ASSERT_TRUE(auth_challenge.ParseFromString(auth_challenge_string)); CastMessage challenge_reply; @@ -85,12 +88,13 @@ TEST_F(DeviceAuthNamespaceHandlerTest, AuthResponse) { fake_cast_socket_pair_.peer_socket->SendMessage(std::move(auth_challenge)); const std::string auth_response_string = - openscreen::ReadEntireFileToString(TEST_DATA_PREFIX "auth_response.pb"); + ReadEntireFileToString(TEST_DATA_PREFIX "auth_response.pb"); AuthResponse expected_auth_response; ASSERT_TRUE(expected_auth_response.ParseFromString(auth_response_string)); DeviceAuthMessage auth_message; - ASSERT_EQ(challenge_reply.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(challenge_reply.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE(auth_message.ParseFromString(challenge_reply.payload_binary())); ASSERT_TRUE(auth_message.has_response()); ASSERT_FALSE(auth_message.has_challenge()); @@ -121,13 +125,14 @@ TEST_F(DeviceAuthNamespaceHandlerTest, BadNonce) { // |router_| and we will catch the result in |challenge_reply|. CastMessage auth_challenge; const std::string auth_challenge_string = - openscreen::ReadEntireFileToString(TEST_DATA_PREFIX "auth_challenge.pb"); + ReadEntireFileToString(TEST_DATA_PREFIX "auth_challenge.pb"); ASSERT_TRUE(auth_challenge.ParseFromString(auth_challenge_string)); // Change the nonce to be different from what was used to record the correct // response originally. DeviceAuthMessage msg; - ASSERT_EQ(auth_challenge.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(auth_challenge.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE(msg.ParseFromString(auth_challenge.payload_binary())); ASSERT_TRUE(msg.has_challenge()); std::string* nonce = msg.mutable_challenge()->mutable_sender_nonce(); @@ -145,12 +150,13 @@ TEST_F(DeviceAuthNamespaceHandlerTest, BadNonce) { fake_cast_socket_pair_.peer_socket->SendMessage(std::move(auth_challenge)); const std::string auth_response_string = - openscreen::ReadEntireFileToString(TEST_DATA_PREFIX "auth_response.pb"); + ReadEntireFileToString(TEST_DATA_PREFIX "auth_response.pb"); AuthResponse expected_auth_response; ASSERT_TRUE(expected_auth_response.ParseFromString(auth_response_string)); DeviceAuthMessage auth_message; - ASSERT_EQ(challenge_reply.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(challenge_reply.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE(auth_message.ParseFromString(challenge_reply.payload_binary())); ASSERT_TRUE(auth_message.has_response()); ASSERT_FALSE(auth_message.has_challenge()); @@ -170,12 +176,13 @@ TEST_F(DeviceAuthNamespaceHandlerTest, UnsupportedSignatureAlgorithm) { // |router_| and we will catch the result in |challenge_reply|. CastMessage auth_challenge; const std::string auth_challenge_string = - openscreen::ReadEntireFileToString(TEST_DATA_PREFIX "auth_challenge.pb"); + ReadEntireFileToString(TEST_DATA_PREFIX "auth_challenge.pb"); ASSERT_TRUE(auth_challenge.ParseFromString(auth_challenge_string)); // Change the signature algorithm an unsupported value. DeviceAuthMessage msg; - ASSERT_EQ(auth_challenge.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(auth_challenge.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE(msg.ParseFromString(auth_challenge.payload_binary())); ASSERT_TRUE(msg.has_challenge()); msg.mutable_challenge()->set_signature_algorithm( @@ -193,12 +200,14 @@ TEST_F(DeviceAuthNamespaceHandlerTest, UnsupportedSignatureAlgorithm) { fake_cast_socket_pair_.peer_socket->SendMessage(std::move(auth_challenge)); DeviceAuthMessage auth_message; - ASSERT_EQ(challenge_reply.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(challenge_reply.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE(auth_message.ParseFromString(challenge_reply.payload_binary())); ASSERT_FALSE(auth_message.has_response()); ASSERT_FALSE(auth_message.has_challenge()); ASSERT_TRUE(auth_message.has_error()); } -} // namespace channel +} // namespace } // namespace cast +} // namespace openscreen diff --git a/cast/receiver/channel/receiver_socket_factory.cc b/cast/receiver/channel/receiver_socket_factory.cc index a555717a..f4276e4d 100644 --- a/cast/receiver/channel/receiver_socket_factory.cc +++ b/cast/receiver/channel/receiver_socket_factory.cc @@ -6,8 +6,8 @@ #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { ReceiverSocketFactory::ReceiverSocketFactory(Client* client, CastSocket::Client* socket_client) @@ -46,5 +46,5 @@ void ReceiverSocketFactory::OnError(TlsConnectionFactory* factory, client_->OnError(this, error); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/receiver/channel/receiver_socket_factory.h b/cast/receiver/channel/receiver_socket_factory.h index 573da4d0..71a66cb2 100644 --- a/cast/receiver/channel/receiver_socket_factory.h +++ b/cast/receiver/channel/receiver_socket_factory.h @@ -11,13 +11,8 @@ #include "platform/api/tls_connection_factory.h" #include "platform/base/ip_address.h" +namespace openscreen { namespace cast { -namespace channel { - -using openscreen::Error; -using openscreen::IPEndpoint; -using openscreen::TlsConnection; -using openscreen::TlsConnectionFactory; class ReceiverSocketFactory final : public TlsConnectionFactory::Client { public: @@ -49,7 +44,7 @@ class ReceiverSocketFactory final : public TlsConnectionFactory::Client { CastSocket::Client* const socket_client_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_RECEIVER_CHANNEL_RECEIVER_SOCKET_FACTORY_H_ diff --git a/cast/receiver/channel/testing/device_auth_test_helpers.cc b/cast/receiver/channel/testing/device_auth_test_helpers.cc index dace8429..51d7ebaa 100644 --- a/cast/receiver/channel/testing/device_auth_test_helpers.cc +++ b/cast/receiver/channel/testing/device_auth_test_helpers.cc @@ -6,19 +6,19 @@ #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace channel { void InitStaticCredentialsFromFiles(StaticCredentialsProvider* creds, bssl::UniquePtr<X509>* parsed_cert, - certificate::TrustStore* fake_trust_store, + TrustStore* fake_trust_store, absl::string_view privkey_filename, absl::string_view chain_filename, absl::string_view tls_filename) { - auto private_key = certificate::testing::ReadKeyFromPemFile(privkey_filename); + auto private_key = testing::ReadKeyFromPemFile(privkey_filename); ASSERT_TRUE(private_key); std::vector<std::string> certs = - certificate::testing::ReadCertificatesFromPemFile(chain_filename); + testing::ReadCertificatesFromPemFile(chain_filename); ASSERT_GT(certs.size(), 1u); // Use the root of the chain as the trust store for the test. @@ -35,7 +35,7 @@ void InitStaticCredentialsFromFiles(StaticCredentialsProvider* creds, std::move(certs), std::move(private_key), std::string()}; const std::vector<std::string> tls_cert = - certificate::testing::ReadCertificatesFromPemFile(tls_filename); + testing::ReadCertificatesFromPemFile(tls_filename); ASSERT_EQ(tls_cert.size(), 1u); data = reinterpret_cast<const uint8_t*>(tls_cert[0].data()); if (parsed_cert) { @@ -47,5 +47,5 @@ void InitStaticCredentialsFromFiles(StaticCredentialsProvider* creds, creds->tls_cert_der.assign(begin, begin + tls_cert[0].size()); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/receiver/channel/testing/device_auth_test_helpers.h b/cast/receiver/channel/testing/device_auth_test_helpers.h index 81f8266b..c82b3da7 100644 --- a/cast/receiver/channel/testing/device_auth_test_helpers.h +++ b/cast/receiver/channel/testing/device_auth_test_helpers.h @@ -13,8 +13,8 @@ #include "cast/common/certificate/test_helpers.h" #include "cast/receiver/channel/device_auth_namespace_handler.h" +namespace openscreen { namespace cast { -namespace channel { class StaticCredentialsProvider final : public DeviceAuthNamespaceHandler::CredentialsProvider { @@ -35,12 +35,12 @@ class StaticCredentialsProvider final void InitStaticCredentialsFromFiles(StaticCredentialsProvider* creds, bssl::UniquePtr<X509>* parsed_cert, - certificate::TrustStore* fake_trust_store, + TrustStore* fake_trust_store, absl::string_view privkey_filename, absl::string_view chain_filename, absl::string_view tls_filename); -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_RECEIVER_CHANNEL_TESTING_DEVICE_AUTH_TEST_HELPERS_H_ diff --git a/cast/sender/channel/cast_auth_util.cc b/cast/sender/channel/cast_auth_util.cc index 5201aa11..6954980a 100644 --- a/cast/sender/channel/cast_auth_util.cc +++ b/cast/sender/channel/cast_auth_util.cc @@ -16,8 +16,14 @@ #include "platform/base/error.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { + +using ::cast::channel::AuthResponse; +using ::cast::channel::CastMessage; +using ::cast::channel::DeviceAuthMessage; +using ::cast::channel::HashAlgorithm; + namespace { #define PARSE_ERROR_PREFIX "Failed to parse auth message: " @@ -31,40 +37,35 @@ const int kNonceSizeInBytes = 16; // The number of hours after which a nonce is regenerated. long kNonceExpirationTimeInHours = 24; -using CastCertError = openscreen::Error::Code; - // Extracts an embedded DeviceAuthMessage payload from an auth challenge reply // message. -openscreen::Error ParseAuthMessage(const CastMessage& challenge_reply, - DeviceAuthMessage* auth_message) { - if (challenge_reply.payload_type() != CastMessage_PayloadType_BINARY) { - return openscreen::Error(CastCertError::kCastV2WrongPayloadType, - PARSE_ERROR_PREFIX - "Wrong payload type in challenge reply"); +Error ParseAuthMessage(const CastMessage& challenge_reply, + DeviceAuthMessage* auth_message) { + if (challenge_reply.payload_type() != + ::cast::channel::CastMessage_PayloadType_BINARY) { + return Error(Error::Code::kCastV2WrongPayloadType, + PARSE_ERROR_PREFIX "Wrong payload type in challenge reply"); } if (!challenge_reply.has_payload_binary()) { - return openscreen::Error( - CastCertError::kCastV2NoPayload, PARSE_ERROR_PREFIX - "Payload type is binary but payload_binary field not set"); + return Error(Error::Code::kCastV2NoPayload, PARSE_ERROR_PREFIX + "Payload type is binary but payload_binary field not set"); } if (!auth_message->ParseFromString(challenge_reply.payload_binary())) { - return openscreen::Error( - CastCertError::kCastV2PayloadParsingFailed, PARSE_ERROR_PREFIX - "Cannot parse binary payload into DeviceAuthMessage"); + return Error(Error::Code::kCastV2PayloadParsingFailed, PARSE_ERROR_PREFIX + "Cannot parse binary payload into DeviceAuthMessage"); } if (auth_message->has_error()) { std::stringstream ss; ss << PARSE_ERROR_PREFIX "Auth message error: " << auth_message->error().error_type(); - return openscreen::Error(CastCertError::kCastV2MessageError, ss.str()); + return Error(Error::Code::kCastV2MessageError, ss.str()); } if (!auth_message->has_response()) { - return openscreen::Error(CastCertError::kCastV2NoResponse, - PARSE_ERROR_PREFIX - "Auth message has no response field"); + return Error(Error::Code::kCastV2NoResponse, + PARSE_ERROR_PREFIX "Auth message has no response field"); } - return openscreen::Error::None(); + return Error::None(); } class CastNonce { @@ -85,11 +86,11 @@ class CastNonce { OSP_CHECK_EQ( RAND_bytes(reinterpret_cast<uint8_t*>(&nonce_[0]), kNonceSizeInBytes), 1); - nonce_generation_time_ = openscreen::GetWallTimeSinceUnixEpoch(); + nonce_generation_time_ = GetWallTimeSinceUnixEpoch(); } void EnsureNonceTimely() { - if (openscreen::GetWallTimeSinceUnixEpoch() > + if (GetWallTimeSinceUnixEpoch() > (nonce_generation_time_ + std::chrono::hours(kNonceExpirationTimeInHours))) { GenerateNonce(); @@ -102,62 +103,60 @@ class CastNonce { std::chrono::seconds nonce_generation_time_; }; -// Maps CastCertError from certificate verification to openscreen::Error. +// Maps Error::Code from certificate verification to Error. // If crl_required is set to false, all revocation related errors are ignored. -openscreen::Error MapToOpenscreenError(CastCertError error, bool crl_required) { +Error MapToOpenscreenError(Error::Code error, bool crl_required) { switch (error) { - case CastCertError::kErrCertsMissing: - return openscreen::Error(CastCertError::kCastV2PeerCertEmpty, - "Failed to locate certificates."); - case CastCertError::kErrCertsParse: - return openscreen::Error(CastCertError::kErrCertsParse, - "Failed to parse certificates."); - case CastCertError::kErrCertsDateInvalid: - return openscreen::Error(CastCertError::kCastV2CertNotSignedByTrustedCa, - "Failed date validity check."); - case CastCertError::kErrCertsVerifyGeneric: - return openscreen::Error( - CastCertError::kCastV2CertNotSignedByTrustedCa, - "Failed with a generic certificate verification error."); - case CastCertError::kErrCertsRestrictions: - return openscreen::Error(CastCertError::kCastV2CertNotSignedByTrustedCa, - "Failed certificate restrictions."); - case CastCertError::kErrCrlInvalid: + case Error::Code::kErrCertsMissing: + return Error(Error::Code::kCastV2PeerCertEmpty, + "Failed to locate certificates."); + case Error::Code::kErrCertsParse: + return Error(Error::Code::kErrCertsParse, + "Failed to parse certificates."); + case Error::Code::kErrCertsDateInvalid: + return Error(Error::Code::kCastV2CertNotSignedByTrustedCa, + "Failed date validity check."); + case Error::Code::kErrCertsVerifyGeneric: + return Error(Error::Code::kCastV2CertNotSignedByTrustedCa, + "Failed with a generic certificate verification error."); + case Error::Code::kErrCertsRestrictions: + return Error(Error::Code::kCastV2CertNotSignedByTrustedCa, + "Failed certificate restrictions."); + case Error::Code::kErrCrlInvalid: // This error is only encountered if |crl_required| is true. OSP_DCHECK(crl_required); - return openscreen::Error(CastCertError::kErrCrlInvalid, - "Failed to provide a valid CRL."); - case CastCertError::kErrCertsRevoked: - return openscreen::Error(CastCertError::kErrCertsRevoked, - "Failed certificate revocation check."); - case CastCertError::kNone: - return openscreen::Error::None(); + return Error(Error::Code::kErrCrlInvalid, + "Failed to provide a valid CRL."); + case Error::Code::kErrCertsRevoked: + return Error(Error::Code::kErrCertsRevoked, + "Failed certificate revocation check."); + case Error::Code::kNone: + return Error::None(); default: - return openscreen::Error(CastCertError::kCastV2CertNotSignedByTrustedCa, - "Failed verifying cast device certificate."); + return Error(Error::Code::kCastV2CertNotSignedByTrustedCa, + "Failed verifying cast device certificate."); } - return openscreen::Error::None(); + return Error::None(); } -openscreen::Error VerifyAndMapDigestAlgorithm( - HashAlgorithm response_digest_algorithm, - certificate::DigestAlgorithm* digest_algorithm, - bool enforce_sha256_checking) { +Error VerifyAndMapDigestAlgorithm(HashAlgorithm response_digest_algorithm, + DigestAlgorithm* digest_algorithm, + bool enforce_sha256_checking) { switch (response_digest_algorithm) { - case SHA1: + case ::cast::channel::SHA1: if (enforce_sha256_checking) { - return openscreen::Error(CastCertError::kCastV2DigestUnsupported, - "Unsupported digest algorithm."); + return Error(Error::Code::kCastV2DigestUnsupported, + "Unsupported digest algorithm."); } - *digest_algorithm = certificate::DigestAlgorithm::kSha1; + *digest_algorithm = DigestAlgorithm::kSha1; break; - case SHA256: - *digest_algorithm = certificate::DigestAlgorithm::kSha256; + case ::cast::channel::SHA256: + *digest_algorithm = DigestAlgorithm::kSha256; break; default: - return CastCertError::kCastV2DigestUnsupported; + return Error::Code::kCastV2DigestUnsupported; } - return openscreen::Error::None(); + return Error::None(); } } // namespace @@ -171,77 +170,74 @@ AuthContext::AuthContext(const std::string& nonce) : nonce_(nonce) {} AuthContext::~AuthContext() {} -openscreen::Error AuthContext::VerifySenderNonce( - const std::string& nonce_response, - bool enforce_nonce_checking) const { +Error AuthContext::VerifySenderNonce(const std::string& nonce_response, + bool enforce_nonce_checking) const { if (nonce_ != nonce_response) { if (enforce_nonce_checking) { - return openscreen::Error(CastCertError::kCastV2SenderNonceMismatch, - "Sender nonce mismatched."); + return Error(Error::Code::kCastV2SenderNonceMismatch, + "Sender nonce mismatched."); } } - return openscreen::Error::None(); + return Error::None(); } -openscreen::Error VerifyTLSCertificateValidity( - X509* peer_cert, - std::chrono::seconds verification_time) { +Error VerifyTLSCertificateValidity(X509* peer_cert, + std::chrono::seconds verification_time) { // Ensure the peer cert is valid and doesn't have an excessive remaining // lifetime. Although it is not verified as an X.509 certificate, the entire // structure is signed by the AuthResponse, so the validity field from X.509 // is repurposed as this signature's expiration. - certificate::DateTime not_before; - certificate::DateTime not_after; - if (!certificate::GetCertValidTimeRange(peer_cert, ¬_before, ¬_after)) { - return openscreen::Error(CastCertError::kErrCertsParse, PARSE_ERROR_PREFIX - "Parsing validity fields failed."); + DateTime not_before; + DateTime not_after; + if (!GetCertValidTimeRange(peer_cert, ¬_before, ¬_after)) { + return Error(Error::Code::kErrCertsParse, + PARSE_ERROR_PREFIX "Parsing validity fields failed."); } std::chrono::seconds lifetime_limit = verification_time + std::chrono::hours(24 * kMaxSelfSignedCertLifetimeInDays); - certificate::DateTime verification_time_exploded = {}; - certificate::DateTime lifetime_limit_exploded = {}; - OSP_CHECK(certificate::DateTimeFromSeconds(verification_time.count(), - &verification_time_exploded)); - OSP_CHECK(certificate::DateTimeFromSeconds(lifetime_limit.count(), - &lifetime_limit_exploded)); + DateTime verification_time_exploded = {}; + DateTime lifetime_limit_exploded = {}; + OSP_CHECK(DateTimeFromSeconds(verification_time.count(), + &verification_time_exploded)); + OSP_CHECK( + DateTimeFromSeconds(lifetime_limit.count(), &lifetime_limit_exploded)); if (verification_time_exploded < not_before) { - return openscreen::Error( - CastCertError::kCastV2TlsCertValidStartDateInFuture, - PARSE_ERROR_PREFIX "Certificate's valid start date is in the future."); + return Error(Error::Code::kCastV2TlsCertValidStartDateInFuture, + PARSE_ERROR_PREFIX + "Certificate's valid start date is in the future."); } if (not_after < verification_time_exploded) { - return openscreen::Error(CastCertError::kCastV2TlsCertExpired, - PARSE_ERROR_PREFIX "Certificate has expired."); + return Error(Error::Code::kCastV2TlsCertExpired, + PARSE_ERROR_PREFIX "Certificate has expired."); } if (lifetime_limit_exploded < not_after) { - return openscreen::Error(CastCertError::kCastV2TlsCertValidityPeriodTooLong, - PARSE_ERROR_PREFIX - "Peer cert lifetime is too long."); + return Error(Error::Code::kCastV2TlsCertValidityPeriodTooLong, + PARSE_ERROR_PREFIX "Peer cert lifetime is too long."); } - return openscreen::Error::None(); + return Error::None(); } ErrorOr<CastDeviceCertPolicy> VerifyCredentialsImpl( const AuthResponse& response, const std::string& signature_input, - const certificate::CRLPolicy& crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time, + const CRLPolicy& crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time, bool enforce_sha256_checking); ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReplyImpl( const CastMessage& challenge_reply, X509* peer_cert, const AuthContext& auth_context, - const certificate::CRLPolicy& crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time) { + const CRLPolicy& crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time) { DeviceAuthMessage auth_message; - openscreen::Error result = ParseAuthMessage(challenge_reply, &auth_message); + Error result = ParseAuthMessage(challenge_reply, &auth_message); if (!result.ok()) { return result; } @@ -262,14 +258,12 @@ ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReplyImpl( int len = i2d_X509(peer_cert, nullptr); if (len <= 0) { - return openscreen::Error(CastCertError::kErrCertsParse, - "Serializing cert failed."); + return Error(Error::Code::kErrCertsParse, "Serializing cert failed."); } std::string peer_cert_der(len, 0); uint8_t* data = reinterpret_cast<uint8_t*>(&peer_cert_der[0]); if (!i2d_X509(peer_cert, &data)) { - return openscreen::Error(CastCertError::kErrCertsParse, - "Serializing cert failed."); + return Error(Error::Code::kErrCertsParse, "Serializing cert failed."); } size_t actual_size = data - reinterpret_cast<uint8_t*>(&peer_cert_der[0]); OSP_DCHECK_EQ(actual_size, peer_cert_der.size()); @@ -284,10 +278,9 @@ ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReply( const CastMessage& challenge_reply, X509* peer_cert, const AuthContext& auth_context) { - certificate::DateTime now = {}; - OSP_CHECK(certificate::DateTimeFromSeconds( - openscreen::GetWallTimeSinceUnixEpoch().count(), &now)); - certificate::CRLPolicy policy = certificate::CRLPolicy::kCrlOptional; + DateTime now = {}; + OSP_CHECK(DateTimeFromSeconds(GetWallTimeSinceUnixEpoch().count(), &now)); + CRLPolicy policy = CRLPolicy::kCrlOptional; return AuthenticateChallengeReplyImpl( challenge_reply, peer_cert, auth_context, policy, /* cast_trust_store */ nullptr, /* crl_trust_store */ nullptr, now); @@ -297,10 +290,10 @@ ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReplyForTest( const CastMessage& challenge_reply, X509* peer_cert, const AuthContext& auth_context, - certificate::CRLPolicy crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time) { + CRLPolicy crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time) { return AuthenticateChallengeReplyImpl( challenge_reply, peer_cert, auth_context, crl_policy, cast_trust_store, crl_trust_store, verification_time); @@ -326,18 +319,17 @@ ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReplyForTest( ErrorOr<CastDeviceCertPolicy> VerifyCredentialsImpl( const AuthResponse& response, const std::string& signature_input, - const certificate::CRLPolicy& crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time, + const CRLPolicy& crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time, bool enforce_sha256_checking) { if (response.signature().empty() && !signature_input.empty()) { - return openscreen::Error(CastCertError::kCastV2SignatureEmpty, - "Signature is empty."); + return Error(Error::Code::kCastV2SignatureEmpty, "Signature is empty."); } // Verify the certificate - std::unique_ptr<certificate::CertVerificationContext> verification_context; + std::unique_ptr<CertVerificationContext> verification_context; // Build a single vector containing the certificate chain. std::vector<std::string> cert_chain; @@ -347,43 +339,42 @@ ErrorOr<CastDeviceCertPolicy> VerifyCredentialsImpl( response.intermediate_certificate().end()); // Parse the CRL. - std::unique_ptr<certificate::CastCRL> crl; + std::unique_ptr<CastCRL> crl; if (!response.crl().empty()) { - crl = certificate::ParseAndVerifyCRL(response.crl(), verification_time, - crl_trust_store); + crl = ParseAndVerifyCRL(response.crl(), verification_time, crl_trust_store); } // Perform certificate verification. - certificate::CastDeviceCertPolicy device_policy; - openscreen::Error verify_result = certificate::VerifyDeviceCert( - cert_chain, verification_time, &verification_context, &device_policy, - crl.get(), crl_policy, cast_trust_store); + CastDeviceCertPolicy device_policy; + Error verify_result = + VerifyDeviceCert(cert_chain, verification_time, &verification_context, + &device_policy, crl.get(), crl_policy, cast_trust_store); // Handle and report errors. - openscreen::Error result = MapToOpenscreenError( - verify_result.code(), crl_policy == certificate::CRLPolicy::kCrlRequired); + Error result = MapToOpenscreenError(verify_result.code(), + crl_policy == CRLPolicy::kCrlRequired); if (!result.ok()) { return result; } // The certificate is verified at this point. - certificate::DigestAlgorithm digest_algorithm; - openscreen::Error digest_result = VerifyAndMapDigestAlgorithm( + DigestAlgorithm digest_algorithm; + Error digest_result = VerifyAndMapDigestAlgorithm( response.hash_algorithm(), &digest_algorithm, enforce_sha256_checking); if (!digest_result.ok()) { return digest_result; } - certificate::ConstDataSpan signature = { + ConstDataSpan signature = { reinterpret_cast<const uint8_t*>(response.signature().data()), static_cast<uint32_t>(response.signature().size())}; - certificate::ConstDataSpan siginput = { + ConstDataSpan siginput = { reinterpret_cast<const uint8_t*>(signature_input.data()), static_cast<uint32_t>(signature_input.size())}; if (!verification_context->VerifySignatureOverData(signature, siginput, digest_algorithm)) { - return openscreen::Error(CastCertError::kCastV2SignedBlobsMismatch, - "Failed verifying signature over data."); + return Error(Error::Code::kCastV2SignedBlobsMismatch, + "Failed verifying signature over data."); } return device_policy; @@ -394,12 +385,10 @@ ErrorOr<CastDeviceCertPolicy> VerifyCredentials( const std::string& signature_input, bool enforce_revocation_checking, bool enforce_sha256_checking) { - certificate::DateTime now = {}; - OSP_CHECK(certificate::DateTimeFromSeconds( - openscreen::GetWallTimeSinceUnixEpoch().count(), &now)); - certificate::CRLPolicy policy = (enforce_revocation_checking) - ? certificate::CRLPolicy::kCrlRequired - : certificate::CRLPolicy::kCrlOptional; + DateTime now = {}; + OSP_CHECK(DateTimeFromSeconds(GetWallTimeSinceUnixEpoch().count(), &now)); + CRLPolicy policy = (enforce_revocation_checking) ? CRLPolicy::kCrlRequired + : CRLPolicy::kCrlOptional; return VerifyCredentialsImpl(response, signature_input, policy, nullptr, nullptr, now, enforce_sha256_checking); } @@ -407,15 +396,15 @@ ErrorOr<CastDeviceCertPolicy> VerifyCredentials( ErrorOr<CastDeviceCertPolicy> VerifyCredentialsForTest( const AuthResponse& response, const std::string& signature_input, - certificate::CRLPolicy crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time, + CRLPolicy crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time, bool enforce_sha256_checking) { return VerifyCredentialsImpl(response, signature_input, crl_policy, cast_trust_store, crl_trust_store, verification_time, enforce_sha256_checking); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/sender/channel/cast_auth_util.h b/cast/sender/channel/cast_auth_util.h index df6299d3..467dfb82 100644 --- a/cast/sender/channel/cast_auth_util.h +++ b/cast/sender/channel/cast_auth_util.h @@ -7,28 +7,25 @@ #include <openssl/x509.h> -#include <chrono> +#include <chrono> // NOLINT #include <string> #include "cast/common/certificate/cast_cert_validator.h" #include "platform/base/error.h" namespace cast { -namespace certificate { -enum class CRLPolicy; -struct DateTime; -struct TrustStore; -} // namespace certificate -} // namespace cast - -namespace cast { namespace channel { - class AuthResponse; class CastMessage; +} // namespace channel +} // namespace cast + +namespace openscreen { +namespace cast { -using openscreen::ErrorOr; -using CastDeviceCertPolicy = certificate::CastDeviceCertPolicy; +enum class CRLPolicy; +struct DateTime; +struct TrustStore; class AuthContext { public: @@ -40,9 +37,8 @@ class AuthContext { // Verifies the nonce received in the response is equivalent to the one sent. // Returns success if |nonce_response| matches nonce_ - openscreen::Error VerifySenderNonce( - const std::string& nonce_response, - bool enforce_nonce_checking = false) const; + Error VerifySenderNonce(const std::string& nonce_response, + bool enforce_nonce_checking = false) const; // The nonce challenge. const std::string& nonce() const { return nonce_; } @@ -57,7 +53,7 @@ class AuthContext { // 1. Signature contained in the reply is valid. // 2. certificate used to sign is rooted to a trusted CA. ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReply( - const CastMessage& challenge_reply, + const ::cast::channel::CastMessage& challenge_reply, X509* peer_cert, const AuthContext& auth_context); @@ -66,24 +62,23 @@ ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReply( // Overloaded version of AuthenticateChallengeReply that allows modifying the // crl policy, trust stores, and verification times. ErrorOr<CastDeviceCertPolicy> AuthenticateChallengeReplyForTest( - const CastMessage& challenge_reply, + const ::cast::channel::CastMessage& challenge_reply, X509* peer_cert, const AuthContext& auth_context, - certificate::CRLPolicy crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time); + CRLPolicy crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time); // Performs a quick check of the TLS certificate for time validity requirements. -openscreen::Error VerifyTLSCertificateValidity( - X509* peer_cert, - std::chrono::seconds verification_time); +Error VerifyTLSCertificateValidity(X509* peer_cert, + std::chrono::seconds verification_time); // Auth-library specific implementation of cryptographic signature verification // routines. Verifies that |response| contains a valid signature of // |signature_input|. ErrorOr<CastDeviceCertPolicy> VerifyCredentials( - const AuthResponse& response, + const ::cast::channel::AuthResponse& response, const std::string& signature_input, bool enforce_revocation_checking = false, bool enforce_sha256_checking = false); @@ -93,15 +88,15 @@ ErrorOr<CastDeviceCertPolicy> VerifyCredentials( // Overloaded version of VerifyCredentials that allows modifying the crl policy, // trust stores, and verification times. ErrorOr<CastDeviceCertPolicy> VerifyCredentialsForTest( - const AuthResponse& response, + const ::cast::channel::AuthResponse& response, const std::string& signature_input, - certificate::CRLPolicy crl_policy, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store, - const certificate::DateTime& verification_time, + CRLPolicy crl_policy, + TrustStore* cast_trust_store, + TrustStore* crl_trust_store, + const DateTime& verification_time, bool enforce_sha256_checking = false); -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_SENDER_CHANNEL_CAST_AUTH_UTIL_H_ diff --git a/cast/sender/channel/cast_auth_util_unittest.cc b/cast/sender/channel/cast_auth_util_unittest.cc index 5dec424d..93fb913e 100644 --- a/cast/sender/channel/cast_auth_util_unittest.cc +++ b/cast/sender/channel/cast_auth_util_unittest.cc @@ -16,13 +16,13 @@ #include "testing/util/read_file.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { namespace { -using ErrorCode = openscreen::Error::Code; +using ::cast::channel::AuthResponse; -bool ConvertTimeSeconds(const certificate::DateTime& time, uint64_t* seconds) { +bool ConvertTimeSeconds(const DateTime& time, uint64_t* seconds) { static constexpr uint64_t kDaysPerYear = 365; static constexpr uint64_t kHoursPerDay = 24; static constexpr uint64_t kMinutesPerHour = 60; @@ -102,7 +102,7 @@ bool ConvertTimeSeconds(const certificate::DateTime& time, uint64_t* seconds) { #define TEST_DATA_PREFIX OPENSCREEN_TEST_DATA_DIR "cast/common/certificate/" -class CastAuthUtilTest : public testing::Test { +class CastAuthUtilTest : public ::testing::Test { public: CastAuthUtilTest() {} ~CastAuthUtilTest() override {} @@ -110,16 +110,15 @@ class CastAuthUtilTest : public testing::Test { void SetUp() override {} protected: - static AuthResponse CreateAuthResponse(std::string* signed_data, - HashAlgorithm digest_algorithm) { - std::vector<std::string> chain = - certificate::testing::ReadCertificatesFromPemFile( - TEST_DATA_PREFIX "certificates/chromecast_gen1.pem"); + static AuthResponse CreateAuthResponse( + std::string* signed_data, + ::cast::channel::HashAlgorithm digest_algorithm) { + std::vector<std::string> chain = testing::ReadCertificatesFromPemFile( + TEST_DATA_PREFIX "certificates/chromecast_gen1.pem"); OSP_CHECK(!chain.empty()); - certificate::testing::SignatureTestData signatures = - certificate::testing::ReadSignatureTestData( - TEST_DATA_PREFIX "signeddata/2ZZBG9_FA8FCA3EF91A.pem"); + testing::SignatureTestData signatures = testing::ReadSignatureTestData( + TEST_DATA_PREFIX "signeddata/2ZZBG9_FA8FCA3EF91A.pem"); AuthResponse response; @@ -130,12 +129,12 @@ class CastAuthUtilTest : public testing::Test { response.set_hash_algorithm(digest_algorithm); switch (digest_algorithm) { - case SHA1: + case ::cast::channel::SHA1: response.set_signature( std::string(reinterpret_cast<const char*>(signatures.sha1.data), signatures.sha1.length)); break; - case SHA256: + case ::cast::channel::SHA256: response.set_signature( std::string(reinterpret_cast<const char*>(signatures.sha256.data), signatures.sha256.length)); @@ -156,96 +155,100 @@ class CastAuthUtilTest : public testing::Test { // being verified doesn't expire until 2032. TEST_F(CastAuthUtilTest, VerifySuccess) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA256); - certificate::DateTime now = {}; - ASSERT_TRUE(certificate::DateTimeFromSeconds( - openscreen::GetWallTimeSinceUnixEpoch().count(), &now)); - ErrorOr<CastDeviceCertPolicy> result = VerifyCredentialsForTest( - auth_response, signed_data, certificate::CRLPolicy::kCrlOptional, nullptr, - nullptr, now); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA256); + DateTime now = {}; + ASSERT_TRUE(DateTimeFromSeconds(GetWallTimeSinceUnixEpoch().count(), &now)); + ErrorOr<CastDeviceCertPolicy> result = + VerifyCredentialsForTest(auth_response, signed_data, + CRLPolicy::kCrlOptional, nullptr, nullptr, now); EXPECT_TRUE(result); - EXPECT_EQ(certificate::CastDeviceCertPolicy::kUnrestricted, result.value()); + EXPECT_EQ(CastDeviceCertPolicy::kUnrestricted, result.value()); } TEST_F(CastAuthUtilTest, VerifyBadCA) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA256); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA256); MangleString(auth_response.mutable_intermediate_certificate(0)); ErrorOr<CastDeviceCertPolicy> result = VerifyCredentials(auth_response, signed_data); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kErrCertsParse, result.error().code()); + EXPECT_EQ(Error::Code::kErrCertsParse, result.error().code()); } TEST_F(CastAuthUtilTest, VerifyBadClientAuthCert) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA256); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA256); MangleString(auth_response.mutable_client_auth_certificate()); ErrorOr<CastDeviceCertPolicy> result = VerifyCredentials(auth_response, signed_data); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kErrCertsParse, result.error().code()); + EXPECT_EQ(Error::Code::kErrCertsParse, result.error().code()); } TEST_F(CastAuthUtilTest, VerifyBadSignature) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA256); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA256); MangleString(auth_response.mutable_signature()); ErrorOr<CastDeviceCertPolicy> result = VerifyCredentials(auth_response, signed_data); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2SignedBlobsMismatch, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2SignedBlobsMismatch, result.error().code()); } TEST_F(CastAuthUtilTest, VerifyEmptySignature) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA256); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA256); auth_response.mutable_signature()->clear(); ErrorOr<CastDeviceCertPolicy> result = VerifyCredentials(auth_response, signed_data); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2SignatureEmpty, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2SignatureEmpty, result.error().code()); } TEST_F(CastAuthUtilTest, VerifyUnsupportedDigest) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA1); - certificate::DateTime now = {}; - ASSERT_TRUE(certificate::DateTimeFromSeconds( - openscreen::GetWallTimeSinceUnixEpoch().count(), &now)); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA1); + DateTime now = {}; + ASSERT_TRUE(DateTimeFromSeconds(GetWallTimeSinceUnixEpoch().count(), &now)); ErrorOr<CastDeviceCertPolicy> result = VerifyCredentialsForTest( - auth_response, signed_data, certificate::CRLPolicy::kCrlOptional, nullptr, - nullptr, now, true); + auth_response, signed_data, CRLPolicy::kCrlOptional, nullptr, nullptr, + now, true); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2DigestUnsupported, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2DigestUnsupported, result.error().code()); } TEST_F(CastAuthUtilTest, VerifyBackwardsCompatibleDigest) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA1); - certificate::DateTime now = {}; - ASSERT_TRUE(certificate::DateTimeFromSeconds( - openscreen::GetWallTimeSinceUnixEpoch().count(), &now)); - ErrorOr<CastDeviceCertPolicy> result = VerifyCredentialsForTest( - auth_response, signed_data, certificate::CRLPolicy::kCrlOptional, nullptr, - nullptr, now); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA1); + DateTime now = {}; + ASSERT_TRUE(DateTimeFromSeconds(GetWallTimeSinceUnixEpoch().count(), &now)); + ErrorOr<CastDeviceCertPolicy> result = + VerifyCredentialsForTest(auth_response, signed_data, + CRLPolicy::kCrlOptional, nullptr, nullptr, now); EXPECT_TRUE(result); } TEST_F(CastAuthUtilTest, VerifyBadPeerCert) { std::string signed_data; - AuthResponse auth_response = CreateAuthResponse(&signed_data, SHA256); + AuthResponse auth_response = + CreateAuthResponse(&signed_data, ::cast::channel::SHA256); MangleString(&signed_data); ErrorOr<CastDeviceCertPolicy> result = VerifyCredentials(auth_response, signed_data); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2SignedBlobsMismatch, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2SignedBlobsMismatch, result.error().code()); } TEST_F(CastAuthUtilTest, VerifySenderNonceMatch) { AuthContext context = AuthContext::Create(); - const openscreen::Error result = - context.VerifySenderNonce(context.nonce(), true); + const Error result = context.VerifySenderNonce(context.nonce(), true); EXPECT_TRUE(result.ok()); } @@ -256,7 +259,7 @@ TEST_F(CastAuthUtilTest, VerifySenderNonceMismatch) { ErrorOr<CastDeviceCertPolicy> result = context.VerifySenderNonce(received_nonce, true); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2SenderNonceMismatch, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2SenderNonceMismatch, result.error().code()); } TEST_F(CastAuthUtilTest, VerifySenderNonceMissing) { @@ -266,40 +269,36 @@ TEST_F(CastAuthUtilTest, VerifySenderNonceMissing) { ErrorOr<CastDeviceCertPolicy> result = context.VerifySenderNonce(received_nonce, true); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2SenderNonceMismatch, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2SenderNonceMismatch, result.error().code()); } TEST_F(CastAuthUtilTest, VerifyTLSCertificateSuccess) { - std::vector<std::string> tls_cert_der = - certificate::testing::ReadCertificatesFromPemFile( - TEST_DATA_PREFIX "certificates/test_tls_cert.pem"); + std::vector<std::string> tls_cert_der = testing::ReadCertificatesFromPemFile( + TEST_DATA_PREFIX "certificates/test_tls_cert.pem"); std::string& der_cert = tls_cert_der[0]; const uint8_t* data = (const uint8_t*)der_cert.data(); X509* tls_cert = d2i_X509(nullptr, &data, der_cert.size()); - certificate::DateTime not_before; - certificate::DateTime not_after; - ASSERT_TRUE( - certificate::GetCertValidTimeRange(tls_cert, ¬_before, ¬_after)); + DateTime not_before; + DateTime not_after; + ASSERT_TRUE(GetCertValidTimeRange(tls_cert, ¬_before, ¬_after)); uint64_t x; ASSERT_TRUE(ConvertTimeSeconds(not_before, &x)); std::chrono::seconds s(x); - const openscreen::Error result = VerifyTLSCertificateValidity(tls_cert, s); + const Error result = VerifyTLSCertificateValidity(tls_cert, s); EXPECT_TRUE(result.ok()); X509_free(tls_cert); } TEST_F(CastAuthUtilTest, VerifyTLSCertificateTooEarly) { - std::vector<std::string> tls_cert_der = - certificate::testing::ReadCertificatesFromPemFile( - TEST_DATA_PREFIX "certificates/test_tls_cert.pem"); + std::vector<std::string> tls_cert_der = testing::ReadCertificatesFromPemFile( + TEST_DATA_PREFIX "certificates/test_tls_cert.pem"); std::string& der_cert = tls_cert_der[0]; const uint8_t* data = (const uint8_t*)der_cert.data(); X509* tls_cert = d2i_X509(nullptr, &data, der_cert.size()); - certificate::DateTime not_before; - certificate::DateTime not_after; - ASSERT_TRUE( - certificate::GetCertValidTimeRange(tls_cert, ¬_before, ¬_after)); + DateTime not_before; + DateTime not_after; + ASSERT_TRUE(GetCertValidTimeRange(tls_cert, ¬_before, ¬_after)); uint64_t x; ASSERT_TRUE(ConvertTimeSeconds(not_before, &x)); std::chrono::seconds s(x - 1); @@ -307,22 +306,20 @@ TEST_F(CastAuthUtilTest, VerifyTLSCertificateTooEarly) { ErrorOr<CastDeviceCertPolicy> result = VerifyTLSCertificateValidity(tls_cert, s); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2TlsCertValidStartDateInFuture, + EXPECT_EQ(Error::Code::kCastV2TlsCertValidStartDateInFuture, result.error().code()); X509_free(tls_cert); } TEST_F(CastAuthUtilTest, VerifyTLSCertificateTooLate) { - std::vector<std::string> tls_cert_der = - certificate::testing::ReadCertificatesFromPemFile( - TEST_DATA_PREFIX "certificates/test_tls_cert.pem"); + std::vector<std::string> tls_cert_der = testing::ReadCertificatesFromPemFile( + TEST_DATA_PREFIX "certificates/test_tls_cert.pem"); std::string& der_cert = tls_cert_der[0]; const uint8_t* data = (const uint8_t*)der_cert.data(); X509* tls_cert = d2i_X509(nullptr, &data, der_cert.size()); - certificate::DateTime not_before; - certificate::DateTime not_after; - ASSERT_TRUE( - certificate::GetCertValidTimeRange(tls_cert, ¬_before, ¬_after)); + DateTime not_before; + DateTime not_after; + ASSERT_TRUE(GetCertValidTimeRange(tls_cert, ¬_before, ¬_after)); uint64_t x; ASSERT_TRUE(ConvertTimeSeconds(not_after, &x)); std::chrono::seconds s(x + 2); @@ -330,7 +327,7 @@ TEST_F(CastAuthUtilTest, VerifyTLSCertificateTooLate) { ErrorOr<CastDeviceCertPolicy> result = VerifyTLSCertificateValidity(tls_cert, s); EXPECT_FALSE(result); - EXPECT_EQ(ErrorCode::kCastV2TlsCertExpired, result.error().code()); + EXPECT_EQ(Error::Code::kCastV2TlsCertExpired, result.error().code()); X509_free(tls_cert); } @@ -348,10 +345,10 @@ enum TestStepResult { ErrorOr<CastDeviceCertPolicy> TestVerifyRevocation( const std::vector<std::string>& certificate_chain, const std::string& crl_bundle, - const certificate::DateTime& verification_time, + const DateTime& verification_time, bool crl_required, - certificate::TrustStore* cast_trust_store, - certificate::TrustStore* crl_trust_store) { + TrustStore* cast_trust_store, + TrustStore* crl_trust_store) { AuthResponse response; if (certificate_chain.size() > 0) { @@ -363,9 +360,9 @@ ErrorOr<CastDeviceCertPolicy> TestVerifyRevocation( response.set_crl(crl_bundle); - certificate::CRLPolicy crl_policy = certificate::CRLPolicy::kCrlRequired; + CRLPolicy crl_policy = CRLPolicy::kCrlRequired; if (!crl_required && crl_bundle.empty()) - crl_policy = certificate::CRLPolicy::kCrlOptional; + crl_policy = CRLPolicy::kCrlOptional; ErrorOr<CastDeviceCertPolicy> result = VerifyCredentialsForTest(response, "", crl_policy, cast_trust_store, crl_trust_store, verification_time); @@ -375,13 +372,13 @@ ErrorOr<CastDeviceCertPolicy> TestVerifyRevocation( } // Runs a single test case. -bool RunTest(const certificate::DeviceCertTest& test_case) { - std::unique_ptr<certificate::TrustStore> crl_trust_store; - std::unique_ptr<certificate::TrustStore> cast_trust_store; +bool RunTest(const DeviceCertTest& test_case) { + std::unique_ptr<TrustStore> crl_trust_store; + std::unique_ptr<TrustStore> cast_trust_store; if (test_case.use_test_trust_anchors()) { - crl_trust_store = certificate::testing::CreateTrustStoreFromPemFile( + crl_trust_store = testing::CreateTrustStoreFromPemFile( TEST_DATA_PREFIX "certificates/cast_crl_test_root_ca.pem"); - cast_trust_store = certificate::testing::CreateTrustStoreFromPemFile( + cast_trust_store = testing::CreateTrustStoreFromPemFile( TEST_DATA_PREFIX "certificates/cast_test_root_ca.pem"); EXPECT_FALSE(crl_trust_store->certs.empty()); @@ -394,51 +391,49 @@ bool RunTest(const certificate::DeviceCertTest& test_case) { } // CastAuthUtil verifies the CRL at the same time as the certificate. - certificate::DateTime verification_time; + DateTime verification_time; uint64_t cert_verify_time = test_case.cert_verification_time_seconds(); if (!cert_verify_time) { cert_verify_time = test_case.crl_verification_time_seconds(); } - OSP_DCHECK( - certificate::DateTimeFromSeconds(cert_verify_time, &verification_time)); + OSP_DCHECK(DateTimeFromSeconds(cert_verify_time, &verification_time)); std::string crl_bundle = test_case.crl_bundle(); - ErrorOr<CastDeviceCertPolicy> result( - certificate::CastDeviceCertPolicy::kUnrestricted); + ErrorOr<CastDeviceCertPolicy> result(CastDeviceCertPolicy::kUnrestricted); switch (test_case.expected_result()) { - case certificate::PATH_VERIFICATION_FAILED: + case PATH_VERIFICATION_FAILED: result = TestVerifyRevocation( certificate_chain, crl_bundle, verification_time, false, cast_trust_store.get(), crl_trust_store.get()); EXPECT_EQ(result.error().code(), - ErrorCode::kCastV2CertNotSignedByTrustedCa); + Error::Code::kCastV2CertNotSignedByTrustedCa); return result.error().code() == - ErrorCode::kCastV2CertNotSignedByTrustedCa; - case certificate::CRL_VERIFICATION_FAILED: + Error::Code::kCastV2CertNotSignedByTrustedCa; + case CRL_VERIFICATION_FAILED: // Fall-through intended. - case certificate::REVOCATION_CHECK_FAILED_WITHOUT_CRL: + case REVOCATION_CHECK_FAILED_WITHOUT_CRL: result = TestVerifyRevocation( certificate_chain, crl_bundle, verification_time, true, cast_trust_store.get(), crl_trust_store.get()); - EXPECT_EQ(result.error().code(), ErrorCode::kErrCrlInvalid); - return result.error().code() == ErrorCode::kErrCrlInvalid; - case certificate::CRL_EXPIRED_AFTER_INITIAL_VERIFICATION: + EXPECT_EQ(result.error().code(), Error::Code::kErrCrlInvalid); + return result.error().code() == Error::Code::kErrCrlInvalid; + case CRL_EXPIRED_AFTER_INITIAL_VERIFICATION: // By-pass this test because CRL is always verified at the time the // certificate is verified. return true; - case certificate::REVOCATION_CHECK_FAILED: + case REVOCATION_CHECK_FAILED: result = TestVerifyRevocation( certificate_chain, crl_bundle, verification_time, true, cast_trust_store.get(), crl_trust_store.get()); - EXPECT_EQ(result.error().code(), ErrorCode::kErrCertsRevoked); - return result.error().code() == ErrorCode::kErrCertsRevoked; - case certificate::SUCCESS: + EXPECT_EQ(result.error().code(), Error::Code::kErrCertsRevoked); + return result.error().code() == Error::Code::kErrCertsRevoked; + case SUCCESS: result = TestVerifyRevocation( certificate_chain, crl_bundle, verification_time, false, cast_trust_store.get(), crl_trust_store.get()); - EXPECT_EQ(result.error().code(), ErrorCode::kCastV2SignedBlobsMismatch); - return result.error().code() == ErrorCode::kCastV2SignedBlobsMismatch; - case certificate::UNSPECIFIED: + EXPECT_EQ(result.error().code(), Error::Code::kCastV2SignedBlobsMismatch); + return result.error().code() == Error::Code::kCastV2SignedBlobsMismatch; + case UNSPECIFIED: return false; } return false; @@ -449,9 +444,8 @@ bool RunTest(const certificate::DeviceCertTest& test_case) { // To see the description of the test, execute the test. // These tests are generated by a test generator in google3. void RunTestSuite(const std::string& test_suite_file_name) { - std::string testsuite_raw = - openscreen::ReadEntireFileToString(test_suite_file_name); - certificate::DeviceCertTestSuite test_suite; + std::string testsuite_raw = ReadEntireFileToString(test_suite_file_name); + DeviceCertTestSuite test_suite; EXPECT_TRUE(test_suite.ParseFromString(testsuite_raw)); uint16_t successes = 0; @@ -470,5 +464,5 @@ TEST_F(CastAuthUtilTest, CRLTestSuite) { } } // namespace -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/sender/channel/message_util.cc b/cast/sender/channel/message_util.cc index ab3ed5d8..48623cee 100644 --- a/cast/sender/channel/message_util.cc +++ b/cast/sender/channel/message_util.cc @@ -6,8 +6,12 @@ #include "cast/sender/channel/cast_auth_util.h" +namespace openscreen { namespace cast { -namespace channel { + +using ::cast::channel::AuthChallenge; +using ::cast::channel::CastMessage; +using ::cast::channel::DeviceAuthMessage; CastMessage CreateAuthChallengeMessage(const AuthContext& auth_context) { CastMessage message; @@ -15,7 +19,7 @@ CastMessage CreateAuthChallengeMessage(const AuthContext& auth_context) { AuthChallenge* challenge = auth_message.mutable_challenge(); challenge->set_sender_nonce(auth_context.nonce()); - challenge->set_hash_algorithm(SHA256); + challenge->set_hash_algorithm(::cast::channel::SHA256); std::string auth_message_string; auth_message.SerializeToString(&auth_message_string); @@ -24,11 +28,11 @@ CastMessage CreateAuthChallengeMessage(const AuthContext& auth_context) { message.set_source_id(kPlatformSenderId); message.set_destination_id(kPlatformReceiverId); message.set_namespace_(kAuthNamespace); - message.set_payload_type(CastMessage_PayloadType_BINARY); + message.set_payload_type(::cast::channel::CastMessage_PayloadType_BINARY); message.set_payload_binary(auth_message_string); return message; } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/sender/channel/message_util.h b/cast/sender/channel/message_util.h index e2da0cd8..944165bc 100644 --- a/cast/sender/channel/message_util.h +++ b/cast/sender/channel/message_util.h @@ -8,14 +8,15 @@ #include "cast/common/channel/message_util.h" #include "cast/common/channel/proto/cast_channel.pb.h" +namespace openscreen { namespace cast { -namespace channel { class AuthContext; -CastMessage CreateAuthChallengeMessage(const AuthContext& auth_context); +::cast::channel::CastMessage CreateAuthChallengeMessage( + const AuthContext& auth_context); -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_SENDER_CHANNEL_MESSAGE_UTIL_H_ diff --git a/cast/sender/channel/sender_socket_factory.cc b/cast/sender/channel/sender_socket_factory.cc index b185113d..8dff73c4 100644 --- a/cast/sender/channel/sender_socket_factory.cc +++ b/cast/sender/channel/sender_socket_factory.cc @@ -5,18 +5,15 @@ #include "cast/sender/channel/sender_socket_factory.h" #include "cast/common/channel/cast_socket.h" +#include "cast/common/channel/proto/cast_channel.pb.h" #include "cast/sender/channel/message_util.h" #include "platform/base/tls_connect_options.h" #include "util/crypto/certificate_utils.h" -namespace cast { -namespace channel { +using ::cast::channel::CastMessage; -using openscreen::Error; -using openscreen::IPEndpoint; -using openscreen::TlsConnection; -using openscreen::TlsConnectionFactory; -using openscreen::TlsConnectOptions; +namespace openscreen { +namespace cast { bool operator<(const std::unique_ptr<SenderSocketFactory::PendingAuth>& a, uint32_t b) { @@ -68,8 +65,8 @@ void SenderSocketFactory::OnConnected( CastSocket::Client* client = it->client; pending_connections_.erase(it); - ErrorOr<bssl::UniquePtr<X509>> peer_cert = openscreen::ImportCertificate( - der_x509_peer_cert.data(), der_x509_peer_cert.size()); + ErrorOr<bssl::UniquePtr<X509>> peer_cert = + ImportCertificate(der_x509_peer_cert.data(), der_x509_peer_cert.size()); if (!peer_cert) { client_->OnError(this, endpoint, peer_cert.error()); return; @@ -170,5 +167,5 @@ void SenderSocketFactory::OnMessage(CastSocket* socket, CastMessage message) { client_->OnConnected(this, pending->endpoint, std::move(pending->socket)); } -} // namespace channel } // namespace cast +} // namespace openscreen diff --git a/cast/sender/channel/sender_socket_factory.h b/cast/sender/channel/sender_socket_factory.h index c58b369a..9cb31066 100644 --- a/cast/sender/channel/sender_socket_factory.h +++ b/cast/sender/channel/sender_socket_factory.h @@ -12,26 +12,26 @@ #include <vector> #include "cast/common/channel/cast_socket.h" +#include "cast/common/channel/proto/cast_channel.pb.h" #include "cast/sender/channel/cast_auth_util.h" #include "platform/api/tls_connection_factory.h" #include "platform/base/ip_address.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace channel { -class SenderSocketFactory final - : public openscreen::TlsConnectionFactory::Client, - public CastSocket::Client { +class SenderSocketFactory final : public TlsConnectionFactory::Client, + public CastSocket::Client { public: class Client { public: virtual void OnConnected(SenderSocketFactory* factory, - const openscreen::IPEndpoint& endpoint, + const IPEndpoint& endpoint, std::unique_ptr<CastSocket> socket) = 0; virtual void OnError(SenderSocketFactory* factory, - const openscreen::IPEndpoint& endpoint, - openscreen::Error error) = 0; + const IPEndpoint& endpoint, + Error error) = 0; }; enum class DeviceMediaPolicy { @@ -43,39 +43,35 @@ class SenderSocketFactory final explicit SenderSocketFactory(Client* client); ~SenderSocketFactory(); - void set_factory(openscreen::TlsConnectionFactory* factory) { + void set_factory(TlsConnectionFactory* factory) { OSP_DCHECK(factory); factory_ = factory; } - void Connect(const openscreen::IPEndpoint& endpoint, + void Connect(const IPEndpoint& endpoint, DeviceMediaPolicy media_policy, CastSocket::Client* client); - // openscreen::TlsConnectionFactory::Client overrides. - void OnAccepted( - openscreen::TlsConnectionFactory* factory, - std::vector<uint8_t> der_x509_peer_cert, - std::unique_ptr<openscreen::TlsConnection> connection) override; - void OnConnected( - openscreen::TlsConnectionFactory* factory, - std::vector<uint8_t> der_x509_peer_cert, - std::unique_ptr<openscreen::TlsConnection> connection) override; - void OnConnectionFailed( - openscreen::TlsConnectionFactory* factory, - const openscreen::IPEndpoint& remote_address) override; - void OnError(openscreen::TlsConnectionFactory* factory, - openscreen::Error error) override; + // TlsConnectionFactory::Client overrides. + void OnAccepted(TlsConnectionFactory* factory, + std::vector<uint8_t> der_x509_peer_cert, + std::unique_ptr<TlsConnection> connection) override; + void OnConnected(TlsConnectionFactory* factory, + std::vector<uint8_t> der_x509_peer_cert, + std::unique_ptr<TlsConnection> connection) override; + void OnConnectionFailed(TlsConnectionFactory* factory, + const IPEndpoint& remote_address) override; + void OnError(TlsConnectionFactory* factory, Error error) override; private: struct PendingConnection { - openscreen::IPEndpoint endpoint; + IPEndpoint endpoint; DeviceMediaPolicy media_policy; CastSocket::Client* client; }; struct PendingAuth { - openscreen::IPEndpoint endpoint; + IPEndpoint endpoint; DeviceMediaPolicy media_policy; std::unique_ptr<CastSocket> socket; CastSocket::Client* client; @@ -87,19 +83,20 @@ class SenderSocketFactory final friend bool operator<(uint32_t a, const std::unique_ptr<PendingAuth>& b); std::vector<PendingConnection>::iterator FindPendingConnection( - const openscreen::IPEndpoint& endpoint); + const IPEndpoint& endpoint); // CastSocket::Client overrides. - void OnError(CastSocket* socket, openscreen::Error error) override; - void OnMessage(CastSocket* socket, CastMessage message) override; + void OnError(CastSocket* socket, Error error) override; + void OnMessage(CastSocket* socket, + ::cast::channel::CastMessage message) override; Client* const client_; - openscreen::TlsConnectionFactory* factory_ = nullptr; + TlsConnectionFactory* factory_ = nullptr; std::vector<PendingConnection> pending_connections_; std::vector<std::unique_ptr<PendingAuth>> pending_auth_; }; -} // namespace channel } // namespace cast +} // namespace openscreen #endif // CAST_SENDER_CHANNEL_SENDER_SOCKET_FACTORY_H_ diff --git a/cast/standalone_receiver/avcodec_glue.h b/cast/standalone_receiver/avcodec_glue.h index d1dfae78..aa516175 100644 --- a/cast/standalone_receiver/avcodec_glue.h +++ b/cast/standalone_receiver/avcodec_glue.h @@ -14,8 +14,8 @@ extern "C" { #include <libavutil/samplefmt.h> } +namespace openscreen { namespace cast { -namespace streaming { // Macro that, for an AVFoo, generates code for: // @@ -50,7 +50,7 @@ DEFINE_AV_UNIQUE_PTR(AVFrame, av_frame_alloc, av_frame_free(&obj)); #undef DEFINE_AV_UNIQUE_PTR -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_AVCODEC_GLUE_H_ diff --git a/cast/standalone_receiver/decoder.cc b/cast/standalone_receiver/decoder.cc index 8421cd0f..bc0670d3 100644 --- a/cast/standalone_receiver/decoder.cc +++ b/cast/standalone_receiver/decoder.cc @@ -4,8 +4,8 @@ #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { Decoder::Buffer::Buffer() { Resize(0); @@ -196,5 +196,5 @@ AVCodecID Decoder::Detect(const Buffer& buffer) { return AV_CODEC_ID_NONE; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/standalone_receiver/decoder.h b/cast/standalone_receiver/decoder.h index 08d61e43..fef420cf 100644 --- a/cast/standalone_receiver/decoder.h +++ b/cast/standalone_receiver/decoder.h @@ -14,8 +14,8 @@ #include "cast/standalone_receiver/avcodec_glue.h" #include "cast/streaming/frame_id.h" +namespace openscreen { namespace cast { -namespace streaming { // Wraps libavcodec to auto-detect and decode audio or video. class Decoder { @@ -70,8 +70,8 @@ class Decoder { // of the FFMPEG decoder. FrameId DidReceiveFrameFromDecoder(); - // Called when any transient or fatal error occurs, generating an - // openscreen::Error and notifying the Client of it. + // Called when any transient or fatal error occurs, generating an Error and + // notifying the Client of it. void OnError(const char* what, int av_errnum, FrameId frame_id); // Auto-detects the codec needed to decode the data in |buffer|. @@ -90,7 +90,7 @@ class Decoder { std::vector<FrameId> frames_decoding_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_DECODER_H_ diff --git a/cast/standalone_receiver/dummy_player.cc b/cast/standalone_receiver/dummy_player.cc index 8d2af1f7..cce96ee8 100644 --- a/cast/standalone_receiver/dummy_player.cc +++ b/cast/standalone_receiver/dummy_player.cc @@ -12,8 +12,8 @@ using std::chrono::microseconds; +namespace openscreen { namespace cast { -namespace streaming { DummyPlayer::DummyPlayer(Receiver* receiver) : receiver_(receiver) { OSP_DCHECK(receiver_); @@ -41,5 +41,5 @@ void DummyPlayer::OnFramesReady(int buffer_size) { << buffer_size << " bytes"; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/standalone_receiver/dummy_player.h b/cast/standalone_receiver/dummy_player.h index 373d3232..a75aa61e 100644 --- a/cast/standalone_receiver/dummy_player.h +++ b/cast/standalone_receiver/dummy_player.h @@ -13,8 +13,8 @@ #include "platform/api/task_runner.h" #include "platform/api/time.h" +namespace openscreen { namespace cast { -namespace streaming { // Consumes frames from a Receiver, but does nothing other than OSP_LOG_INFO // each one's FrameId, timestamp and size. This is only useful for confirming a @@ -34,7 +34,7 @@ class DummyPlayer : public Receiver::Consumer { std::vector<uint8_t> buffer_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_DUMMY_PLAYER_H_ diff --git a/cast/standalone_receiver/main.cc b/cast/standalone_receiver/main.cc index dd14cd22..8ded25d1 100644 --- a/cast/standalone_receiver/main.cc +++ b/cast/standalone_receiver/main.cc @@ -27,13 +27,8 @@ #include "cast/standalone_receiver/dummy_player.h" #endif // defined(CAST_STREAMING_HAVE_EXTERNAL_LIBS_FOR_DEMO_APPS) -using openscreen::Clock; -using openscreen::IPEndpoint; -using openscreen::TaskRunner; -using openscreen::TaskRunnerImpl; - +namespace openscreen { namespace cast { -namespace streaming { namespace { //////////////////////////////////////////////////////////////////////////////// @@ -50,7 +45,7 @@ namespace { // environment reliability changes. constexpr std::chrono::milliseconds kDemoTargetPlayoutDelay{400}; -const cast::streaming::SessionConfig kSampleAudioAnswerConfig{ +const SessionConfig kSampleAudioAnswerConfig{ /* .sender_ssrc = */ 1, /* .receiver_ssrc = */ 2, @@ -67,7 +62,7 @@ const cast::streaming::SessionConfig kSampleAudioAnswerConfig{ 0x30, 0x20, 0x10, 0x00}, }; -const cast::streaming::SessionConfig kSampleVideoAnswerConfig{ +const SessionConfig kSampleVideoAnswerConfig{ /* .sender_ssrc = */ 50001, /* .receiver_ssrc = */ 50002, /* .rtp_timebase = */ static_cast<int>(kVideoTimebase::den), @@ -87,12 +82,11 @@ constexpr int kCastStreamingPort = 2344; // End of Receiver Configuration. //////////////////////////////////////////////////////////////////////////////// -void DemoMain(TaskRunnerImpl* task_runner) { +void RunStandaloneReceiver(TaskRunnerImpl* task_runner) { // Create the Environment that holds the required injected dependencies // (clock, task runner) used throughout the system, and owns the UDP socket // over which all communication occurs with the Sender. - const IPEndpoint receive_endpoint{openscreen::IPAddress(), - kCastStreamingPort}; + const IPEndpoint receive_endpoint{IPAddress(), kCastStreamingPort}; Environment env(&Clock::now, task_runner, receive_endpoint); // Create the packet router that allows both the Audio Receiver and the Video @@ -153,10 +147,14 @@ void DemoMain(TaskRunnerImpl* task_runner) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen int main(int argc, const char* argv[]) { + using openscreen::Clock; + using openscreen::TaskRunner; + using openscreen::TaskRunnerImpl; + class PlatformClientExposingTaskRunner : public openscreen::PlatformClientPosix { public: @@ -173,7 +171,7 @@ int main(int argc, const char* argv[]) { auto* const platform_client = new PlatformClientExposingTaskRunner( std::make_unique<TaskRunnerImpl>(&Clock::now)); - cast::streaming::DemoMain(static_cast<TaskRunnerImpl*>( + openscreen::cast::RunStandaloneReceiver(static_cast<TaskRunnerImpl*>( openscreen::PlatformClientPosix::GetInstance()->GetTaskRunner())); platform_client->ShutDown(); // Deletes |platform_client|. diff --git a/cast/standalone_receiver/sdl_audio_player.cc b/cast/standalone_receiver/sdl_audio_player.cc index cbd99859..7c7d23c0 100644 --- a/cast/standalone_receiver/sdl_audio_player.cc +++ b/cast/standalone_receiver/sdl_audio_player.cc @@ -16,14 +16,8 @@ using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::seconds; -using openscreen::Clock; -using openscreen::ClockNowFunctionPtr; -using openscreen::Error; -using openscreen::ErrorOr; -using openscreen::TaskRunner; - +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -207,8 +201,6 @@ void SDLAudioPlayer::Present() { // static SDL_AudioFormat SDLAudioPlayer::GetSDLAudioFormat(AVSampleFormat format) { - using openscreen::IsBigEndianArchitecture; - switch (format) { case AV_SAMPLE_FMT_U8P: case AV_SAMPLE_FMT_U8: @@ -234,5 +226,5 @@ SDL_AudioFormat SDLAudioPlayer::GetSDLAudioFormat(AVSampleFormat format) { return kSDLAudioFormatUnknown; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/standalone_receiver/sdl_audio_player.h b/cast/standalone_receiver/sdl_audio_player.h index 89c37146..6b97795d 100644 --- a/cast/standalone_receiver/sdl_audio_player.h +++ b/cast/standalone_receiver/sdl_audio_player.h @@ -7,8 +7,8 @@ #include "cast/standalone_receiver/sdl_player_base.h" +namespace openscreen { namespace cast { -namespace streaming { // Consumes frames from a Receiver, decodes them, and renders them to an // internally-owned SDL audio device. @@ -16,8 +16,8 @@ class SDLAudioPlayer : public SDLPlayerBase { public: // |error_callback| is run only if a fatal error occurs, at which point the // player has halted and set |error_status()|. - SDLAudioPlayer(openscreen::ClockNowFunctionPtr now_function, - openscreen::TaskRunner* task_runner, + SDLAudioPlayer(ClockNowFunctionPtr now_function, + TaskRunner* task_runner, Receiver* receiver, std::function<void()> error_callback); @@ -25,7 +25,7 @@ class SDLAudioPlayer : public SDLPlayerBase { private: // SDLPlayerBase implementation. - openscreen::ErrorOr<openscreen::Clock::time_point> RenderNextFrame( + ErrorOr<Clock::time_point> RenderNextFrame( const SDLPlayerBase::PresentableFrame& frame) final; bool RenderWhileIdle(const SDLPlayerBase::PresentableFrame* frame) final; void Present() final; @@ -38,7 +38,7 @@ class SDLAudioPlayer : public SDLPlayerBase { // The amount of time before a target presentation time to call Present(), to // account for audio buffering (the latency until samples reach the hardware). - openscreen::Clock::duration approximate_lead_time_{}; + Clock::duration approximate_lead_time_{}; // When the decoder provides planar data, this buffer is used for storing the // interleaved conversion. @@ -54,7 +54,7 @@ class SDLAudioPlayer : public SDLPlayerBase { SDL_AudioSpec device_spec_{}; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_SDL_AUDIO_PLAYER_H_ diff --git a/cast/standalone_receiver/sdl_glue.cc b/cast/standalone_receiver/sdl_glue.cc index 89880d6d..3b5deafc 100644 --- a/cast/standalone_receiver/sdl_glue.cc +++ b/cast/standalone_receiver/sdl_glue.cc @@ -8,11 +8,8 @@ #include "platform/api/time.h" #include "util/logging.h" -using openscreen::Clock; -using openscreen::TaskRunner; - +namespace openscreen { namespace cast { -namespace streaming { SDLEventLoopProcessor::SDLEventLoopProcessor( TaskRunner* task_runner, @@ -41,5 +38,5 @@ void SDLEventLoopProcessor::ProcessPendingEvents() { alarm_.ScheduleFromNow([this] { ProcessPendingEvents(); }, kEventPollPeriod); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/standalone_receiver/sdl_glue.h b/cast/standalone_receiver/sdl_glue.h index c4674211..59a3a020 100644 --- a/cast/standalone_receiver/sdl_glue.h +++ b/cast/standalone_receiver/sdl_glue.h @@ -18,11 +18,10 @@ #include "util/alarm.h" namespace openscreen { + class TaskRunner; -} // namespace openscreen namespace cast { -namespace streaming { template <uint32_t subsystem> class ScopedSDLSubSystem { @@ -63,18 +62,18 @@ DEFINE_SDL_UNIQUE_PTR(Texture); // event is received. class SDLEventLoopProcessor { public: - SDLEventLoopProcessor(openscreen::TaskRunner* task_runner, + SDLEventLoopProcessor(TaskRunner* task_runner, std::function<void()> quit_callback); ~SDLEventLoopProcessor(); private: void ProcessPendingEvents(); - openscreen::Alarm alarm_; + Alarm alarm_; std::function<void()> quit_callback_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_SDL_GLUE_H_ diff --git a/cast/standalone_receiver/sdl_player_base.cc b/cast/standalone_receiver/sdl_player_base.cc index ecfcf7c9..64d4d894 100644 --- a/cast/standalone_receiver/sdl_player_base.cc +++ b/cast/standalone_receiver/sdl_player_base.cc @@ -16,14 +16,8 @@ using std::chrono::duration_cast; using std::chrono::milliseconds; -using openscreen::Clock; -using openscreen::ClockNowFunctionPtr; -using openscreen::Error; -using openscreen::ErrorOr; -using openscreen::TaskRunner; - +namespace openscreen { namespace cast { -namespace streaming { SDLPlayerBase::SDLPlayerBase(ClockNowFunctionPtr now_function, TaskRunner* task_runner, @@ -250,5 +244,5 @@ SDLPlayerBase::PendingFrame::PendingFrame(PendingFrame&&) noexcept = default; SDLPlayerBase::PendingFrame& SDLPlayerBase::PendingFrame::operator=( PendingFrame&&) noexcept = default; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/standalone_receiver/sdl_player_base.h b/cast/standalone_receiver/sdl_player_base.h index 365846db..2c2df38f 100644 --- a/cast/standalone_receiver/sdl_player_base.h +++ b/cast/standalone_receiver/sdl_player_base.h @@ -18,8 +18,8 @@ #include "platform/api/time.h" #include "platform/base/error.h" +namespace openscreen { namespace cast { -namespace streaming { // Common base class that consumes frames from a Receiver, decodes them, and // plays them out via the appropriate SDL subsystem. Subclasses implement the @@ -29,7 +29,7 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { ~SDLPlayerBase() override; // Returns OK unless a fatal error has occurred. - const openscreen::Error& error_status() const { return error_status_; } + const Error& error_status() const { return error_status_; } protected: // Current player state, which is used to determine what to render/present, @@ -43,7 +43,7 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { // A decoded frame and its target presentation time. struct PresentableFrame { - openscreen::Clock::time_point presentation_time; + Clock::time_point presentation_time; AVFrameUniquePtr decoded_frame; PresentableFrame(); @@ -55,8 +55,8 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { // |error_callback| is run only if a fatal error occurs, at which point the // player has halted and set |error_status()|. |media_type| should be "audio" // or "video" (only used when logging). - SDLPlayerBase(openscreen::ClockNowFunctionPtr now_function, - openscreen::TaskRunner* task_runner, + SDLPlayerBase(ClockNowFunctionPtr now_function, + TaskRunner* task_runner, Receiver* receiver, std::function<void()> error_callback, const char* media_type); @@ -68,7 +68,7 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { void OnFatalError(std::string message) final; // Renders the |frame| and returns its [possibly adjusted] presentation time. - virtual openscreen::ErrorOr<openscreen::Clock::time_point> RenderNextFrame( + virtual ErrorOr<Clock::time_point> RenderNextFrame( const PresentableFrame& frame) = 0; // Called to render when the player has no new content, and returns true if a @@ -108,13 +108,13 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { // require rendering/presenting a different output. void ResumeRendering(); - const openscreen::ClockNowFunctionPtr now_; + const ClockNowFunctionPtr now_; Receiver* const receiver_; std::function<void()> error_callback_; // Run once by OnFatalError(). const char* const media_type_; // For logging only. // Set to the error code that placed the player in a fatal error state. - openscreen::Error error_status_; + Error error_status_; // Current player state, which is used to determine what to render/present, // and how frequently. @@ -123,7 +123,7 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { // Queue of frames currently being decoded and decoded frames awaiting // rendering. struct PendingFrame : public PresentableFrame { - openscreen::Clock::time_point start_time; + Clock::time_point start_time; PendingFrame(); ~PendingFrame(); @@ -139,7 +139,7 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { // whenever the media (RTP) timestamps drift too much away from the rate at // which the local clock ticks. This is important for A/V synchronization. RtpTimeTicks last_sync_rtp_timestamp_{}; - openscreen::Clock::time_point last_sync_reference_time_{}; + Clock::time_point last_sync_reference_time_{}; Decoder decoder_; @@ -149,13 +149,13 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { // A cumulative moving average of recent single-frame processing times // (consume + decode + render). This is passed to the Cast Receiver so that it // can determine when to drop late frames. - openscreen::Clock::duration recent_processing_time_{}; + Clock::duration recent_processing_time_{}; // Alarms that execute the various stages of the player pipeline at certain // times. - openscreen::Alarm decode_alarm_; - openscreen::Alarm render_alarm_; - openscreen::Alarm presentation_alarm_; + Alarm decode_alarm_; + Alarm render_alarm_; + Alarm presentation_alarm_; // Maximum number of frames in the decode/render pipeline. This limit is about // making sure the player uses resources efficiently: It is better for frames @@ -164,7 +164,7 @@ class SDLPlayerBase : public Receiver::Consumer, public Decoder::Client { static constexpr int kMaxFramesInPipeline = 8; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_SDL_PLAYER_BASE_H_ diff --git a/cast/standalone_receiver/sdl_video_player.cc b/cast/standalone_receiver/sdl_video_player.cc index f91a28a1..78c1c760 100644 --- a/cast/standalone_receiver/sdl_video_player.cc +++ b/cast/standalone_receiver/sdl_video_player.cc @@ -9,14 +9,8 @@ #include "cast/standalone_receiver/avcodec_glue.h" #include "util/logging.h" -using openscreen::Clock; -using openscreen::ClockNowFunctionPtr; -using openscreen::Error; -using openscreen::ErrorOr; -using openscreen::TaskRunner; - +namespace openscreen { namespace cast { -namespace streaming { namespace { constexpr char kVideoMediaType[] = "video"; @@ -201,5 +195,5 @@ uint32_t SDLVideoPlayer::GetSDLPixelFormat(const AVFrame& picture) { return SDL_PIXELFORMAT_UNKNOWN; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/standalone_receiver/sdl_video_player.h b/cast/standalone_receiver/sdl_video_player.h index 515649d0..08b89370 100644 --- a/cast/standalone_receiver/sdl_video_player.h +++ b/cast/standalone_receiver/sdl_video_player.h @@ -7,8 +7,8 @@ #include "cast/standalone_receiver/sdl_player_base.h" +namespace openscreen { namespace cast { -namespace streaming { // Consumes frames from a Receiver, decodes them, and renders them to a // SDL_Renderer. @@ -16,8 +16,8 @@ class SDLVideoPlayer : public SDLPlayerBase { public: // |error_callback| is run only if a fatal error occurs, at which point the // player has halted and set |error_status()|. - SDLVideoPlayer(openscreen::ClockNowFunctionPtr now_function, - openscreen::TaskRunner* task_runner, + SDLVideoPlayer(ClockNowFunctionPtr now_function, + TaskRunner* task_runner, Receiver* receiver, SDL_Renderer* renderer, std::function<void()> error_callback); @@ -32,7 +32,7 @@ class SDLVideoPlayer : public SDLPlayerBase { // Uploads the decoded picture in |frame| to a SDL texture and draws it using // the SDL |renderer_|. - openscreen::ErrorOr<openscreen::Clock::time_point> RenderNextFrame( + ErrorOr<Clock::time_point> RenderNextFrame( const SDLPlayerBase::PresentableFrame& frame) final; // Makes whatever is currently drawn to the SDL |renderer_| be presented @@ -50,7 +50,7 @@ class SDLVideoPlayer : public SDLPlayerBase { SDLTextureUniquePtr texture_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STANDALONE_RECEIVER_SDL_VIDEO_PLAYER_H_ diff --git a/cast/streaming/answer_messages.cc b/cast/streaming/answer_messages.cc index 111c6082..2660ccd8 100644 --- a/cast/streaming/answer_messages.cc +++ b/cast/streaming/answer_messages.cc @@ -7,14 +7,13 @@ #include <utility> #include "absl/strings/str_cat.h" +#include "cast/streaming/message_util.h" #include "platform/base/error.h" #include "util/logging.h" -using openscreen::Error; -using openscreen::ErrorOr; - +namespace openscreen { namespace cast { -namespace streaming { + namespace { static constexpr char kMessageKeyType[] = "type"; @@ -51,10 +50,6 @@ Json::Value PrimitiveVectorToJson(const std::vector<T>& vec) { return array; } -Error CreateParameterError(std::string type) { - return Error(Error::Code::kParameterInvalid, "Invalid parameter: " + type); -} - } // namespace ErrorOr<Json::Value> AudioConstraints::ToJson() const { @@ -208,5 +203,5 @@ Json::Value CreateInvalidAnswer(Error error) { return message_root; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/answer_messages.h b/cast/streaming/answer_messages.h index a2cb7658..1787622c 100644 --- a/cast/streaming/answer_messages.h +++ b/cast/streaming/answer_messages.h @@ -19,8 +19,8 @@ #include "json/value.h" #include "platform/base/error.h" +namespace openscreen { namespace cast { -namespace streaming { struct AudioConstraints { int max_sample_rate = 0; @@ -30,7 +30,7 @@ struct AudioConstraints { int max_bit_rate = 0; std::chrono::milliseconds max_delay = {}; - openscreen::ErrorOr<Json::Value> ToJson() const; + ErrorOr<Json::Value> ToJson() const; }; struct Dimensions { @@ -39,7 +39,7 @@ struct Dimensions { int frame_rate_numerator = 0; int frame_rate_denominator = 0; - openscreen::ErrorOr<Json::Value> ToJson() const; + ErrorOr<Json::Value> ToJson() const; }; struct VideoConstraints { @@ -51,14 +51,14 @@ struct VideoConstraints { int max_bit_rate = 0; std::chrono::milliseconds max_delay = {}; - openscreen::ErrorOr<Json::Value> ToJson() const; + ErrorOr<Json::Value> ToJson() const; }; struct Constraints { AudioConstraints audio; VideoConstraints video; - openscreen::ErrorOr<Json::Value> ToJson() const; + ErrorOr<Json::Value> ToJson() const; }; // Decides whether the Sender scales and letterboxes content to 16:9, or if @@ -78,7 +78,7 @@ struct DisplayDescription { AspectRatio aspect_ratio = {}; AspectRatioConstraint aspect_ratio_constraint = {}; - openscreen::ErrorOr<Json::Value> ToJson() const; + ErrorOr<Json::Value> ToJson() const; }; struct Answer { @@ -100,7 +100,7 @@ struct Answer { // ToJson performs a standard serialization, returning an error if this // instance failed to serialize properly. - openscreen::ErrorOr<Json::Value> ToJson() const; + ErrorOr<Json::Value> ToJson() const; // In constrast to ToJson, ToAnswerMessage performs a successful serialization // even if the answer object is malformed, by complying to the spec's @@ -111,9 +111,9 @@ struct Answer { // Helper method that creates an invalid Answer response. Exposed publicly // here as it is called in ToAnswerMessage(), but can also be called by // the receiver session. -Json::Value CreateInvalidAnswer(openscreen::Error error); +Json::Value CreateInvalidAnswer(Error error); -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_ANSWER_MESSAGES_H_ diff --git a/cast/streaming/answer_messages_unittest.cc b/cast/streaming/answer_messages_unittest.cc index 2a6a64d3..95a30bd7 100644 --- a/cast/streaming/answer_messages_unittest.cc +++ b/cast/streaming/answer_messages_unittest.cc @@ -10,8 +10,8 @@ #include "gtest/gtest.h" #include "util/json/json_serialization.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -176,5 +176,5 @@ TEST(AnswerMessagesTest, InvalidUdpPortsCauseError) { EXPECT_TRUE(value_or_error.is_error()); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/clock_drift_smoother.cc b/cast/streaming/clock_drift_smoother.cc index bb829578..dbcca86e 100644 --- a/cast/streaming/clock_drift_smoother.cc +++ b/cast/streaming/clock_drift_smoother.cc @@ -8,12 +8,11 @@ #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { -constexpr ClockDriftSmoother::Clock::time_point kNullTime = - ClockDriftSmoother::Clock::time_point::min(); +constexpr Clock::time_point kNullTime = Clock::time_point::min(); } ClockDriftSmoother::ClockDriftSmoother(Clock::duration time_constant) @@ -25,7 +24,7 @@ ClockDriftSmoother::ClockDriftSmoother(Clock::duration time_constant) ClockDriftSmoother::~ClockDriftSmoother() = default; -ClockDriftSmoother::Clock::duration ClockDriftSmoother::Current() const { +Clock::duration ClockDriftSmoother::Current() const { OSP_DCHECK(last_update_time_ != kNullTime); const double rounded_estimate = std::round(estimated_tick_offset_); if (rounded_estimate < Clock::duration::min().count()) { @@ -68,5 +67,5 @@ void ClockDriftSmoother::Update(Clock::time_point now, // static constexpr std::chrono::seconds ClockDriftSmoother::kDefaultTimeConstant; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/clock_drift_smoother.h b/cast/streaming/clock_drift_smoother.h index 783c755c..97fe1ec6 100644 --- a/cast/streaming/clock_drift_smoother.h +++ b/cast/streaming/clock_drift_smoother.h @@ -9,16 +9,14 @@ #include "platform/api/time.h" +namespace openscreen { namespace cast { -namespace streaming { // Tracks the jitter and drift between clocks, providing a smoothed offset. // Internally, a Simple IIR filter is used to maintain a running average that // moves at a rate based on the passage of time. class ClockDriftSmoother { public: - using Clock = openscreen::Clock; - // |time_constant| is the amount of time an impulse signal takes to decay by // ~62.6%. Interpretation: If the value passed to several Update() calls is // held constant for T seconds, then the running average will have moved @@ -54,7 +52,7 @@ class ClockDriftSmoother { double estimated_tick_offset_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_CLOCK_DRIFT_SMOOTHER_H_ diff --git a/cast/streaming/compound_rtcp_builder.cc b/cast/streaming/compound_rtcp_builder.cc index 2593e95a..37625d05 100644 --- a/cast/streaming/compound_rtcp_builder.cc +++ b/cast/streaming/compound_rtcp_builder.cc @@ -14,11 +14,8 @@ #include "util/logging.h" #include "util/std_util.h" -using openscreen::AreElementsSortedAndUnique; -using openscreen::Clock; - +namespace openscreen { namespace cast { -namespace streaming { CompoundRtcpBuilder::CompoundRtcpBuilder(RtcpSession* session) : session_(session) { @@ -293,7 +290,7 @@ void CompoundRtcpBuilder::AppendCastFeedbackAckFields( // Compute how many additional octets are needed. constexpr int kIncrement = sizeof(uint32_t); const int num_additional = - openscreen::DividePositivesRoundingUp( + DividePositivesRoundingUp( (octet_index + 1) - num_ack_bitvector_octets, kIncrement) * kIncrement; @@ -328,5 +325,5 @@ void CompoundRtcpBuilder::AppendCastFeedbackAckFields( acks_for_next_packet_.clear(); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/compound_rtcp_builder.h b/cast/streaming/compound_rtcp_builder.h index a2d8e26e..59ceda48 100644 --- a/cast/streaming/compound_rtcp_builder.h +++ b/cast/streaming/compound_rtcp_builder.h @@ -16,8 +16,8 @@ #include "cast/streaming/rtcp_common.h" #include "cast/streaming/rtp_defines.h" +namespace openscreen { namespace cast { -namespace streaming { class RtcpSession; @@ -97,7 +97,7 @@ class CompoundRtcpBuilder { // should be monotonically increasing so the consuming side (the Sender) can // determine the chronological ordering of RTCP packets. The Sender might also // use this to estimate round-trip times over the network. - absl::Span<uint8_t> BuildPacket(openscreen::Clock::time_point send_time, + absl::Span<uint8_t> BuildPacket(Clock::time_point send_time, absl::Span<uint8_t> buffer); // The required buffer size to be provided to BuildPacket(). This accounts for @@ -110,9 +110,8 @@ class CompoundRtcpBuilder { // Helper methods called by BuildPacket() to append one RTCP packet to the // |buffer| that will ultimately contain a "compound RTCP packet." void AppendReceiverReportPacket(absl::Span<uint8_t>* buffer); - void AppendReceiverReferenceTimeReportPacket( - openscreen::Clock::time_point send_time, - absl::Span<uint8_t>* buffer); + void AppendReceiverReferenceTimeReportPacket(Clock::time_point send_time, + absl::Span<uint8_t>* buffer); void AppendPictureLossIndicatorPacket(absl::Span<uint8_t>* buffer); void AppendCastFeedbackPacket(absl::Span<uint8_t>* buffer); int AppendCastFeedbackLossFields(absl::Span<uint8_t>* buffer); @@ -133,7 +132,7 @@ class CompoundRtcpBuilder { uint8_t feedback_count_ = 0; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_COMPOUND_RTCP_BUILDER_H_ diff --git a/cast/streaming/compound_rtcp_builder_unittest.cc b/cast/streaming/compound_rtcp_builder_unittest.cc index c86859b9..969056cf 100644 --- a/cast/streaming/compound_rtcp_builder_unittest.cc +++ b/cast/streaming/compound_rtcp_builder_unittest.cc @@ -15,16 +15,14 @@ #include "gtest/gtest.h" #include "platform/api/time.h" -using openscreen::Clock; - using testing::_; using testing::Invoke; using testing::Mock; using testing::SaveArg; using testing::StrictMock; +namespace openscreen { namespace cast { -namespace streaming { namespace { constexpr Ssrc kSenderSsrc{1}; @@ -369,5 +367,5 @@ TEST_F(CompoundRtcpBuilderTest, WithEverythingThatCanFit) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/compound_rtcp_parser.cc b/cast/streaming/compound_rtcp_parser.cc index b1ea4b67..260989b0 100644 --- a/cast/streaming/compound_rtcp_parser.cc +++ b/cast/streaming/compound_rtcp_parser.cc @@ -11,10 +11,8 @@ #include "util/logging.h" #include "util/std_util.h" -using openscreen::Clock; - +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -185,7 +183,7 @@ bool CompoundRtcpParser::Parse(absl::Span<const uint8_t> buffer, client_->OnReceiverCheckpoint(checkpoint_frame_id, target_playout_delay); } if (!received_frames.empty()) { - OSP_DCHECK(openscreen::AreElementsSortedAndUnique(received_frames)); + OSP_DCHECK(AreElementsSortedAndUnique(received_frames)); client_->OnReceiverHasFrames(std::move(received_frames)); } CanonicalizePacketNackVector(&packet_nacks); @@ -338,7 +336,7 @@ bool CompoundRtcpParser::ParseExtendedReports( return false; // Length field must always be 2 words. } *receiver_reference_time = session_->ntp_converter().ToLocalTime( - openscreen::ReadBigEndian<uint64_t>(in.data())); + ReadBigEndian<uint64_t>(in.data())); } else { // Ignore any other type of extended report. } @@ -377,5 +375,5 @@ void CompoundRtcpParser::Client::OnReceiverHasFrames( void CompoundRtcpParser::Client::OnReceiverIsMissingPackets( std::vector<PacketNack> nacks) {} -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/compound_rtcp_parser.h b/cast/streaming/compound_rtcp_parser.h index 1de12c3f..c74bb3ec 100644 --- a/cast/streaming/compound_rtcp_parser.h +++ b/cast/streaming/compound_rtcp_parser.h @@ -14,8 +14,8 @@ #include "cast/streaming/rtcp_common.h" #include "cast/streaming/rtp_defines.h" +namespace openscreen { namespace cast { -namespace streaming { class RtcpSession; @@ -41,7 +41,7 @@ class CompoundRtcpParser { // Called when a Receiver Reference Time Report has been parsed. virtual void OnReceiverReferenceTimeAdvanced( - openscreen::Clock::time_point reference_time); + Clock::time_point reference_time); // Called when a Receiver Report with a Report Block has been parsed. virtual void OnReceiverReport(const RtcpReportBlock& receiver_report); @@ -101,9 +101,8 @@ class CompoundRtcpParser { std::chrono::milliseconds* target_playout_delay, std::vector<FrameId>* received_frames, std::vector<PacketNack>* packet_nacks); - bool ParseExtendedReports( - absl::Span<const uint8_t> in, - openscreen::Clock::time_point* receiver_reference_time); + bool ParseExtendedReports(absl::Span<const uint8_t> in, + Clock::time_point* receiver_reference_time); bool ParsePictureLossIndicator(absl::Span<const uint8_t> in, bool* picture_loss_indicator); @@ -113,10 +112,10 @@ class CompoundRtcpParser { // Tracks the latest timestamp seen from any Receiver Reference Time Report, // and uses this to ignore stale RTCP packets that arrived out-of-order and/or // late from the network. - openscreen::Clock::time_point latest_receiver_timestamp_; + Clock::time_point latest_receiver_timestamp_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_COMPOUND_RTCP_PARSER_H_ diff --git a/cast/streaming/compound_rtcp_parser_fuzzer.cc b/cast/streaming/compound_rtcp_parser_fuzzer.cc index addc6283..bb3dd179 100644 --- a/cast/streaming/compound_rtcp_parser_fuzzer.cc +++ b/cast/streaming/compound_rtcp_parser_fuzzer.cc @@ -9,10 +9,10 @@ #include "cast/streaming/rtcp_session.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - using cast::streaming::CompoundRtcpParser; - using cast::streaming::FrameId; - using cast::streaming::RtcpSession; - using cast::streaming::Ssrc; + using openscreen::cast::CompoundRtcpParser; + using openscreen::cast::FrameId; + using openscreen::cast::RtcpSession; + using openscreen::cast::Ssrc; constexpr Ssrc kSenderSsrcInSeedCorpus = 1; constexpr Ssrc kReceiverSsrcInSeedCorpus = 2; diff --git a/cast/streaming/compound_rtcp_parser_unittest.cc b/cast/streaming/compound_rtcp_parser_unittest.cc index f09224f9..9f8e3c50 100644 --- a/cast/streaming/compound_rtcp_parser_unittest.cc +++ b/cast/streaming/compound_rtcp_parser_unittest.cc @@ -18,8 +18,8 @@ using testing::Mock; using testing::SaveArg; using testing::StrictMock; +namespace openscreen { namespace cast { -namespace streaming { namespace { constexpr Ssrc kSenderSsrc{1}; @@ -32,7 +32,7 @@ class CompoundRtcpParserTest : public testing::Test { CompoundRtcpParser* parser() { return &parser_; } private: - RtcpSession session_{kSenderSsrc, kReceiverSsrc, openscreen::Clock::now()}; + RtcpSession session_{kSenderSsrc, kReceiverSsrc, Clock::now()}; StrictMock<MockCompoundRtcpParserClient> client_; CompoundRtcpParser parser_{&session_, &client_}; }; @@ -403,5 +403,5 @@ TEST_F(CompoundRtcpParserTest, ParsesFeedbackWithAcks) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/constants.h b/cast/streaming/constants.h index d67ba3e9..4d8bd7ab 100644 --- a/cast/streaming/constants.h +++ b/cast/streaming/constants.h @@ -14,8 +14,8 @@ #include <chrono> #include <ratio> +namespace openscreen { namespace cast { -namespace streaming { // Default target playout delay. The playout delay is the window of time between // capture from the source until presentation at the receiver. @@ -38,7 +38,7 @@ constexpr int kMaxUnackedFrames = 120; // per second for video. using kVideoTimebase = std::ratio<1, 90000>; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_CONSTANTS_H_ diff --git a/cast/streaming/encoded_frame.cc b/cast/streaming/encoded_frame.cc index ebd6cc75..4fb832bd 100644 --- a/cast/streaming/encoded_frame.cc +++ b/cast/streaming/encoded_frame.cc @@ -4,8 +4,8 @@ #include "cast/streaming/encoded_frame.h" +namespace openscreen { namespace cast { -namespace streaming { EncodedFrame::EncodedFrame() = default; EncodedFrame::~EncodedFrame() = default; @@ -22,5 +22,5 @@ void EncodedFrame::CopyMetadataTo(EncodedFrame* dest) const { dest->new_playout_delay = this->new_playout_delay; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/encoded_frame.h b/cast/streaming/encoded_frame.h index cf36b61a..40fbda81 100644 --- a/cast/streaming/encoded_frame.h +++ b/cast/streaming/encoded_frame.h @@ -16,8 +16,8 @@ #include "platform/api/time.h" #include "platform/base/macros.h" +namespace openscreen { namespace cast { -namespace streaming { // A combination of metadata and data for one encoded frame. This can contain // audio data or video data or other. @@ -78,7 +78,7 @@ struct EncodedFrame { // (see |rtp_timestamp|, above). It is also meant to be used to synchronize // the presentation of multiple streams (e.g., audio and video), commonly // known as "lip-sync." It is NOT meant to be a mandatory/exact playout time. - openscreen::Clock::time_point reference_time; + Clock::time_point reference_time; // Playout delay for this and all future frames. Used by the Adaptive // Playout delay extension. Non-positive values means no change. @@ -93,7 +93,7 @@ struct EncodedFrame { OSP_DISALLOW_COPY_AND_ASSIGN(EncodedFrame); }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_ENCODED_FRAME_H_ diff --git a/cast/streaming/environment.cc b/cast/streaming/environment.cc index 55094a4e..b3a6c7b1 100644 --- a/cast/streaming/environment.cc +++ b/cast/streaming/environment.cc @@ -8,18 +8,8 @@ #include "platform/api/task_runner.h" #include "util/logging.h" -using openscreen::Clock; -using openscreen::ClockNowFunctionPtr; -using openscreen::Error; -using openscreen::ErrorOr; -using openscreen::IPAddress; -using openscreen::IPEndpoint; -using openscreen::TaskRunner; -using openscreen::UdpPacket; -using openscreen::UdpSocket; - +namespace openscreen { namespace cast { -namespace streaming { Environment::Environment(ClockNowFunctionPtr now_function, TaskRunner* task_runner) @@ -136,5 +126,5 @@ void Environment::OnRead(UdpSocket* socket, std::move(static_cast<std::vector<uint8_t>&>(packet))); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/environment.h b/cast/streaming/environment.h index 5fb613f5..e96359ad 100644 --- a/cast/streaming/environment.h +++ b/cast/streaming/environment.h @@ -16,20 +16,16 @@ #include "platform/base/ip_address.h" namespace openscreen { -class TaskRunner; -} // namespace openscreen - namespace cast { -namespace streaming { // Provides the common environment for operating system resources shared by // multiple components. -class Environment : public openscreen::UdpSocket::Client { +class Environment : public UdpSocket::Client { public: class PacketConsumer { public: - virtual void OnReceivedPacket(const openscreen::IPEndpoint& source, - openscreen::Clock::time_point arrival_time, + virtual void OnReceivedPacket(const IPEndpoint& source, + Clock::time_point arrival_time, std::vector<uint8_t> packet) = 0; protected: @@ -39,33 +35,30 @@ class Environment : public openscreen::UdpSocket::Client { // Construct with the given clock source and TaskRunner. Creates and // internally-owns a UdpSocket, and immediately binds it to the given // |local_endpoint|. - Environment(openscreen::ClockNowFunctionPtr now_function, - openscreen::TaskRunner* task_runner, - const openscreen::IPEndpoint& local_endpoint); + Environment(ClockNowFunctionPtr now_function, + TaskRunner* task_runner, + const IPEndpoint& local_endpoint); ~Environment() override; - openscreen::ClockNowFunctionPtr now_function() const { return now_function_; } - openscreen::TaskRunner* task_runner() const { return task_runner_; } + ClockNowFunctionPtr now_function() const { return now_function_; } + TaskRunner* task_runner() const { return task_runner_; } // Returns the local endpoint the socket is bound to, or the zero IPEndpoint // if socket creation/binding failed. - openscreen::IPEndpoint GetBoundLocalEndpoint() const; + IPEndpoint GetBoundLocalEndpoint() const; // Set a handler function to run whenever non-recoverable socket errors occur. // If never set, the default is to emit log messages at error priority. - void set_socket_error_handler( - std::function<void(openscreen::Error)> handler) { + void set_socket_error_handler(std::function<void(Error)> handler) { socket_error_handler_ = handler; } // Get/Set the remote endpoint. This is separate from the constructor because // the remote endpoint is, in some cases, discovered only after receiving a // packet. - const openscreen::IPEndpoint& remote_endpoint() const { - return remote_endpoint_; - } - void set_remote_endpoint(const openscreen::IPEndpoint& endpoint) { + const IPEndpoint& remote_endpoint() const { return remote_endpoint_; } + void set_remote_endpoint(const IPEndpoint& endpoint) { remote_endpoint_ = endpoint; } @@ -93,32 +86,29 @@ class Environment : public openscreen::UdpSocket::Client { // Common constructor that just stores the injected dependencies and does not // create a socket. Subclasses use this to provide an alternative packet // receive/send mechanism (e.g., for testing). - Environment(openscreen::ClockNowFunctionPtr now_function, - openscreen::TaskRunner* task_runner); + Environment(ClockNowFunctionPtr now_function, TaskRunner* task_runner); private: - // openscreen::UdpSocket::Client implementation. - void OnError(openscreen::UdpSocket* socket, openscreen::Error error) final; - void OnSendError(openscreen::UdpSocket* socket, - openscreen::Error error) final; - void OnRead(openscreen::UdpSocket* socket, - openscreen::ErrorOr<openscreen::UdpPacket> packet_or_error) final; + // UdpSocket::Client implementation. + void OnError(UdpSocket* socket, Error error) final; + void OnSendError(UdpSocket* socket, Error error) final; + void OnRead(UdpSocket* socket, ErrorOr<UdpPacket> packet_or_error) final; - const openscreen::ClockNowFunctionPtr now_function_; - openscreen::TaskRunner* const task_runner_; + const ClockNowFunctionPtr now_function_; + TaskRunner* const task_runner_; // The UDP socket bound to the local endpoint that was passed into the // constructor, or null if socket creation failed. - const std::unique_ptr<openscreen::UdpSocket> socket_; + const std::unique_ptr<UdpSocket> socket_; // These are externally set/cleared. Behaviors are described in getter/setter // method comments above. - std::function<void(openscreen::Error)> socket_error_handler_; - openscreen::IPEndpoint remote_endpoint_{}; + std::function<void(Error)> socket_error_handler_; + IPEndpoint remote_endpoint_{}; PacketConsumer* packet_consumer_ = nullptr; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_ENVIRONMENT_H_ diff --git a/cast/streaming/expanded_value_base.h b/cast/streaming/expanded_value_base.h index 0ac0dbeb..d418df64 100644 --- a/cast/streaming/expanded_value_base.h +++ b/cast/streaming/expanded_value_base.h @@ -11,8 +11,8 @@ #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { // Abstract base template class for common "sequence value" data types such as // RtpTimeTicks, FrameId, or PacketId which generally increment/decrement in @@ -158,7 +158,7 @@ class ExpandedValueBase { FullWidthInteger value_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_EXPANDED_VALUE_BASE_H_ diff --git a/cast/streaming/expanded_value_base_unittest.cc b/cast/streaming/expanded_value_base_unittest.cc index 220af221..bcbf0d9f 100644 --- a/cast/streaming/expanded_value_base_unittest.cc +++ b/cast/streaming/expanded_value_base_unittest.cc @@ -6,8 +6,8 @@ #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -104,5 +104,5 @@ TEST(ExpandedValueBaseTest, TruncationAndExpansion) { } } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/frame_collector.cc b/cast/streaming/frame_collector.cc index aabbdd06..dbd6fb4d 100644 --- a/cast/streaming/frame_collector.cc +++ b/cast/streaming/frame_collector.cc @@ -12,8 +12,8 @@ #include "cast/streaming/rtp_defines.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -156,5 +156,5 @@ void FrameCollector::Reset() { FrameCollector::PayloadChunk::PayloadChunk() = default; FrameCollector::PayloadChunk::~PayloadChunk() = default; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/frame_collector.h b/cast/streaming/frame_collector.h index 7504d690..ca68ab31 100644 --- a/cast/streaming/frame_collector.h +++ b/cast/streaming/frame_collector.h @@ -13,8 +13,8 @@ #include "cast/streaming/rtcp_common.h" #include "cast/streaming/rtp_packet_parser.h" +namespace openscreen { namespace cast { -namespace streaming { // Used by a Receiver to collect the parts of a frame, track what is // missing/complete, and assemble a complete frame. @@ -84,7 +84,7 @@ class FrameCollector { std::vector<PayloadChunk> chunks_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_FRAME_COLLECTOR_H_ diff --git a/cast/streaming/frame_collector_unittest.cc b/cast/streaming/frame_collector_unittest.cc index 53e13811..34448c24 100644 --- a/cast/streaming/frame_collector_unittest.cc +++ b/cast/streaming/frame_collector_unittest.cc @@ -15,8 +15,8 @@ #include "cast/streaming/rtp_time.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { const FrameId kSomeFrameId = FrameId::first() + 39; @@ -207,5 +207,5 @@ TEST(FrameCollectorTest, RejectsInvalidParts) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/frame_crypto.cc b/cast/streaming/frame_crypto.cc index 416c2df1..4d506d5e 100644 --- a/cast/streaming/frame_crypto.cc +++ b/cast/streaming/frame_crypto.cc @@ -12,8 +12,8 @@ #include "util/big_endian.h" #include "util/crypto/openssl_util.h" +namespace openscreen { namespace cast { -namespace streaming { EncryptedFrame::EncryptedFrame() { data = absl::Span<uint8_t>(owned_data_); @@ -91,8 +91,7 @@ void FrameCrypto::EncryptCommon(FrameId frame_id, std::array<uint8_t, 16> aes_nonce{/* zero initialized */}; static_assert(AES_BLOCK_SIZE == sizeof(aes_nonce), "AES_BLOCK_SIZE is not 16 bytes."); - openscreen::WriteBigEndian<uint32_t>(frame_id.lower_32_bits(), - aes_nonce.data() + 8); + WriteBigEndian<uint32_t>(frame_id.lower_32_bits(), aes_nonce.data() + 8); for (size_t i = 0; i < aes_nonce.size(); ++i) { aes_nonce[i] ^= cast_iv_mask_[i]; } @@ -116,5 +115,5 @@ std::array<uint8_t, 16> FrameCrypto::GenerateRandomBytes() { return result; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/frame_crypto.h b/cast/streaming/frame_crypto.h index 693385ad..35ee9787 100644 --- a/cast/streaming/frame_crypto.h +++ b/cast/streaming/frame_crypto.h @@ -16,8 +16,8 @@ #include "openssl/aes.h" #include "platform/base/macros.h" +namespace openscreen { namespace cast { -namespace streaming { class FrameCollector; class FrameCrypto; @@ -91,7 +91,7 @@ class FrameCrypto { absl::Span<uint8_t> out) const; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_FRAME_CRYPTO_H_ diff --git a/cast/streaming/frame_crypto_unittest.cc b/cast/streaming/frame_crypto_unittest.cc index c5fcd400..7ac8d5cf 100644 --- a/cast/streaming/frame_crypto_unittest.cc +++ b/cast/streaming/frame_crypto_unittest.cc @@ -10,8 +10,8 @@ #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { TEST(FrameCryptoTest, EncryptsAndDecryptsFrames) { @@ -76,5 +76,5 @@ TEST(FrameCryptoTest, EncryptsAndDecryptsFrames) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/frame_id.cc b/cast/streaming/frame_id.cc index bf061fe8..3dd49518 100644 --- a/cast/streaming/frame_id.cc +++ b/cast/streaming/frame_id.cc @@ -4,8 +4,8 @@ #include "cast/streaming/frame_id.h" +namespace openscreen { namespace cast { -namespace streaming { std::ostream& operator<<(std::ostream& out, const FrameId rhs) { out << "F"; @@ -14,5 +14,5 @@ std::ostream& operator<<(std::ostream& out, const FrameId rhs) { return out << rhs.value(); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/frame_id.h b/cast/streaming/frame_id.h index 36252422..5610742f 100644 --- a/cast/streaming/frame_id.h +++ b/cast/streaming/frame_id.h @@ -11,8 +11,8 @@ #include "cast/streaming/expanded_value_base.h" +namespace openscreen { namespace cast { -namespace streaming { // Forward declaration (see below). class FrameId; @@ -104,7 +104,7 @@ class FrameId : public ExpandedValueBase<int64_t, FrameId> { constexpr int64_t value() const { return value_; } }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_FRAME_ID_H_ diff --git a/cast/streaming/message_port.h b/cast/streaming/message_port.h index 901d162b..34873722 100644 --- a/cast/streaming/message_port.h +++ b/cast/streaming/message_port.h @@ -8,11 +8,7 @@ #include "absl/strings/string_view.h" namespace openscreen { -class Error; -} - namespace cast { -namespace streaming { // This interface is intended to provide an abstraction for communicating // cast messages across a pipe with guaranteed delivery. This is used to @@ -25,7 +21,7 @@ class MessagePort { virtual void OnMessage(absl::string_view sender_id, absl::string_view message_namespace, absl::string_view message) = 0; - virtual void OnError(openscreen::Error error) = 0; + virtual void OnError(Error error) = 0; }; virtual ~MessagePort() = default; @@ -35,7 +31,7 @@ class MessagePort { absl::string_view message) = 0; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_MESSAGE_PORT_H_ diff --git a/cast/streaming/message_util.h b/cast/streaming/message_util.h index 17345495..de207da2 100644 --- a/cast/streaming/message_util.h +++ b/cast/streaming/message_util.h @@ -8,21 +8,19 @@ #include "json/value.h" #include "platform/base/error.h" +namespace openscreen { namespace cast { -namespace streaming { -inline openscreen::Error CreateParseError(const std::string& type) { - return openscreen::Error(openscreen::Error::Code::kJsonParseError, - "Failed to parse " + type); +inline Error CreateParseError(const std::string& type) { + return Error(Error::Code::kJsonParseError, "Failed to parse " + type); } -inline openscreen::Error CreateParameterError(const std::string& type) { - return openscreen::Error(openscreen::Error::Code::kParameterInvalid, - "Invalid parameter: " + type); +inline Error CreateParameterError(const std::string& type) { + return Error(Error::Code::kParameterInvalid, "Invalid parameter: " + type); } -inline openscreen::ErrorOr<bool> ParseBool(const Json::Value& parent, - const std::string& field) { +inline ErrorOr<bool> ParseBool(const Json::Value& parent, + const std::string& field) { const Json::Value& value = parent[field]; if (!value.isBool()) { return CreateParseError("bool field " + field); @@ -30,8 +28,8 @@ inline openscreen::ErrorOr<bool> ParseBool(const Json::Value& parent, return value.asBool(); } -inline openscreen::ErrorOr<int> ParseInt(const Json::Value& parent, - const std::string& field) { +inline ErrorOr<int> ParseInt(const Json::Value& parent, + const std::string& field) { const Json::Value& value = parent[field]; if (!value.isInt()) { return CreateParseError("integer field: " + field); @@ -39,8 +37,8 @@ inline openscreen::ErrorOr<int> ParseInt(const Json::Value& parent, return value.asInt(); } -inline openscreen::ErrorOr<uint32_t> ParseUint(const Json::Value& parent, - const std::string& field) { +inline ErrorOr<uint32_t> ParseUint(const Json::Value& parent, + const std::string& field) { const Json::Value& value = parent[field]; if (!value.isUInt()) { return CreateParseError("unsigned integer field: " + field); @@ -48,8 +46,8 @@ inline openscreen::ErrorOr<uint32_t> ParseUint(const Json::Value& parent, return value.asUInt(); } -inline openscreen::ErrorOr<std::string> ParseString(const Json::Value& parent, - const std::string& field) { +inline ErrorOr<std::string> ParseString(const Json::Value& parent, + const std::string& field) { const Json::Value& value = parent[field]; if (!value.isString()) { return CreateParseError("string field: " + field); @@ -61,14 +59,14 @@ inline openscreen::ErrorOr<std::string> ParseString(const Json::Value& parent, // Use this template for parsing only when there is a reasonable default // for the type you are using, e.g. int or std::string. template <typename T> -T ValueOrDefault(const openscreen::ErrorOr<T>& value, T fallback = T{}) { +T ValueOrDefault(const ErrorOr<T>& value, T fallback = T{}) { if (value.is_value()) { return value.value(); } return fallback; } -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_MESSAGE_UTIL_H_ diff --git a/cast/streaming/mock_compound_rtcp_parser_client.h b/cast/streaming/mock_compound_rtcp_parser_client.h index 4411e98a..93d93f67 100644 --- a/cast/streaming/mock_compound_rtcp_parser_client.h +++ b/cast/streaming/mock_compound_rtcp_parser_client.h @@ -8,13 +8,13 @@ #include "cast/streaming/compound_rtcp_parser.h" #include "gmock/gmock.h" +namespace openscreen { namespace cast { -namespace streaming { class MockCompoundRtcpParserClient : public CompoundRtcpParser::Client { public: MOCK_METHOD1(OnReceiverReferenceTimeAdvanced, - void(openscreen::Clock::time_point reference_time)); + void(Clock::time_point reference_time)); MOCK_METHOD1(OnReceiverReport, void(const RtcpReportBlock& receiver_report)); MOCK_METHOD0(OnReceiverIndicatesPictureLoss, void()); MOCK_METHOD2(OnReceiverCheckpoint, @@ -23,7 +23,7 @@ class MockCompoundRtcpParserClient : public CompoundRtcpParser::Client { MOCK_METHOD1(OnReceiverIsMissingPackets, void(std::vector<PacketNack> nacks)); }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_MOCK_COMPOUND_RTCP_PARSER_CLIENT_H_ diff --git a/cast/streaming/ntp_time.cc b/cast/streaming/ntp_time.cc index 5bead4ba..0d59c0a8 100644 --- a/cast/streaming/ntp_time.cc +++ b/cast/streaming/ntp_time.cc @@ -6,11 +6,10 @@ #include "util/logging.h" -using openscreen::Clock; using std::chrono::duration_cast; +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -54,5 +53,5 @@ Clock::time_point NtpTimeConverter::ToLocalTime(NtpTimestamp timestamp) const { return seconds_since_start + remainder; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/ntp_time.h b/cast/streaming/ntp_time.h index 7330148c..6b13132f 100644 --- a/cast/streaming/ntp_time.h +++ b/cast/streaming/ntp_time.h @@ -9,8 +9,8 @@ #include "platform/api/time.h" +namespace openscreen { namespace cast { -namespace streaming { // NTP timestamps are 64-bit timestamps that consist of two 32-bit parts: 1) The // number of seconds since 1 January 1900; and 2) The fraction of the second, @@ -41,22 +41,21 @@ constexpr NtpTimestamp AssembleNtpTimestamp(NtpSeconds seconds, static_cast<uint32_t>(fraction.count()); } -// Converts between openscreen::Clock::time_points and NtpTimestamps. -// The class is instantiated with the current openscreen::Clock time -// and the current wall clock time, and these are used to determine a fixed -// origin reference point for all conversions. Thus, to avoid introducing -// unintended timing-related behaviors, only one NtpTimeConverter instance -// should be used for converting all the NTP timestamps in the same streaming -// session. +// Converts between Clock::time_points and NtpTimestamps. The class is +// instantiated with the current Clock time and the current wall clock time, and +// these are used to determine a fixed origin reference point for all +// conversions. Thus, to avoid introducing unintended timing-related behaviors, +// only one NtpTimeConverter instance should be used for converting all the NTP +// timestamps in the same streaming session. class NtpTimeConverter { public: - NtpTimeConverter(openscreen::Clock::time_point now, - std::chrono::seconds since_unix_epoch = - openscreen::GetWallTimeSinceUnixEpoch()); + NtpTimeConverter( + Clock::time_point now, + std::chrono::seconds since_unix_epoch = GetWallTimeSinceUnixEpoch()); ~NtpTimeConverter(); - NtpTimestamp ToNtpTimestamp(openscreen::Clock::time_point time_point) const; - openscreen::Clock::time_point ToLocalTime(NtpTimestamp timestamp) const; + NtpTimestamp ToNtpTimestamp(Clock::time_point time_point) const; + Clock::time_point ToLocalTime(NtpTimestamp timestamp) const; private: // The time point on the platform clock's timeline that corresponds to @@ -66,11 +65,11 @@ class NtpTimeConverter { // can be off (with respect to each other) by even a large amount; and all // that matters is that time ticks forward at a reasonable pace from some // initial point. - const openscreen::Clock::time_point start_time_; + const Clock::time_point start_time_; const NtpSeconds since_ntp_epoch_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_NTP_TIME_H_ diff --git a/cast/streaming/ntp_time_unittest.cc b/cast/streaming/ntp_time_unittest.cc index 6c72a187..1caa81ad 100644 --- a/cast/streaming/ntp_time_unittest.cc +++ b/cast/streaming/ntp_time_unittest.cc @@ -6,13 +6,12 @@ #include "gtest/gtest.h" -using openscreen::Clock; using std::chrono::duration_cast; using std::chrono::microseconds; using std::chrono::milliseconds; +namespace openscreen { namespace cast { -namespace streaming { TEST(NtpTimestampTest, SplitsIntoParts) { // 1 Jan 1900. @@ -73,8 +72,7 @@ TEST(NtpTimeConverterTest, ConvertsToNtpTimeAndBack) { // our core assumptions (or the design) about the time math are wrong and // should be looked into! const Clock::time_point steady_clock_start = Clock::now(); - const std::chrono::seconds wall_clock_start = - openscreen::GetWallTimeSinceUnixEpoch(); + const std::chrono::seconds wall_clock_start = GetWallTimeSinceUnixEpoch(); SCOPED_TRACE(::testing::Message() << "steady_clock_start.time_since_epoch().count() is " << steady_clock_start.time_since_epoch().count() @@ -106,5 +104,5 @@ TEST(NtpTimeConverterTest, ConvertsToNtpTimeAndBack) { } } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/offer_messages.cc b/cast/streaming/offer_messages.cc index 4ca1fa1b..e9a3a28f 100644 --- a/cast/streaming/offer_messages.cc +++ b/cast/streaming/offer_messages.cc @@ -20,12 +20,8 @@ #include "util/json/json_serialization.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { - -using openscreen::Error; -using openscreen::ErrorOr; -using ErrorCode = openscreen::Error::Code; namespace { @@ -85,8 +81,8 @@ ErrorOr<std::array<uint8_t, 16>> ParseAesHexBytes(const Json::Value& parent, std::none_of(hex_string.value().begin(), hex_string.value().end(), [](char c) { return std::isspace(c); })) { std::array<uint8_t, 16> bytes; - openscreen::WriteBigEndian(quads[0], bytes.data()); - openscreen::WriteBigEndian(quads[1], bytes.data() + 8); + WriteBigEndian(quads[0], bytes.data()); + WriteBigEndian(quads[1], bytes.data() + 8); return bytes; } return CreateParseError("AES hex string bytes"); @@ -286,8 +282,7 @@ std::string CastMode::ToString() const { ErrorOr<Offer> Offer::Parse(const Json::Value& root) { CastMode cast_mode = CastMode::Parse(root["castMode"].asString()); - const openscreen::ErrorOr<bool> get_status = - ParseBool(root, "receiverGetStatus"); + const ErrorOr<bool> get_status = ParseBool(root, "receiverGetStatus"); Json::Value supported_streams = root[kSupportedStreams]; if (!supported_streams.isArray()) { @@ -322,5 +317,5 @@ ErrorOr<Offer> Offer::Parse(const Json::Value& root) { std::move(video_streams)}; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/offer_messages.h b/cast/streaming/offer_messages.h index a4369c5f..7d1c2f9c 100644 --- a/cast/streaming/offer_messages.h +++ b/cast/streaming/offer_messages.h @@ -18,8 +18,8 @@ // This file contains the implementation of the Cast V2 Mirroring Control // Protocol offer object definition. +namespace openscreen { namespace cast { -namespace streaming { // If the target delay provided by the sender is not bounded by // [kMinTargetDelay, kMaxTargetDelay], it will be set to @@ -95,7 +95,7 @@ struct CastMode { }; struct Offer { - static openscreen::ErrorOr<Offer> Parse(const Json::Value& root); + static ErrorOr<Offer> Parse(const Json::Value& root); CastMode cast_mode = {}; // This field is poorly named in the spec (receiverGetStatus), so we use @@ -105,7 +105,7 @@ struct Offer { std::vector<VideoStream> video_streams = {}; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_OFFER_MESSAGES_H_ diff --git a/cast/streaming/offer_messages_unittest.cc b/cast/streaming/offer_messages_unittest.cc index c5ba4071..18ab986c 100644 --- a/cast/streaming/offer_messages_unittest.cc +++ b/cast/streaming/offer_messages_unittest.cc @@ -13,8 +13,8 @@ using ::testing::ElementsAre; +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -86,7 +86,7 @@ constexpr char kValidOffer[] = R"({ })"; void ExpectFailureOnParse(absl::string_view body) { - openscreen::ErrorOr<Json::Value> root = openscreen::json::Parse(body); + ErrorOr<Json::Value> root = json::Parse(body); ASSERT_TRUE(root.is_value()); EXPECT_TRUE(Offer::Parse(std::move(root.value())).is_error()); } @@ -106,7 +106,7 @@ TEST(OfferTest, ErrorOnMissingMandatoryFields) { } TEST(OfferTest, CanParseValidButStreamlessOffer) { - openscreen::ErrorOr<Json::Value> root = openscreen::json::Parse(R"({ + ErrorOr<Json::Value> root = json::Parse(R"({ "castMode": "mirroring", "supportedStreams": [] })"); @@ -143,7 +143,7 @@ TEST(OfferTest, ErrorOnMissingAudioStreamMandatoryField) { } TEST(OfferTest, CanParseValidButMinimalAudioOffer) { - openscreen::ErrorOr<Json::Value> root = openscreen::json::Parse(R"({ + ErrorOr<Json::Value> root = json::Parse(R"({ "castMode": "mirroring", "supportedStreams": [{ "index": 2, @@ -240,7 +240,7 @@ TEST(OfferTest, ErrorOnMissingVideoStreamMandatoryField) { } TEST(OfferTest, CanParseValidButMinimalVideoOffer) { - openscreen::ErrorOr<Json::Value> root = openscreen::json::Parse(R"({ + ErrorOr<Json::Value> root = json::Parse(R"({ "castMode": "mirroring", "supportedStreams": [{ "index": 2, @@ -262,9 +262,9 @@ TEST(OfferTest, CanParseValidButMinimalVideoOffer) { } TEST(OfferTest, CanParseValidOffer) { - openscreen::ErrorOr<Json::Value> root = openscreen::json::Parse(kValidOffer); + ErrorOr<Json::Value> root = json::Parse(kValidOffer); ASSERT_TRUE(root.is_value()); - openscreen::ErrorOr<Offer> offer = Offer::Parse(std::move(root.value())); + ErrorOr<Offer> offer = Offer::Parse(std::move(root.value())); EXPECT_EQ(CastMode::Type::kMirroring, offer.value().cast_mode.type); EXPECT_EQ(true, offer.value().supports_wifi_status_reporting); @@ -346,5 +346,5 @@ TEST(OfferTest, CanParseValidOffer) { 0xe4, 0x11, 0x6c, 0xaa, 0xef, 0xf6, 0xd1)); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/packet_receive_stats_tracker.cc b/cast/streaming/packet_receive_stats_tracker.cc index c00af536..23a5e715 100644 --- a/cast/streaming/packet_receive_stats_tracker.cc +++ b/cast/streaming/packet_receive_stats_tracker.cc @@ -6,10 +6,8 @@ #include <algorithm> -using openscreen::Clock; - +namespace openscreen { namespace cast { -namespace streaming { PacketReceiveStatsTracker::PacketReceiveStatsTracker(int rtp_timebase) : rtp_timebase_(rtp_timebase) {} @@ -77,5 +75,5 @@ void PacketReceiveStatsTracker::PopulateNextReport(RtcpReportBlock* report) { report->jitter = RtpTimeDelta::FromDuration(jitter_, rtp_timebase_); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/packet_receive_stats_tracker.h b/cast/streaming/packet_receive_stats_tracker.h index a13696bf..8d8e23c9 100644 --- a/cast/streaming/packet_receive_stats_tracker.h +++ b/cast/streaming/packet_receive_stats_tracker.h @@ -12,8 +12,8 @@ #include "cast/streaming/rtp_time.h" #include "platform/api/time.h" +namespace openscreen { namespace cast { -namespace streaming { // Maintains statistics for RTP packet arrival timing, jitter, and loss rates; // and then uses these to compute and set the related fields in a RTCP Receiver @@ -31,7 +31,7 @@ class PacketReceiveStatsTracker { // processing/parsing). void OnReceivedValidRtpPacket(uint16_t sequence_number, RtpTimeTicks rtp_timestamp, - openscreen::Clock::time_point arrival_time); + Clock::time_point arrival_time); // Populates *only* those fields in the given |report| that pertain to packet // loss, jitter, and the latest-known RTP packet sequence number. @@ -88,7 +88,7 @@ class PacketReceiveStatsTracker { // The time the last RTP packet was received. This is used in the computation // that updates |jitter_|. - openscreen::Clock::time_point last_rtp_packet_arrival_time_; + Clock::time_point last_rtp_packet_arrival_time_; // The RTP timestamp of the last RTP packet received. This is used in the // computation that updates |jitter_|. @@ -97,10 +97,10 @@ class PacketReceiveStatsTracker { // The interarrival jitter. See RFC 3550 spec, section 6.4.1. The Cast // Streaming spec diverges from the algorithm in the RFC spec in that it uses // different pieces of timing data to calculate this metric. - openscreen::Clock::duration jitter_; + Clock::duration jitter_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_PACKET_RECEIVE_STATS_TRACKER_H_ diff --git a/cast/streaming/packet_receive_stats_tracker_unittest.cc b/cast/streaming/packet_receive_stats_tracker_unittest.cc index c386a799..5146cc8d 100644 --- a/cast/streaming/packet_receive_stats_tracker_unittest.cc +++ b/cast/streaming/packet_receive_stats_tracker_unittest.cc @@ -9,10 +9,8 @@ #include "cast/streaming/constants.h" #include "gtest/gtest.h" -using openscreen::Clock; - +namespace openscreen { namespace cast { -namespace streaming { namespace { constexpr int kSomeRtpTimebase = static_cast<int>(kVideoTimebase::den); @@ -206,5 +204,5 @@ TEST(PacketReceiveStatsTrackerTest, ComputesJitterCorrectly) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/packet_util.cc b/cast/streaming/packet_util.cc index cf43ac14..7e789808 100644 --- a/cast/streaming/packet_util.cc +++ b/cast/streaming/packet_util.cc @@ -7,10 +7,8 @@ #include "cast/streaming/rtcp_common.h" #include "cast/streaming/rtp_defines.h" -using openscreen::ReadBigEndian; - +namespace openscreen { namespace cast { -namespace streaming { std::pair<ApparentPacketType, Ssrc> InspectPacketForRouting( absl::Span<const uint8_t> packet) { @@ -40,5 +38,5 @@ std::pair<ApparentPacketType, Ssrc> InspectPacketForRouting( return std::make_pair(ApparentPacketType::UNKNOWN, Ssrc{0}); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/packet_util.h b/cast/streaming/packet_util.h index 869b917e..ba84ff71 100644 --- a/cast/streaming/packet_util.h +++ b/cast/streaming/packet_util.h @@ -11,14 +11,14 @@ #include "cast/streaming/ssrc.h" #include "util/big_endian.h" +namespace openscreen { namespace cast { -namespace streaming { // Reads a field from the start of the given span and advances the span to point // just after the field. template <typename Integer> inline Integer ConsumeField(absl::Span<const uint8_t>* in) { - const Integer result = openscreen::ReadBigEndian<Integer>(in->data()); + const Integer result = ReadBigEndian<Integer>(in->data()); in->remove_prefix(sizeof(Integer)); return result; } @@ -27,7 +27,7 @@ inline Integer ConsumeField(absl::Span<const uint8_t>* in) { // just after the field. template <typename Integer> inline void AppendField(Integer value, absl::Span<uint8_t>* out) { - openscreen::WriteBigEndian<Integer>(value, out->data()); + WriteBigEndian<Integer>(value, out->data()); out->remove_prefix(sizeof(Integer)); } @@ -56,7 +56,7 @@ enum class ApparentPacketType { UNKNOWN, RTP, RTCP }; std::pair<ApparentPacketType, Ssrc> InspectPacketForRouting( absl::Span<const uint8_t> packet); -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_PACKET_UTIL_H_ diff --git a/cast/streaming/packet_util_unittest.cc b/cast/streaming/packet_util_unittest.cc index 1f1f095d..82e2a408 100644 --- a/cast/streaming/packet_util_unittest.cc +++ b/cast/streaming/packet_util_unittest.cc @@ -7,8 +7,8 @@ #include "absl/types/span.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { // Tests that a simple RTCP packet containing only a Sender Report can be @@ -181,5 +181,5 @@ TEST(PacketUtilTest, InspectsGarbagePacket) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/receiver.cc b/cast/streaming/receiver.cc index f0b1b1d8..4cc4ce2c 100644 --- a/cast/streaming/receiver.cc +++ b/cast/streaming/receiver.cc @@ -13,14 +13,12 @@ #include "util/logging.h" #include "util/std_util.h" -using openscreen::Clock; - using std::chrono::duration_cast; using std::chrono::microseconds; using std::chrono::milliseconds; +namespace openscreen { namespace cast { -namespace streaming { // Conveniences for ensuring logging output includes the SSRC of the Receiver, // to help distinguish one out of multiple instances in a Cast Streaming @@ -33,7 +31,7 @@ namespace streaming { Receiver::Receiver(Environment* environment, ReceiverPacketRouter* packet_router, - const cast::streaming::SessionConfig& config) + const SessionConfig& config) : now_(environment->now_function()), packet_router_(packet_router), rtcp_session_(config.sender_ssrc, config.receiver_ssrc, now_()), @@ -388,7 +386,7 @@ void Receiver::RecordNewTargetPlayoutDelay(FrameId as_of_frame, [&](const auto& entry) { return entry.first > as_of_frame; }); playout_delay_changes_.emplace(insert_it, as_of_frame, delay); - OSP_DCHECK(openscreen::AreElementsSortedAndUnique(playout_delay_changes_)); + OSP_DCHECK(AreElementsSortedAndUnique(playout_delay_changes_)); } milliseconds Receiver::ResolveTargetPlayoutDelay(FrameId frame_id) const { @@ -480,5 +478,5 @@ constexpr milliseconds Receiver::kDefaultPlayerProcessingTime; constexpr int Receiver::kNoFramesReady; constexpr milliseconds Receiver::kNackFeedbackInterval; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/receiver.h b/cast/streaming/receiver.h index a20e444b..eaf0bda3 100644 --- a/cast/streaming/receiver.h +++ b/cast/streaming/receiver.h @@ -29,8 +29,8 @@ #include "platform/api/time.h" #include "util/alarm.h" +namespace openscreen { namespace cast { -namespace streaming { struct EncodedFrame; class ReceiverPacketRouter; @@ -56,7 +56,7 @@ class ReceiverPacketRouter; // decoder, and the resulting decoded media is played out. Also, here is a // general usage example: // -// class MyPlayer : public cast::streaming::Receiver::Consumer { +// class MyPlayer : public openscreen::cast::Receiver::Consumer { // public: // explicit MyPlayer(Receiver* receiver) : receiver_(receiver) { // recevier_->SetPlayerProcessingTime(std::chrono::milliseconds(10)); @@ -72,7 +72,7 @@ class ReceiverPacketRouter; // void OnFramesReady(int next_frame_buffer_size) override { // std::vector<uint8_t> buffer; // buffer.resize(next_frame_buffer_size); -// cast::streaming::EncodedFrame encoded_frame = +// openscreen::cast::EncodedFrame encoded_frame = // receiver_->ConsumeNextFrame(absl::Span<uint8_t>(buffer)); // // display_.RenderFrame(decoder_.DecodeFrame(encoded_frame.data)); @@ -124,7 +124,7 @@ class Receiver { // is started). Receiver(Environment* environment, ReceiverPacketRouter* packet_router, - const cast::streaming::SessionConfig& config); + const SessionConfig& config); ~Receiver(); Ssrc ssrc() const { return rtcp_session_.receiver_ssrc(); } @@ -142,7 +142,7 @@ class Receiver { // based on changing environmental conditions. // // Default setting: kDefaultPlayerProcessingTime - void SetPlayerProcessingTime(openscreen::Clock::duration needed_time); + void SetPlayerProcessingTime(Clock::duration needed_time); // Propagates a "picture loss indicator" notification to the Sender, // requesting a key frame so that decode/playout can recover. It is safe to @@ -183,9 +183,9 @@ class Receiver { // Called by ReceiverPacketRouter to provide this Receiver with what looks // like a RTP/RTCP packet meant for it specifically (among other Receivers). - void OnReceivedRtpPacket(openscreen::Clock::time_point arrival_time, + void OnReceivedRtpPacket(Clock::time_point arrival_time, std::vector<uint8_t> packet); - void OnReceivedRtcpPacket(openscreen::Clock::time_point arrival_time, + void OnReceivedRtcpPacket(Clock::time_point arrival_time, std::vector<uint8_t> packet); private: @@ -197,7 +197,7 @@ class Receiver { // at the Sender. This is computed and assigned when the RTP packet with ID // 0 is processed. Add the target playout delay to this to get the target // playout time. - absl::optional<openscreen::Clock::time_point> estimated_capture_time; + absl::optional<Clock::time_point> estimated_capture_time; PendingFrame(); ~PendingFrame(); @@ -252,9 +252,9 @@ class Receiver { // Sets the |consumption_alarm_| to check whether any frames are ready, // including possibly skipping over late frames in order to make not-yet-late // frames become ready. The default argument value means "without delay." - void ScheduleFrameReadyCheck(openscreen::Clock::time_point when = {}); + void ScheduleFrameReadyCheck(Clock::time_point when = {}); - const openscreen::ClockNowFunctionPtr now_; + const ClockNowFunctionPtr now_; ReceiverPacketRouter* const packet_router_; RtcpSession rtcp_session_; SenderReportParser rtcp_parser_; @@ -271,9 +271,8 @@ class Receiver { // Schedules tasks to ensure RTCP reports are sent within a bounded interval. // Not scheduled until after this Receiver has processed the first packet from // the Sender. - openscreen::Alarm rtcp_alarm_; - openscreen::Clock::time_point last_rtcp_send_time_ = - openscreen::Clock::time_point::min(); + Alarm rtcp_alarm_; + Clock::time_point last_rtcp_send_time_ = Clock::time_point::min(); // The last Sender Report received and when the packet containing it had // arrived. This contains lip-sync timestamps used as part of the calculation @@ -281,7 +280,7 @@ class Receiver { // back to the Sender in the Receiver Reports. It is nullopt until the first // parseable Sender Report is received. absl::optional<SenderReportParser::SenderReportWithId> last_sender_report_; - openscreen::Clock::time_point last_sender_report_arrival_time_; + Clock::time_point last_sender_report_arrival_time_; // Tracks the offset between the Receiver's [local] clock and the Sender's // clock. This is invalid until the first Sender Report has been successfully @@ -328,19 +327,18 @@ class Receiver { // The additional time needed to decode/play-out each frame after being // consumed from this Receiver. - openscreen::Clock::duration player_processing_time_ = - kDefaultPlayerProcessingTime; + Clock::duration player_processing_time_ = kDefaultPlayerProcessingTime; // Scheduled to check whether there are frames ready and, if there are, to // notify the Consumer via OnFramesReady(). - openscreen::Alarm consumption_alarm_; + Alarm consumption_alarm_; // The interval between sending ACK/NACK feedback RTCP messages while // incomplete frames exist in the queue. static constexpr std::chrono::milliseconds kNackFeedbackInterval{30}; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RECEIVER_H_ diff --git a/cast/streaming/receiver_packet_router.cc b/cast/streaming/receiver_packet_router.cc index 456a2ce8..3e109830 100644 --- a/cast/streaming/receiver_packet_router.cc +++ b/cast/streaming/receiver_packet_router.cc @@ -11,11 +11,8 @@ #include "cast/streaming/receiver.h" #include "util/logging.h" -using openscreen::Clock; -using openscreen::IPEndpoint; - +namespace openscreen { namespace cast { -namespace streaming { ReceiverPacketRouter::ReceiverPacketRouter(Environment* environment) : environment_(environment) { @@ -115,5 +112,5 @@ ReceiverPacketRouter::ReceiverEntries::iterator ReceiverPacketRouter::FindEntry( }); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/receiver_packet_router.h b/cast/streaming/receiver_packet_router.h index 007f41f1..d90e5335 100644 --- a/cast/streaming/receiver_packet_router.h +++ b/cast/streaming/receiver_packet_router.h @@ -14,8 +14,8 @@ #include "cast/streaming/environment.h" #include "cast/streaming/ssrc.h" +namespace openscreen { namespace cast { -namespace streaming { class Receiver; @@ -47,8 +47,8 @@ class ReceiverPacketRouter final : public Environment::PacketConsumer { using ReceiverEntries = std::vector<std::pair<Ssrc, Receiver*>>; // Environment::PacketConsumer implementation. - void OnReceivedPacket(const openscreen::IPEndpoint& source, - openscreen::Clock::time_point arrival_time, + void OnReceivedPacket(const IPEndpoint& source, + Clock::time_point arrival_time, std::vector<uint8_t> packet) final; // Helper to return an iterator pointing to the entry corresponding to the @@ -60,7 +60,7 @@ class ReceiverPacketRouter final : public Environment::PacketConsumer { ReceiverEntries receivers_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RECEIVER_PACKET_ROUTER_H_ diff --git a/cast/streaming/receiver_session.cc b/cast/streaming/receiver_session.cc index 19abfa43..6a0b8aba 100644 --- a/cast/streaming/receiver_session.cc +++ b/cast/streaming/receiver_session.cc @@ -15,8 +15,8 @@ #include "cast/streaming/offer_messages.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { // JSON message field values specific to the Receiver Session. static constexpr char kMessageTypeOffer[] = "OFFER"; @@ -134,11 +134,10 @@ ReceiverSession::~ReceiverSession() { void ReceiverSession::OnMessage(absl::string_view sender_id, absl::string_view message_namespace, absl::string_view message) { - openscreen::ErrorOr<Json::Value> message_json = - openscreen::json::Parse(message); + ErrorOr<Json::Value> message_json = json::Parse(message); if (!message_json) { - client_->OnError(this, openscreen::Error::Code::kJsonParseError); + client_->OnError(this, Error::Code::kJsonParseError); OSP_LOG_WARN << "Received an invalid message: " << message; return; } @@ -168,13 +167,13 @@ void ReceiverSession::OnMessage(absl::string_view sender_id, } } -void ReceiverSession::OnError(openscreen::Error error) { +void ReceiverSession::OnError(Error error) { OSP_LOG_WARN << "ReceiverSession's MessagePump encountered an error:" << error; } void ReceiverSession::OnOffer(Message* message) { - openscreen::ErrorOr<Offer> offer = Offer::Parse(std::move(message->body)); + ErrorOr<Offer> offer = Offer::Parse(std::move(message->body)); if (!offer) { client_->OnError(this, offer.error()); OSP_LOG_WARN << "Could not parse offer" << offer.error(); @@ -223,11 +222,11 @@ ReceiverSession::ConstructReceiver(const Stream& stream) { return std::make_pair(std::move(config), std::move(receiver)); } -openscreen::ErrorOr<ConfiguredReceivers> ReceiverSession::TrySpawningReceivers( +ErrorOr<ConfiguredReceivers> ReceiverSession::TrySpawningReceivers( const AudioStream* audio, const VideoStream* video) { if (!audio && !video) { - return openscreen::Error::Code::kParameterInvalid; + return Error::Code::kParameterInvalid; } ResetReceivers(); @@ -302,7 +301,7 @@ void ReceiverSession::SendMessage(Message* message) { // All messages have the sequence number embedded. message->body[kSequenceNumber] = message->sequence_number; - auto body_or_error = openscreen::json::Stringify(message->body); + auto body_or_error = json::Stringify(message->body); if (body_or_error.is_value()) { message_port_->PostMessage(message->sender_id, message->message_namespace, body_or_error.value()); @@ -310,5 +309,6 @@ void ReceiverSession::SendMessage(Message* message) { client_->OnError(this, body_or_error.error()); } } -} // namespace streaming + } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/receiver_session.h b/cast/streaming/receiver_session.h index 4ded8895..72e46385 100644 --- a/cast/streaming/receiver_session.h +++ b/cast/streaming/receiver_session.h @@ -18,16 +18,12 @@ #include "cast/streaming/session_config.h" #include "util/json/json_serialization.h" +namespace openscreen { namespace cast { -namespace channel { class CastSocket; -class CastMessage; class VirtualConnectionRouter; class VirtualConnection; -} // namespace channel - -namespace streaming { class ReceiverSession final : public MessagePort::Client { public: @@ -83,7 +79,8 @@ class ReceiverSession final : public MessagePort::Client { // This method is called immediately preceding the invalidation of // this session's receivers. virtual void OnReceiversDestroyed(ReceiverSession* session) = 0; - virtual void OnError(ReceiverSession* session, openscreen::Error error) = 0; + + virtual void OnError(ReceiverSession* session, Error error) = 0; }; // The embedder has the option of providing a list of prioritized @@ -132,7 +129,7 @@ class ReceiverSession final : public MessagePort::Client { void OnMessage(absl::string_view sender_id, absl::string_view message_namespace, absl::string_view message) override; - void OnError(openscreen::Error error) override; + void OnError(Error error) override; private: struct Message { @@ -150,9 +147,8 @@ class ReceiverSession final : public MessagePort::Client { // Either stream input to this method may be null, however if both // are null this method returns error. - openscreen::ErrorOr<ConfiguredReceivers> TrySpawningReceivers( - const AudioStream* audio, - const VideoStream* video); + ErrorOr<ConfiguredReceivers> TrySpawningReceivers(const AudioStream* audio, + const VideoStream* video); // Callers of this method should ensure at least one stream is non-null. Answer ConstructAnswer(Message* message, @@ -177,7 +173,7 @@ class ReceiverSession final : public MessagePort::Client { std::unique_ptr<Receiver> current_video_receiver_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RECEIVER_SESSION_H_ diff --git a/cast/streaming/receiver_session_unittest.cc b/cast/streaming/receiver_session_unittest.cc index 4d66c210..687da87f 100644 --- a/cast/streaming/receiver_session_unittest.cc +++ b/cast/streaming/receiver_session_unittest.cc @@ -11,16 +11,12 @@ #include "platform/test/fake_clock.h" #include "platform/test/fake_task_runner.h" -using openscreen::Clock; -using openscreen::FakeClock; -using openscreen::FakeTaskRunner; - using ::testing::_; using ::testing::Invoke; using ::testing::StrictMock; +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -177,7 +173,7 @@ class SimpleMessagePort : public MessagePort { message); } - void ReceiveError(openscreen::Error error) { + void ReceiveError(Error error) { ASSERT_NE(client_, nullptr); client_->OnError(error); } @@ -205,14 +201,10 @@ class FakeClient : public ReceiverSession::Client { (ReceiverSession*, ReceiverSession::ConfiguredReceivers), (override)); MOCK_METHOD(void, OnReceiversDestroyed, (ReceiverSession*), (override)); - MOCK_METHOD(void, - OnError, - (ReceiverSession*, openscreen::Error error), - (override)); + MOCK_METHOD(void, OnError, (ReceiverSession*, Error error), (override)); }; -void ExpectIsErrorAnswerMessage( - const openscreen::ErrorOr<Json::Value>& message_or_error) { +void ExpectIsErrorAnswerMessage(const ErrorOr<Json::Value>& message_or_error) { EXPECT_TRUE(message_or_error.is_value()); const Json::Value message = std::move(message_or_error.value()); EXPECT_TRUE(message["answer"].isNull()); @@ -235,7 +227,7 @@ class ReceiverSessionTest : public ::testing::Test { task_runner_(&clock_), env_(std::make_unique<Environment>(&FakeClock::now, &task_runner_, - openscreen::IPEndpoint{})) {} + IPEndpoint{})) {} FakeClock clock_; FakeTaskRunner task_runner_; @@ -287,7 +279,7 @@ TEST_F(ReceiverSessionTest, CanNegotiateWithDefaultPreferences) { const auto& messages = raw_port->posted_messages(); ASSERT_EQ(1u, messages.size()); - auto message_body = openscreen::json::Parse(messages[0]); + auto message_body = json::Parse(messages[0]); EXPECT_TRUE(message_body.is_value()); const Json::Value answer = std::move(message_body.value()); @@ -375,7 +367,7 @@ TEST_F(ReceiverSessionTest, CanNegotiateWithCustomConstraints) { const auto& messages = raw_port->posted_messages(); EXPECT_EQ(1u, messages.size()); - auto message_body = openscreen::json::Parse(messages[0]); + auto message_body = json::Parse(messages[0]); ASSERT_TRUE(message_body.is_value()); const Json::Value answer = std::move(message_body.value()); @@ -432,7 +424,7 @@ TEST_F(ReceiverSessionTest, HandlesNoValidAudioStream) { const auto& messages = raw_port->posted_messages(); EXPECT_EQ(1u, messages.size()); - auto message_body = openscreen::json::Parse(messages[0]); + auto message_body = json::Parse(messages[0]); EXPECT_TRUE(message_body.is_value()); const Json::Value& answer_body = message_body.value()["answer"]; EXPECT_TRUE(answer_body.isObject()); @@ -458,7 +450,7 @@ TEST_F(ReceiverSessionTest, HandlesNoValidVideoStream) { const auto& messages = raw_port->posted_messages(); EXPECT_EQ(1u, messages.size()); - auto message_body = openscreen::json::Parse(messages[0]); + auto message_body = json::Parse(messages[0]); EXPECT_TRUE(message_body.is_value()); const Json::Value& answer_body = message_body.value()["answer"]; EXPECT_TRUE(answer_body.isObject()); @@ -485,7 +477,7 @@ TEST_F(ReceiverSessionTest, HandlesNoValidStreams) { const auto& messages = raw_port->posted_messages(); EXPECT_EQ(1u, messages.size()); - auto message_body = openscreen::json::Parse(messages[0]); + auto message_body = json::Parse(messages[0]); ExpectIsErrorAnswerMessage(message_body); } @@ -501,9 +493,7 @@ TEST_F(ReceiverSessionTest, HandlesMalformedOffer) { // is actually completely invalid we call OnError. EXPECT_CALL(client, OnNegotiated(&session, _)).Times(0); EXPECT_CALL(client, OnReceiversDestroyed(&session)).Times(0); - EXPECT_CALL(client, - OnError(&session, openscreen::Error( - openscreen::Error::Code::kJsonParseError))) + EXPECT_CALL(client, OnError(&session, Error(Error::Code::kJsonParseError))) .Times(1); raw_port->ReceiveMessage(kInvalidJsonOfferMessage); @@ -522,5 +512,5 @@ TEST_F(ReceiverSessionTest, NotifiesReceiverDestruction) { raw_port->ReceiveMessage(kNoAudioOfferMessage); raw_port->ReceiveMessage(kValidOfferMessage); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/receiver_unittest.cc b/cast/streaming/receiver_unittest.cc index 3fa247bd..31515279 100644 --- a/cast/streaming/receiver_unittest.cc +++ b/cast/streaming/receiver_unittest.cc @@ -35,18 +35,6 @@ #include "platform/test/fake_task_runner.h" #include "util/logging.h" -using openscreen::Clock; -using openscreen::ClockNowFunctionPtr; -using openscreen::Error; -using openscreen::ErrorOr; -using openscreen::FakeClock; -using openscreen::FakeTaskRunner; -using openscreen::IPAddress; -using openscreen::IPEndpoint; -using openscreen::TaskRunner; -using openscreen::UdpPacket; -using openscreen::UdpSocket; - using std::chrono::duration_cast; using std::chrono::microseconds; using std::chrono::milliseconds; @@ -58,8 +46,8 @@ using testing::Gt; using testing::Invoke; using testing::SaveArg; +namespace openscreen { namespace cast { -namespace streaming { namespace { // Receiver configuration. @@ -839,5 +827,5 @@ TEST_F(ReceiverTest, DropsLateFrames) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtcp_common.cc b/cast/streaming/rtcp_common.cc index 2a48ce51..d14234fa 100644 --- a/cast/streaming/rtcp_common.cc +++ b/cast/streaming/rtcp_common.cc @@ -9,11 +9,8 @@ #include "cast/streaming/packet_util.h" #include "util/saturate_cast.h" -using openscreen::Clock; -using openscreen::saturate_cast; - +namespace openscreen { namespace cast { -namespace streaming { RtcpCommonHeader::RtcpCommonHeader() = default; RtcpCommonHeader::~RtcpCommonHeader() = default; @@ -242,5 +239,5 @@ absl::optional<RtcpReportBlock> RtcpReportBlock::ParseOne( RtcpSenderReport::RtcpSenderReport() = default; RtcpSenderReport::~RtcpSenderReport() = default; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtcp_common.h b/cast/streaming/rtcp_common.h index 7e7cf963..25e2c2ed 100644 --- a/cast/streaming/rtcp_common.h +++ b/cast/streaming/rtcp_common.h @@ -18,8 +18,8 @@ #include "cast/streaming/rtp_time.h" #include "cast/streaming/ssrc.h" +namespace openscreen { namespace cast { -namespace streaming { struct RtcpCommonHeader { RtcpCommonHeader(); @@ -116,7 +116,7 @@ struct RtcpReportBlock { // Convenience helper to convert the given |local_clock_delay| to the // RtcpReportBlock::Delay timebase, then clamp and assign it to // |delay_since_last_report|. - void SetDelaySinceLastReport(openscreen::Clock::duration local_clock_delay); + void SetDelaySinceLastReport(Clock::duration local_clock_delay); // Serializes this report block in the first |kRtcpReportBlockSize| bytes of // the given |buffer| and adjusts |buffer| to point to the first byte after @@ -138,7 +138,7 @@ struct RtcpSenderReport { // common reference clock shared by all RTP streams; 2) the RTP timestamp on // the media capture/playout timeline. Together, these are used by a Receiver // to achieve A/V synchronization across RTP streams for playout. - openscreen::Clock::time_point reference_time{}; + Clock::time_point reference_time{}; RtpTimeTicks rtp_timestamp; // The total number of RTP packets transmitted since the start of the session @@ -177,7 +177,7 @@ struct PacketNack { } }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RTCP_COMMON_H_ diff --git a/cast/streaming/rtcp_common_unittest.cc b/cast/streaming/rtcp_common_unittest.cc index 9cc6a3fe..d593e4f0 100644 --- a/cast/streaming/rtcp_common_unittest.cc +++ b/cast/streaming/rtcp_common_unittest.cc @@ -11,10 +11,8 @@ #include "gtest/gtest.h" #include "platform/api/time.h" -using openscreen::Clock; - +namespace openscreen { namespace cast { -namespace streaming { namespace { template <typename T> @@ -308,5 +306,5 @@ TEST(RtcpCommonTest, ComputesDelayForReportBlocks) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtcp_session.cc b/cast/streaming/rtcp_session.cc index 2b4af644..c9bf34ff 100644 --- a/cast/streaming/rtcp_session.cc +++ b/cast/streaming/rtcp_session.cc @@ -6,12 +6,12 @@ #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { RtcpSession::RtcpSession(Ssrc sender_ssrc, Ssrc receiver_ssrc, - openscreen::Clock::time_point start_time) + Clock::time_point start_time) : sender_ssrc_(sender_ssrc), receiver_ssrc_(receiver_ssrc), ntp_converter_(start_time) { @@ -22,5 +22,5 @@ RtcpSession::RtcpSession(Ssrc sender_ssrc, RtcpSession::~RtcpSession() = default; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtcp_session.h b/cast/streaming/rtcp_session.h index 33a219cb..0c0b6a45 100644 --- a/cast/streaming/rtcp_session.h +++ b/cast/streaming/rtcp_session.h @@ -8,8 +8,8 @@ #include "cast/streaming/ntp_time.h" #include "cast/streaming/ssrc.h" +namespace openscreen { namespace cast { -namespace streaming { // Session-level configuration and shared components for the RTCP messaging // associated with a single Cast RTP stream. Multiple packet serialization and @@ -21,7 +21,7 @@ class RtcpSession { // world" wall time. RtcpSession(Ssrc sender_ssrc, Ssrc receiver_ssrc, - openscreen::Clock::time_point start_time); + Clock::time_point start_time); ~RtcpSession(); Ssrc sender_ssrc() const { return sender_ssrc_; } @@ -36,7 +36,7 @@ class RtcpSession { NtpTimeConverter ntp_converter_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RTCP_SESSION_H_ diff --git a/cast/streaming/rtp_defines.cc b/cast/streaming/rtp_defines.cc index 0c359129..f12818e7 100644 --- a/cast/streaming/rtp_defines.cc +++ b/cast/streaming/rtp_defines.cc @@ -4,8 +4,8 @@ #include "cast/streaming/rtp_defines.h" +namespace openscreen { namespace cast { -namespace streaming { bool IsRtpPayloadType(uint8_t raw_byte) { switch (static_cast<RtpPayloadType>(raw_byte)) { @@ -42,5 +42,5 @@ bool IsRtcpPacketType(uint8_t raw_byte) { return false; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtp_defines.h b/cast/streaming/rtp_defines.h index 82e60eee..aeb34f8f 100644 --- a/cast/streaming/rtp_defines.h +++ b/cast/streaming/rtp_defines.h @@ -7,8 +7,8 @@ #include <stdint.h> +namespace openscreen { namespace cast { -namespace streaming { // Note: Cast Streaming uses a subset of the messages in the RTP/RTCP // specification, but also adds some of its own extensions. See: @@ -339,7 +339,7 @@ constexpr int kRtcpReceiverReferenceTimeReportBlockSize = 8; // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ constexpr int kRtcpPictureLossIndicatorHeaderSize = 8; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RTP_DEFINES_H_ diff --git a/cast/streaming/rtp_packet_parser.cc b/cast/streaming/rtp_packet_parser.cc index 5fbf005a..b7a838e3 100644 --- a/cast/streaming/rtp_packet_parser.cc +++ b/cast/streaming/rtp_packet_parser.cc @@ -10,10 +10,8 @@ #include "cast/streaming/packet_util.h" #include "util/logging.h" -using openscreen::ReadBigEndian; - +namespace openscreen { namespace cast { -namespace streaming { RtpPacketParser::RtpPacketParser(Ssrc sender_ssrc) : sender_ssrc_(sender_ssrc), highest_rtp_frame_id_(FrameId::first()) {} @@ -114,5 +112,5 @@ absl::optional<RtpPacketParser::ParseResult> RtpPacketParser::Parse( RtpPacketParser::ParseResult::ParseResult() = default; RtpPacketParser::ParseResult::~ParseResult() = default; -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtp_packet_parser.h b/cast/streaming/rtp_packet_parser.h index b2be4c53..b8ce126f 100644 --- a/cast/streaming/rtp_packet_parser.h +++ b/cast/streaming/rtp_packet_parser.h @@ -14,8 +14,8 @@ #include "cast/streaming/rtp_time.h" #include "cast/streaming/ssrc.h" +namespace openscreen { namespace cast { -namespace streaming { // Parses RTP packets for all frames in the same Cast RTP stream. One // RtpPacketParser instance should be used for all RTP packets having the same @@ -72,7 +72,7 @@ class RtpPacketParser { FrameId highest_rtp_frame_id_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RTP_PACKET_PARSER_H_ diff --git a/cast/streaming/rtp_packet_parser_fuzzer.cc b/cast/streaming/rtp_packet_parser_fuzzer.cc index 24169ce7..73bde613 100644 --- a/cast/streaming/rtp_packet_parser_fuzzer.cc +++ b/cast/streaming/rtp_packet_parser_fuzzer.cc @@ -7,8 +7,8 @@ #include "cast/streaming/rtp_packet_parser.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - using cast::streaming::RtpPacketParser; - using cast::streaming::Ssrc; + using openscreen::cast::RtpPacketParser; + using openscreen::cast::Ssrc; constexpr Ssrc kSenderSsrcInSeedCorpus = 0x01020304; RtpPacketParser parser(kSenderSsrcInSeedCorpus); diff --git a/cast/streaming/rtp_packet_parser_unittest.cc b/cast/streaming/rtp_packet_parser_unittest.cc index 927521c0..5f9db875 100644 --- a/cast/streaming/rtp_packet_parser_unittest.cc +++ b/cast/streaming/rtp_packet_parser_unittest.cc @@ -8,11 +8,8 @@ #include "gtest/gtest.h" #include "util/big_endian.h" -using openscreen::ReadBigEndian; -using openscreen::WriteBigEndian; - +namespace openscreen { namespace cast { -namespace streaming { namespace { // Tests that a simple packet for a key frame can be parsed. @@ -309,5 +306,5 @@ TEST(RtpPacketParserTest, RejectsPacketWithBadFramePacketIds) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtp_packetizer.cc b/cast/streaming/rtp_packetizer.cc index 3e0bd506..610791fc 100644 --- a/cast/streaming/rtp_packetizer.cc +++ b/cast/streaming/rtp_packetizer.cc @@ -14,10 +14,8 @@ #include "util/integer_division.h" #include "util/logging.h" -using openscreen::Clock; - +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -124,7 +122,7 @@ absl::Span<uint8_t> RtpPacketizer::GeneratePacket(const EncryptedFrame& frame, int RtpPacketizer::ComputeNumberOfPackets(const EncryptedFrame& frame) const { // The total number of packets is computed by assuming the payload will be // split-up across as few packets as possible. - int num_packets = openscreen::DividePositivesRoundingUp( + int num_packets = DividePositivesRoundingUp( static_cast<int>(frame.data.size()), max_payload_size()); // Edge case: There must always be at least one packet, even when there are no // payload bytes. Some audio codecs, for example, use zero bytes to represent @@ -135,5 +133,5 @@ int RtpPacketizer::ComputeNumberOfPackets(const EncryptedFrame& frame) const { return num_packets <= int{kMaxAllowedFramePacketId} ? num_packets : -1; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtp_packetizer.h b/cast/streaming/rtp_packetizer.h index a3811948..c9b64ac8 100644 --- a/cast/streaming/rtp_packetizer.h +++ b/cast/streaming/rtp_packetizer.h @@ -12,8 +12,8 @@ #include "cast/streaming/rtp_defines.h" #include "cast/streaming/ssrc.h" +namespace openscreen { namespace cast { -namespace streaming { // Transforms a logical sequence of EncryptedFrames into RTP packets for // transmission. A single instance of RtpPacketizer should be used for all the @@ -75,7 +75,7 @@ class RtpPacketizer { kBaseRtpHeaderSize + kAdaptiveLatencyHeaderSize; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RTP_PACKETIZER_H_ diff --git a/cast/streaming/rtp_packetizer_unittest.cc b/cast/streaming/rtp_packetizer_unittest.cc index dc8bf8ac..d99eefa0 100644 --- a/cast/streaming/rtp_packetizer_unittest.cc +++ b/cast/streaming/rtp_packetizer_unittest.cc @@ -11,8 +11,8 @@ #include "cast/streaming/ssrc.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { constexpr RtpPayloadType kPayloadType = RtpPayloadType::kAudioOpus; @@ -42,7 +42,7 @@ class RtpPacketizerTest : public testing::Test { frame.frame_id = frame_id; frame.referenced_frame_id = is_key_frame ? frame_id : (frame_id - 1); frame.rtp_timestamp = RtpTimeTicks() + RtpTimeDelta::FromTicks(987); - frame.reference_time = openscreen::Clock::now(); + frame.reference_time = Clock::now(); frame.new_playout_delay = new_playout_delay; std::unique_ptr<uint8_t[]> buffer(new uint8_t[payload_size]); @@ -203,5 +203,5 @@ TEST_F(RtpPacketizerTest, GeneratesPacketForRetransmission) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtp_time.cc b/cast/streaming/rtp_time.cc index 3f73715e..ee6078d4 100644 --- a/cast/streaming/rtp_time.cc +++ b/cast/streaming/rtp_time.cc @@ -6,8 +6,8 @@ #include <sstream> +namespace openscreen { namespace cast { -namespace streaming { std::ostream& operator<<(std::ostream& out, const RtpTimeDelta rhs) { if (rhs.value_ >= 0) @@ -21,5 +21,5 @@ std::ostream& operator<<(std::ostream& out, const RtpTimeTicks rhs) { return out << "RTP@" << rhs.value_; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/rtp_time.h b/cast/streaming/rtp_time.h index 0a7f5d86..0e710f50 100644 --- a/cast/streaming/rtp_time.h +++ b/cast/streaming/rtp_time.h @@ -15,8 +15,8 @@ #include "cast/streaming/expanded_value_base.h" #include "platform/api/time.h" +namespace openscreen { namespace cast { -namespace streaming { // Forward declarations (see below). class RtpTimeDelta; @@ -262,7 +262,7 @@ class RtpTimeTicks : public ExpandedValueBase<int64_t, RtpTimeTicks> { constexpr int64_t value() const { return value_; } }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_RTP_TIME_H_ diff --git a/cast/streaming/rtp_time_unittest.cc b/cast/streaming/rtp_time_unittest.cc index 44312e7b..8427a5ea 100644 --- a/cast/streaming/rtp_time_unittest.cc +++ b/cast/streaming/rtp_time_unittest.cc @@ -6,8 +6,8 @@ #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { // Tests that conversions between std::chrono durations and RtpTimeDelta are // accurate. Note that this implicitly tests the conversions to/from @@ -71,5 +71,5 @@ TEST(RtpTimeDeltaTest, ConversionToAndFromDurations) { .ToDuration<microseconds>(kTimebase)); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/sender_report_builder.cc b/cast/streaming/sender_report_builder.cc index 56d100d8..c04acdc3 100644 --- a/cast/streaming/sender_report_builder.cc +++ b/cast/streaming/sender_report_builder.cc @@ -7,8 +7,8 @@ #include "cast/streaming/packet_util.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { SenderReportBuilder::SenderReportBuilder(RtcpSession* session) : session_(session) { @@ -52,5 +52,5 @@ std::pair<absl::Span<uint8_t>, StatusReportId> SenderReportBuilder::BuildPacket( ToStatusReportId(ntp_timestamp)); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/sender_report_builder.h b/cast/streaming/sender_report_builder.h index 724e7342..49d402c1 100644 --- a/cast/streaming/sender_report_builder.h +++ b/cast/streaming/sender_report_builder.h @@ -14,8 +14,8 @@ #include "cast/streaming/rtcp_session.h" #include "cast/streaming/rtp_defines.h" +namespace openscreen { namespace cast { -namespace streaming { // Builds RTCP packets containing one Sender Report. class SenderReportBuilder { @@ -39,7 +39,7 @@ class SenderReportBuilder { RtcpSession* const session_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_SENDER_REPORT_BUILDER_H_ diff --git a/cast/streaming/sender_report_parser.cc b/cast/streaming/sender_report_parser.cc index 4770dd6b..d9174863 100644 --- a/cast/streaming/sender_report_parser.cc +++ b/cast/streaming/sender_report_parser.cc @@ -7,8 +7,8 @@ #include "cast/streaming/packet_util.h" #include "util/logging.h" +namespace openscreen { namespace cast { -namespace streaming { SenderReportParser::SenderReportWithId::SenderReportWithId() = default; SenderReportParser::SenderReportWithId::~SenderReportWithId() = default; @@ -71,5 +71,5 @@ SenderReportParser::Parse(absl::Span<const uint8_t> buffer) { return sender_report; } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/sender_report_parser.h b/cast/streaming/sender_report_parser.h index df7f89a0..3c66829c 100644 --- a/cast/streaming/sender_report_parser.h +++ b/cast/streaming/sender_report_parser.h @@ -12,8 +12,8 @@ #include "cast/streaming/rtp_defines.h" #include "cast/streaming/rtp_time.h" +namespace openscreen { namespace cast { -namespace streaming { // Parses RTCP packets from a Sender to extract Sender Reports. Ignores anything // else, since that is all a Receiver would be interested in. @@ -45,7 +45,7 @@ class SenderReportParser { RtpTimeTicks last_parsed_rtp_timestamp_; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_SENDER_REPORT_PARSER_H_ diff --git a/cast/streaming/sender_report_parser_fuzzer.cc b/cast/streaming/sender_report_parser_fuzzer.cc index 8c91a6d2..c79eaa6a 100644 --- a/cast/streaming/sender_report_parser_fuzzer.cc +++ b/cast/streaming/sender_report_parser_fuzzer.cc @@ -8,10 +8,10 @@ #include "platform/api/time.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - using cast::streaming::RtcpSenderReport; - using cast::streaming::RtcpSession; - using cast::streaming::SenderReportParser; - using cast::streaming::Ssrc; + using openscreen::cast::RtcpSenderReport; + using openscreen::cast::RtcpSession; + using openscreen::cast::SenderReportParser; + using openscreen::cast::Ssrc; constexpr Ssrc kSenderSsrcInSeedCorpus = 1; constexpr Ssrc kReceiverSsrcInSeedCorpus = 2; diff --git a/cast/streaming/sender_report_unittest.cc b/cast/streaming/sender_report_unittest.cc index 4f757fc0..63da8012 100644 --- a/cast/streaming/sender_report_unittest.cc +++ b/cast/streaming/sender_report_unittest.cc @@ -9,8 +9,8 @@ #include "cast/streaming/sender_report_parser.h" #include "gtest/gtest.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { constexpr Ssrc kSenderSsrc{1}; @@ -25,7 +25,7 @@ class SenderReportTest : public testing::Test { } private: - RtcpSession session_{kSenderSsrc, kReceiverSsrc, openscreen::Clock::now()}; + RtcpSession session_{kSenderSsrc, kReceiverSsrc, Clock::now()}; SenderReportBuilder builder_{&session_}; SenderReportParser parser_{&session_}; }; @@ -119,7 +119,7 @@ TEST_F(SenderReportTest, BuildPackets) { const bool with_report_block = (i == 1); RtcpSenderReport original; - original.reference_time = openscreen::Clock::now(); + original.reference_time = Clock::now(); original.rtp_timestamp = RtpTimeTicks() + RtpTimeDelta::FromTicks(5); original.send_packet_count = 55; original.send_octet_count = 20044; @@ -161,5 +161,5 @@ TEST_F(SenderReportTest, BuildPackets) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/session_config.cc b/cast/streaming/session_config.cc index 024cb093..65117029 100644 --- a/cast/streaming/session_config.cc +++ b/cast/streaming/session_config.cc @@ -4,8 +4,8 @@ #include "cast/streaming/session_config.h" +namespace openscreen { namespace cast { -namespace streaming { SessionConfig::SessionConfig(Ssrc sender_ssrc, Ssrc receiver_ssrc, @@ -22,5 +22,5 @@ SessionConfig::SessionConfig(Ssrc sender_ssrc, aes_secret_key(aes_secret_key), aes_iv_mask(aes_iv_mask) {} -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/session_config.h b/cast/streaming/session_config.h index dc8cd553..4d611b65 100644 --- a/cast/streaming/session_config.h +++ b/cast/streaming/session_config.h @@ -11,8 +11,8 @@ #include "cast/streaming/ssrc.h" +namespace openscreen { namespace cast { -namespace streaming { // Common streaming configuration, established from the OFFER/ANSWER exchange, // that the Sender and Receiver are both assuming. @@ -52,7 +52,7 @@ struct SessionConfig final { std::array<uint8_t, 16> aes_iv_mask{}; }; -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_SESSION_CONFIG_H_ diff --git a/cast/streaming/ssrc.cc b/cast/streaming/ssrc.cc index cb18a800..d71b8069 100644 --- a/cast/streaming/ssrc.cc +++ b/cast/streaming/ssrc.cc @@ -8,8 +8,8 @@ #include "platform/api/time.h" +namespace openscreen { namespace cast { -namespace streaming { namespace { @@ -28,7 +28,7 @@ Ssrc GenerateSsrc(bool higher_priority) { // it is light-weight and does not need to produce unguessable (nor // crypto-secure) values. static std::minstd_rand generator(static_cast<std::minstd_rand::result_type>( - openscreen::Clock::now().time_since_epoch().count())); + Clock::now().time_since_epoch().count())); std::uniform_int_distribution<int> distribution( higher_priority ? kHigherPriorityMin : kNormalPriorityMin, @@ -40,5 +40,5 @@ int ComparePriority(Ssrc ssrc_a, Ssrc ssrc_b) { return static_cast<int>(ssrc_a) - static_cast<int>(ssrc_b); } -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/streaming/ssrc.h b/cast/streaming/ssrc.h index 0cd23566..b84d7ac0 100644 --- a/cast/streaming/ssrc.h +++ b/cast/streaming/ssrc.h @@ -7,8 +7,8 @@ #include <stdint.h> +namespace openscreen { namespace cast { -namespace streaming { // A Synchronization Source is a 32-bit opaque identifier used in RTP packets // for identifying the source (or recipient) of a logical sequence of encoded @@ -33,7 +33,7 @@ Ssrc GenerateSsrc(bool higher_priority); // ret > 0: Stream |ssrc_b| has higher priority. int ComparePriority(Ssrc ssrc_a, Ssrc ssrc_b); -} // namespace streaming } // namespace cast +} // namespace openscreen #endif // CAST_STREAMING_SSRC_H_ diff --git a/cast/streaming/ssrc_unittest.cc b/cast/streaming/ssrc_unittest.cc index 29741409..aa9e50ed 100644 --- a/cast/streaming/ssrc_unittest.cc +++ b/cast/streaming/ssrc_unittest.cc @@ -9,10 +9,8 @@ #include "gtest/gtest.h" #include "util/std_util.h" -using openscreen::SortAndDedupeElements; - +namespace openscreen { namespace cast { -namespace streaming { namespace { TEST(SsrcTest, GeneratesUniqueAndPrioritizedSsrcs) { @@ -53,5 +51,5 @@ TEST(SsrcTest, GeneratesUniqueAndPrioritizedSsrcs) { } } // namespace -} // namespace streaming } // namespace cast +} // namespace openscreen diff --git a/cast/test/device_auth_test.cc b/cast/test/device_auth_test.cc index 3d30e43b..7c413e03 100644 --- a/cast/test/device_auth_test.cc +++ b/cast/test/device_auth_test.cc @@ -18,15 +18,16 @@ #include "gtest/gtest.h" #include "testing/util/read_file.h" +namespace openscreen { namespace cast { -namespace channel { namespace { +using ::cast::channel::CastMessage; +using ::cast::channel::DeviceAuthMessage; + using ::testing::_; using ::testing::Invoke; -using openscreen::ErrorOr; - #define TEST_DATA_PREFIX OPENSCREEN_TEST_DATA_DIR "cast/receiver/channel/" class DeviceAuthTest : public ::testing::Test { @@ -40,11 +41,11 @@ class DeviceAuthTest : public ::testing::Test { protected: void RunAuthTest(std::string serialized_crl, - certificate::TrustStore* fake_crl_trust_store, + TrustStore* fake_crl_trust_store, bool should_succeed = true, bool record_this_test = false) { bssl::UniquePtr<X509> parsed_cert; - certificate::TrustStore fake_trust_store; + TrustStore fake_trust_store; InitStaticCredentialsFromFiles(&creds_, &parsed_cert, &fake_trust_store, TEST_DATA_PREFIX "device_key.pem", TEST_DATA_PREFIX "device_chain.pem", @@ -58,7 +59,8 @@ class DeviceAuthTest : public ::testing::Test { if (record_this_test) { std::string output; DeviceAuthMessage auth_message; - ASSERT_EQ(auth_challenge.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(auth_challenge.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE( auth_message.ParseFromString(auth_challenge.payload_binary())); ASSERT_TRUE(auth_message.has_challenge()); @@ -82,7 +84,8 @@ class DeviceAuthTest : public ::testing::Test { if (record_this_test) { std::string output; DeviceAuthMessage auth_message; - ASSERT_EQ(challenge_reply.payload_type(), CastMessage_PayloadType_BINARY); + ASSERT_EQ(challenge_reply.payload_type(), + ::cast::channel::CastMessage_PayloadType_BINARY); ASSERT_TRUE( auth_message.ParseFromString(challenge_reply.payload_binary())); ASSERT_TRUE(auth_message.has_response()); @@ -96,15 +99,15 @@ class DeviceAuthTest : public ::testing::Test { fclose(fd); } - certificate::DateTime December2019 = {}; + DateTime December2019 = {}; December2019.year = 2019; December2019.month = 12; December2019.day = 17; const ErrorOr<CastDeviceCertPolicy> error_or_policy = AuthenticateChallengeReplyForTest( challenge_reply, parsed_cert.get(), auth_context, - fake_crl_trust_store ? certificate::CRLPolicy::kCrlRequired - : certificate::CRLPolicy::kCrlOptional, + fake_crl_trust_store ? CRLPolicy::kCrlRequired + : CRLPolicy::kCrlOptional, &fake_trust_store, fake_crl_trust_store, December2019); EXPECT_EQ(error_or_policy.is_value(), should_succeed); } @@ -119,8 +122,6 @@ class DeviceAuthTest : public ::testing::Test { DeviceAuthNamespaceHandler auth_handler_{&creds_}; }; -} // namespace - TEST_F(DeviceAuthTest, MANUAL_SerializeTestData) { if (::testing::GTEST_FLAG(filter) == "DeviceAuthTest.MANUAL_SerializeTestData") { @@ -133,76 +134,63 @@ TEST_F(DeviceAuthTest, AuthIntegration) { } TEST_F(DeviceAuthTest, GoodCrl) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest( - openscreen::ReadEntireFileToString(TEST_DATA_PREFIX "good_crl.pb"), - fake_crl_trust_store.get()); + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest(ReadEntireFileToString(TEST_DATA_PREFIX "good_crl.pb"), + fake_crl_trust_store.get()); } TEST_F(DeviceAuthTest, InvalidCrlTime) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString(TEST_DATA_PREFIX - "invalid_time_crl.pb"), + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest(ReadEntireFileToString(TEST_DATA_PREFIX "invalid_time_crl.pb"), fake_crl_trust_store.get(), false); } TEST_F(DeviceAuthTest, IssuerRevoked) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString(TEST_DATA_PREFIX - "issuer_revoked_crl.pb"), + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest(ReadEntireFileToString(TEST_DATA_PREFIX "issuer_revoked_crl.pb"), fake_crl_trust_store.get(), false); } TEST_F(DeviceAuthTest, DeviceRevoked) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString(TEST_DATA_PREFIX - "device_revoked_crl.pb"), + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest(ReadEntireFileToString(TEST_DATA_PREFIX "device_revoked_crl.pb"), fake_crl_trust_store.get(), false); } TEST_F(DeviceAuthTest, IssuerSerialRevoked) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString( - TEST_DATA_PREFIX "issuer_serial_revoked_crl.pb"), - fake_crl_trust_store.get(), false); + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest( + ReadEntireFileToString(TEST_DATA_PREFIX "issuer_serial_revoked_crl.pb"), + fake_crl_trust_store.get(), false); } TEST_F(DeviceAuthTest, DeviceSerialRevoked) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString( - TEST_DATA_PREFIX "device_serial_revoked_crl.pb"), - fake_crl_trust_store.get(), false); + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest( + ReadEntireFileToString(TEST_DATA_PREFIX "device_serial_revoked_crl.pb"), + fake_crl_trust_store.get(), false); } TEST_F(DeviceAuthTest, BadCrlSignerCert) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString(TEST_DATA_PREFIX - "bad_signer_cert_crl.pb"), + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest(ReadEntireFileToString(TEST_DATA_PREFIX "bad_signer_cert_crl.pb"), fake_crl_trust_store.get(), false); } TEST_F(DeviceAuthTest, BadCrlSignature) { - std::unique_ptr<certificate::TrustStore> fake_crl_trust_store = - certificate::testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX - "crl_root.pem"); - RunAuthTest(openscreen::ReadEntireFileToString(TEST_DATA_PREFIX - "bad_signature_crl.pb"), + std::unique_ptr<TrustStore> fake_crl_trust_store = + testing::CreateTrustStoreFromPemFile(TEST_DATA_PREFIX "crl_root.pem"); + RunAuthTest(ReadEntireFileToString(TEST_DATA_PREFIX "bad_signature_crl.pb"), fake_crl_trust_store.get(), false); } -} // namespace channel +} // namespace } // namespace cast +} // namespace openscreen diff --git a/cast/test/make_crl_tests.cc b/cast/test/make_crl_tests.cc index edbe1afd..76e08258 100644 --- a/cast/test/make_crl_tests.cc +++ b/cast/test/make_crl_tests.cc @@ -15,42 +15,37 @@ #define TEST_DATA_PREFIX OPENSCREEN_TEST_DATA_DIR "cast/receiver/channel/" +namespace openscreen { namespace cast { namespace { -using certificate::ConstDataSpan; -using certificate::DateTime; -using openscreen::Error; -using openscreen::ErrorOr; - -std::string* AddRevokedPublicKeyHash(certificate::TbsCrl* tbs_crl, X509* cert) { +std::string* AddRevokedPublicKeyHash(TbsCrl* tbs_crl, X509* cert) { std::string* pubkey_hash = tbs_crl->add_revoked_public_key_hashes(); - std::string pubkey_spki = openscreen::GetSpkiTlv(cert); - ErrorOr<std::string> hash_value = openscreen::SHA256HashString(pubkey_spki); + std::string pubkey_spki = GetSpkiTlv(cert); + ErrorOr<std::string> hash_value = SHA256HashString(pubkey_spki); OSP_DCHECK(hash_value.is_value()); *pubkey_hash = std::move(hash_value.value()); return pubkey_hash; } -void AddSerialNumberRange(certificate::TbsCrl* tbs_crl, +void AddSerialNumberRange(TbsCrl* tbs_crl, X509* issuer, uint64_t first, uint64_t last) { - certificate::SerialNumberRange* serial_range = - tbs_crl->add_revoked_serial_number_ranges(); - std::string issuer_spki = openscreen::GetSpkiTlv(issuer); - ErrorOr<std::string> issuer_hash = openscreen::SHA256HashString(issuer_spki); + SerialNumberRange* serial_range = tbs_crl->add_revoked_serial_number_ranges(); + std::string issuer_spki = GetSpkiTlv(issuer); + ErrorOr<std::string> issuer_hash = SHA256HashString(issuer_spki); OSP_DCHECK(issuer_hash.is_value()); serial_range->set_issuer_public_key_hash(std::move(issuer_hash.value())); serial_range->set_first_serial_number(first); serial_range->set_last_serial_number(last); } -certificate::TbsCrl MakeTbsCrl(uint64_t not_before, - uint64_t not_after, - X509* device_cert, - X509* inter_cert) { - certificate::TbsCrl tbs_crl; +TbsCrl MakeTbsCrl(uint64_t not_before, + uint64_t not_after, + X509* device_cert, + X509* inter_cert) { + TbsCrl tbs_crl; tbs_crl.set_version(0); tbs_crl.set_not_before_seconds(not_before); tbs_crl.set_not_after_seconds(not_after); @@ -62,7 +57,7 @@ certificate::TbsCrl MakeTbsCrl(uint64_t not_before, // NOTE: Include default serial number range at device-level, which should not // include any of our certs. ErrorOr<uint64_t> maybe_serial = - openscreen::ParseDerUint64(device_cert->cert_info->serialNumber); + ParseDerUint64(device_cert->cert_info->serialNumber); OSP_DCHECK(maybe_serial); uint64_t serial = maybe_serial.value(); OSP_DCHECK_LE(serial, UINT64_MAX - 200); @@ -74,19 +69,19 @@ certificate::TbsCrl MakeTbsCrl(uint64_t not_before, // Pack into a CrlBundle and sign with |crl_inter_key|. |crl_inter_der| must be // directly signed by a Cast CRL root CA (possibly distinct from Cast root CA). void PackCrlIntoFile(const char* filename, - const certificate::TbsCrl& tbs_crl, + const TbsCrl& tbs_crl, const std::string& crl_inter_der, EVP_PKEY* crl_inter_key) { - certificate::CrlBundle crl_bundle; - certificate::Crl* crl = crl_bundle.add_crls(); + CrlBundle crl_bundle; + Crl* crl = crl_bundle.add_crls(); std::string* tbs_crl_serial = crl->mutable_tbs_crl(); tbs_crl.SerializeToString(tbs_crl_serial); crl->set_signer_cert(crl_inter_der); - ErrorOr<std::string> signature = openscreen::SignData( - EVP_sha256(), crl_inter_key, - absl::Span<const uint8_t>{ - reinterpret_cast<const uint8_t*>(tbs_crl_serial->data()), - tbs_crl_serial->size()}); + ErrorOr<std::string> signature = + SignData(EVP_sha256(), crl_inter_key, + absl::Span<const uint8_t>{ + reinterpret_cast<const uint8_t*>(tbs_crl_serial->data()), + tbs_crl_serial->size()}); OSP_DCHECK(signature); crl->set_signature(std::move(signature.value())); @@ -100,20 +95,16 @@ void PackCrlIntoFile(const char* filename, int CastMain() { bssl::UniquePtr<EVP_PKEY> inter_key = - certificate::testing::ReadKeyFromPemFile(TEST_DATA_PREFIX - "inter_key.pem"); + testing::ReadKeyFromPemFile(TEST_DATA_PREFIX "inter_key.pem"); bssl::UniquePtr<EVP_PKEY> crl_inter_key = - certificate::testing::ReadKeyFromPemFile(TEST_DATA_PREFIX - "crl_inter_key.pem"); + testing::ReadKeyFromPemFile(TEST_DATA_PREFIX "crl_inter_key.pem"); OSP_DCHECK(inter_key); OSP_DCHECK(crl_inter_key); std::vector<std::string> chain_der = - certificate::testing::ReadCertificatesFromPemFile(TEST_DATA_PREFIX - "device_chain.pem"); + testing::ReadCertificatesFromPemFile(TEST_DATA_PREFIX "device_chain.pem"); std::vector<std::string> crl_inter_der = - certificate::testing::ReadCertificatesFromPemFile(TEST_DATA_PREFIX - "crl_inter.pem"); + testing::ReadCertificatesFromPemFile(TEST_DATA_PREFIX "crl_inter.pem"); OSP_DCHECK_EQ(chain_der.size(), 3u); OSP_DCHECK_EQ(crl_inter_der.size(), 1u); @@ -145,11 +136,10 @@ int CastMain() { july2020.month = 7; july2020.year = 2020; july2020.day = 23; - std::chrono::seconds not_before = certificate::DateTimeToSeconds(july2019); - std::chrono::seconds not_after = certificate::DateTimeToSeconds(july2020); - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + std::chrono::seconds not_before = DateTimeToSeconds(july2019); + std::chrono::seconds not_after = DateTimeToSeconds(july2020); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); PackCrlIntoFile(TEST_DATA_PREFIX "good_crl.pb", tbs_crl, crl_inter_der[0], crl_inter_key.get()); @@ -159,19 +149,17 @@ int CastMain() { august2019.month = 8; august2019.year = 2019; august2019.day = 16; - std::chrono::seconds not_after = certificate::DateTimeToSeconds(august2019); - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + std::chrono::seconds not_after = DateTimeToSeconds(august2019); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); PackCrlIntoFile(TEST_DATA_PREFIX "invalid_time_crl.pb", tbs_crl, crl_inter_der[0], crl_inter_key.get()); } // NOTE: Device's issuer revoked. { - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); AddRevokedPublicKeyHash(&tbs_crl, inter_cert.get()); PackCrlIntoFile(TEST_DATA_PREFIX "issuer_revoked_crl.pb", tbs_crl, crl_inter_der[0], crl_inter_key.get()); @@ -179,9 +167,8 @@ int CastMain() { // NOTE: Device revoked. { - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); AddRevokedPublicKeyHash(&tbs_crl, device_cert.get()); PackCrlIntoFile(TEST_DATA_PREFIX "device_revoked_crl.pb", tbs_crl, crl_inter_der[0], crl_inter_key.get()); @@ -189,11 +176,10 @@ int CastMain() { // NOTE: Issuer serial revoked. { - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); ErrorOr<uint64_t> maybe_serial = - openscreen::ParseDerUint64(inter_cert->cert_info->serialNumber); + ParseDerUint64(inter_cert->cert_info->serialNumber); OSP_DCHECK(maybe_serial); uint64_t serial = maybe_serial.value(); OSP_DCHECK_GE(serial, 10); @@ -205,11 +191,10 @@ int CastMain() { // NOTE: Device serial revoked. { - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); ErrorOr<uint64_t> maybe_serial = - openscreen::ParseDerUint64(device_cert->cert_info->serialNumber); + ParseDerUint64(device_cert->cert_info->serialNumber); OSP_DCHECK(maybe_serial); uint64_t serial = maybe_serial.value(); OSP_DCHECK_GE(serial, 10); @@ -221,18 +206,16 @@ int CastMain() { // NOTE: Bad |signer_cert| used for Crl (not issued by Cast CRL root). { - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); PackCrlIntoFile(TEST_DATA_PREFIX "bad_signer_cert_crl.pb", tbs_crl, inter_der, inter_key.get()); } // NOTE: Mismatched key for signature in Crl (just looks like bad signature). { - certificate::TbsCrl tbs_crl = - MakeTbsCrl(not_before.count(), not_after.count(), device_cert.get(), - inter_cert.get()); + TbsCrl tbs_crl = MakeTbsCrl(not_before.count(), not_after.count(), + device_cert.get(), inter_cert.get()); PackCrlIntoFile(TEST_DATA_PREFIX "bad_signature_crl.pb", tbs_crl, crl_inter_der[0], inter_key.get()); } @@ -242,7 +225,8 @@ int CastMain() { } // namespace } // namespace cast +} // namespace openscreen int main() { - return cast::CastMain(); + return openscreen::cast::CastMain(); } |