From 3c3da01d58052da6b028324c26094e28fb9d4ab0 Mon Sep 17 00:00:00 2001 From: Edwin Date: Thu, 30 Dec 2021 11:39:14 -0800 Subject: [PATCH] Use aidl interface for Widevine service. The interface is defined in hardware/interfaces/drm/aidl(http://go/ag/15329852). Test: build m android.hardware.drm-service.widevine -j128 Test: build_and_run_all_unit_tests.sh for hidl tests Test: atest VtsAidlHalDrmTargetTest Test: atest vts_treble_vintf_vendor_test:vts_treble_vintf_vendor_test.DeviceManifest/SingleManifestTest#ManifestAidlHalsServed/0 -- --abi x86_64 Bug: 200055138 Bug: 170964303 Change-Id: I5654d90d8a4b0bae4b4a78e79b27c1cafec36be7 --- libwvdrmengine/Android.bp | 150 +- libwvdrmengine/aidl_include/Utils.h | 50 + .../aidl_include/WVCreatePluginFactories.h | 26 + libwvdrmengine/aidl_include/WVCryptoFactory.h | 45 + libwvdrmengine/aidl_include/WVDrmFactory.h | 71 + libwvdrmengine/aidl_include/WVTypes.h | 23 + libwvdrmengine/aidl_include/mapErrors-inl.h | 443 ++++ libwvdrmengine/aidl_include/wv_metrics.h | 19 + .../aidl_src/WVCreatePluginFactories.cpp | 25 + libwvdrmengine/aidl_src/WVCryptoFactory.cpp | 65 + libwvdrmengine/aidl_src/WVDrmFactory.cpp | 289 +++ .../android.hardware.drm-service.widevine.rc | 11 + libwvdrmengine/aidl_src/service.cpp | 53 + libwvdrmengine/aidl_src/wv_metrics.cpp | 448 ++++ libwvdrmengine/cdm/core/include/cdm_engine.h | 10 +- .../include/cdm_engine_metrics_decorator.h | 13 +- libwvdrmengine/cdm/core/include/cdm_session.h | 4 +- .../core/include/certificate_provisioning.h | 6 +- .../cdm/core/include/crypto_session.h | 53 +- .../cdm/core/include/device_files.h | 4 +- .../cdm/core/include/oemcrypto_adapter.h | 48 +- .../cdm/core/include/usage_table_header.h | 4 +- .../cdm/core/include/wv_cdm_types.h | 4 +- libwvdrmengine/cdm/core/src/cdm_engine.cpp | 31 +- .../cdm/core/src/certificate_provisioning.cpp | 4 +- .../cdm/core/src/crypto_session.cpp | 76 +- .../core/src/oemcrypto_adapter_dynamic.cpp | 79 +- .../cdm/core/src/usage_table_header.cpp | 2 +- libwvdrmengine/cdm/core/src/wv_cdm_types.cpp | 3 +- .../cdm_engine_metrics_decorator_unittest.cpp | 4 +- .../cdm/core/test/cdm_engine_test.cpp | 2 +- .../cdm/core/test/cdm_session_unittest.cpp | 2 +- .../certificate_provisioning_unittest.cpp | 8 +- .../cdm/core/test/device_files_unittest.cpp | 2 +- libwvdrmengine/cdm/core/test/test_base.cpp | 2 +- .../core/test/usage_table_header_unittest.cpp | 38 +- .../include/wv_content_decryption_module.h | 12 +- .../cdm/metrics/include/metrics_collections.h | 2 +- .../cdm/metrics/src/attribute_handler.cpp | 5 +- .../metrics/test/counter_metric_unittest.cpp | 2 +- .../cdm/src/wv_content_decryption_module.cpp | 11 +- .../cdm/test/cdm_extended_duration_test.cpp | 7 +- libwvdrmengine/cdm/test/cdm_feature_test.cpp | 8 +- libwvdrmengine/cdm/test/coverage-test.mk | 2 +- libwvdrmengine/cdm/test/integration-test.mk | 2 +- .../cdm/test/request_license_test.cpp | 11 +- libwvdrmengine/cdm/test/unit-test.mk | 2 +- libwvdrmengine/cdm/util/include/log.h | 22 +- libwvdrmengine/cdm/util/src/log.cpp | 42 +- libwvdrmengine/include_hidl/TypeConvert.h | 78 +- libwvdrmengine/level3/arm/libl3oemcrypto.cpp | 20 +- .../level3/arm64/libl3oemcrypto.cpp | 20 +- .../level3/src/level3_file_system_android.cpp | 3 +- libwvdrmengine/level3/x86/libl3oemcrypto.cpp | 20 +- .../level3/x86_64/libl3oemcrypto.cpp | 20 +- ..._android.hardware.drm-service.widevine.xml | 23 + libwvdrmengine/mediacrypto/Android.bp | 45 +- .../mediacrypto/aidl_include/WVCryptoPlugin.h | 93 + .../mediacrypto/aidl_src/WVCryptoPlugin.cpp | 350 +++ libwvdrmengine/mediacrypto/test/Android.mk | 2 +- libwvdrmengine/mediadrm/Android.bp | 45 +- .../mediadrm/aidl_include/WVDrmPlugin.h | 465 ++++ .../aidl_include/WVGenericCryptoInterface.h | 94 + .../aidl_include/wv_metrics_adapter.h | 108 + .../mediadrm/aidl_src/WVDrmPlugin.cpp | 2163 +++++++++++++++++ .../aidl_src/WVGenericCryptoInterface.cpp | 50 + .../mediadrm/aidl_src/wv_metrics_adapter.cpp | 595 +++++ .../mediadrm/include_hidl/WVDrmPlugin.h | 342 ++- .../mediadrm/src_hidl/WVDrmPlugin.cpp | 621 +++-- libwvdrmengine/mediadrm/test/Android.mk | 2 +- .../mediadrm/test/WVDrmPlugin_test.cpp | 1136 ++++----- .../oemcrypto/include/OEMCryptoCENCCommon.h | 2 +- libwvdrmengine/oemcrypto/test/common.mk | 3 +- libwvdrmengine/src_hidl/WVDrmFactory.cpp | 4 +- libwvdrmengine/vts/vendor_module/Android.bp | 2 +- 75 files changed, 7071 insertions(+), 1480 deletions(-) create mode 100644 libwvdrmengine/aidl_include/Utils.h create mode 100644 libwvdrmengine/aidl_include/WVCreatePluginFactories.h create mode 100644 libwvdrmengine/aidl_include/WVCryptoFactory.h create mode 100644 libwvdrmengine/aidl_include/WVDrmFactory.h create mode 100644 libwvdrmengine/aidl_include/WVTypes.h create mode 100644 libwvdrmengine/aidl_include/mapErrors-inl.h create mode 100644 libwvdrmengine/aidl_include/wv_metrics.h create mode 100644 libwvdrmengine/aidl_src/WVCreatePluginFactories.cpp create mode 100644 libwvdrmengine/aidl_src/WVCryptoFactory.cpp create mode 100644 libwvdrmengine/aidl_src/WVDrmFactory.cpp create mode 100644 libwvdrmengine/aidl_src/android.hardware.drm-service.widevine.rc create mode 100644 libwvdrmengine/aidl_src/service.cpp create mode 100644 libwvdrmengine/aidl_src/wv_metrics.cpp create mode 100644 libwvdrmengine/manifest_android.hardware.drm-service.widevine.xml create mode 100644 libwvdrmengine/mediacrypto/aidl_include/WVCryptoPlugin.h create mode 100644 libwvdrmengine/mediacrypto/aidl_src/WVCryptoPlugin.cpp create mode 100644 libwvdrmengine/mediadrm/aidl_include/WVDrmPlugin.h create mode 100644 libwvdrmengine/mediadrm/aidl_include/WVGenericCryptoInterface.h create mode 100644 libwvdrmengine/mediadrm/aidl_include/wv_metrics_adapter.h create mode 100644 libwvdrmengine/mediadrm/aidl_src/WVDrmPlugin.cpp create mode 100644 libwvdrmengine/mediadrm/aidl_src/WVGenericCryptoInterface.cpp create mode 100644 libwvdrmengine/mediadrm/aidl_src/wv_metrics_adapter.cpp diff --git a/libwvdrmengine/Android.bp b/libwvdrmengine/Android.bp index 4435855b..10cbe49f 100644 --- a/libwvdrmengine/Android.bp +++ b/libwvdrmengine/Android.bp @@ -114,6 +114,29 @@ cc_defaults { ], } +cc_defaults { + name: "common_widevine_service-multilib-defaults-aidl", + owner: "widevine", + proprietary: true, + relative_install_path: "hw", + include_dirs: [ + "vendor/widevine/libwvdrmengine/aidl_include", + "vendor/widevine/libwvdrmengine/mediadrm/aidl_include", + "vendor/widevine/libwvdrmengine/oemcrypto/include", + ], + header_libs: ["libstagefright_foundation_headers"], + + shared_libs: [ + "android.hardware.drm-V1-ndk", + "libbase", + "libbinder_ndk", + "liblog", + "libhwbinder", + "libutils", + "libwvaidl", + ], +} + cc_defaults { name: "common_widevine_service-multilib-defaults", defaults: [ @@ -227,7 +250,26 @@ cc_binary { } // ---------------------------------------------------------------------------- -// Builds libcdm_utils.a +// Builds android.hardware.drm-service.widevine +// +cc_binary { + name: "android.hardware.drm-service.widevine", + defaults: [ + "common_widevine_service-multilib-first", + "common_widevine_service-multilib-defaults-aidl", + ], + + srcs: ["aidl_src/service.cpp"], + + shared_libs: ["libbinder"], + + init_rc: ["aidl_src/android.hardware.drm-service.widevine.rc"], + vintf_fragments: ["manifest_android.hardware.drm-service.widevine.xml"], + +} + +// ---------------------------------------------------------------------------- +// Builds libcdm_utils.a and libcdm_utils_hidl.a // cdm_util_src_files = [ @@ -244,6 +286,40 @@ cdm_util_src_files = [ "cdm/util/src/string_conversions.cpp", ] +cc_library_static { + + name: "libcdm_utils_hidl", + + proprietary: true, + + include_dirs: [ + "vendor/widevine/libwvdrmengine/cdm/core/include", + "vendor/widevine/libwvdrmengine/cdm/include", + "vendor/widevine/libwvdrmengine/cdm/util/include", + "vendor/widevine/libwvdrmengine/oemcrypto/include", + ], + + header_libs: [ + "libbase_headers", + "libutils_headers", + ], + + shared_libs: [ + "libbinder", + "libcrypto", + "libhidlbase", + "liblog", + ], + + cflags: [ + "-DCORE_UTIL_IMPLEMENTATION", + "-DIS_HIDL", + ], + + srcs: cdm_util_src_files, + +} + cc_library_static { name: "libcdm_utils", @@ -263,9 +339,10 @@ cc_library_static { ], shared_libs: [ - "liblog", + "libbinder", "libcrypto", "libhidlbase", + "liblog", ], cflags: ["-DCORE_UTIL_IMPLEMENTATION"], @@ -297,7 +374,7 @@ cc_library_shared { "vendor/widevine/libwvdrmengine/cdm/util/include", "vendor/widevine/libwvdrmengine/cdm/include", "vendor/widevine/libwvdrmengine/include", - "vendor/widevine/libwvdrmengine/include_hidl", + "vendor/widevine/libwvdrmengine/include_hidl", "vendor/widevine/libwvdrmengine/mediacrypto/include_hidl", "vendor/widevine/libwvdrmengine/mediadrm/include_hidl", "vendor/widevine/libwvdrmengine/oemcrypto/include", @@ -306,7 +383,7 @@ cc_library_shared { static_libs: [ "libcdm", "libcdm_protos", - "libcdm_utils", + "libcdm_utils_hidl", "libjsmn", "libwvdrmcryptoplugin_hidl", "libwvdrmdrmplugin_hidl", @@ -380,9 +457,72 @@ cc_prebuilt_library_shared { } +// ---------------------------------------------------------------------------- +// Builds libwvaidl.so +// +cc_library_shared { + name: "libwvaidl", + + srcs: [ + "src/WVCDMSingleton.cpp", + "src/WVUUID.cpp", + "aidl_src/wv_metrics.cpp", + "aidl_src/WVCreatePluginFactories.cpp", + "aidl_src/WVCryptoFactory.cpp", + "aidl_src/WVDrmFactory.cpp", + ], + + include_dirs: [ + "frameworks/av/include", + "frameworks/native/include", + "vendor/widevine/libwvdrmengine/cdm/core/include", + "vendor/widevine/libwvdrmengine/cdm/metrics/include", + "vendor/widevine/libwvdrmengine/cdm/util/include", + "vendor/widevine/libwvdrmengine/cdm/include", + "vendor/widevine/libwvdrmengine/aidl_include", + "vendor/widevine/libwvdrmengine/include", + "vendor/widevine/libwvdrmengine/mediacrypto/aidl_include", + "vendor/widevine/libwvdrmengine/mediadrm/aidl_include", + "vendor/widevine/libwvdrmengine/oemcrypto/include", + ], + + static_libs: [ + "android.hardware.common-V2-ndk", + "libaidlcommonsupport", + "libcdm", + "libcdm_protos", + "libcdm_utils", + "libjsmn", + "libwvdrmcryptoplugin_aidl", + "libwvdrmdrmplugin_aidl", + "libwvlevel3", + "libwv_odk", + ], + + shared_libs: [ + "android.hardware.drm-V1-ndk", + "libbase", + "libbinder", + "libbinder_ndk", + "libcrypto", + "libcutils", + "libdl", + "liblog", + "libprotobuf-cpp-lite", + "libutils", + ], + + header_libs: ["libstagefright_foundation_headers"], + + owner: "widevine", + + proprietary: true, + +} + phony { name: "android.hardware.drm@latest-service.widevine", required: [ "android.hardware.drm@1.4-service.widevine", ], -} \ No newline at end of file +} diff --git a/libwvdrmengine/aidl_include/Utils.h b/libwvdrmengine/aidl_include/Utils.h new file mode 100644 index 00000000..4479386b --- /dev/null +++ b/libwvdrmengine/aidl_include/Utils.h @@ -0,0 +1,50 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_UTILS_H_ +#define WV_UTILS_H_ + +#include +#include + +#include +#include + +#include "log.h" + +namespace wvdrm { + +inline ::aidl::android::hardware::drm::LogPriority toAidlLogPriority( + wvutil::LogPriority p) { + switch (p) { + case wvutil::LogPriority::CDM_LOG_ERROR: + return ::aidl::android::hardware::drm::LogPriority::ERROR; + case wvutil::LogPriority::CDM_LOG_WARN: + return ::aidl::android::hardware::drm::LogPriority::WARN; + case wvutil::LogPriority::CDM_LOG_INFO: + return ::aidl::android::hardware::drm::LogPriority::INFO; + case wvutil::LogPriority::CDM_LOG_DEBUG: + return ::aidl::android::hardware::drm::LogPriority::DEBUG; + case wvutil::LogPriority::CDM_LOG_VERBOSE: + return ::aidl::android::hardware::drm::LogPriority::VERBOSE; + default: + return ::aidl::android::hardware::drm::LogPriority::UNKNOWN; + } +} + +inline ::ndk::ScopedAStatus toNdkScopedAStatus( + ::aidl::android::hardware::drm::Status status) { + if (::aidl::android::hardware::drm::Status::OK == status) + return ::ndk::ScopedAStatus::ok(); + else { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(status)); + } +} + +} // namespace wvdrm + +#endif // WV_UTILS_H_ diff --git a/libwvdrmengine/aidl_include/WVCreatePluginFactories.h b/libwvdrmengine/aidl_include/WVCreatePluginFactories.h new file mode 100644 index 00000000..26b1fcc9 --- /dev/null +++ b/libwvdrmengine/aidl_include/WVCreatePluginFactories.h @@ -0,0 +1,26 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_CREATE_PLUGIN_FACTORIES_H_ +#define WV_CREATE_PLUGIN_FACTORIES_H_ + +#include "WVCryptoFactory.h" +#include "WVDrmFactory.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +std::shared_ptr createDrmFactory(); +std::shared_ptr createCryptoFactory(); + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm + +#endif // WV_CREATE_PLUGIN_FACTORIES_H_ diff --git a/libwvdrmengine/aidl_include/WVCryptoFactory.h b/libwvdrmengine/aidl_include/WVCryptoFactory.h new file mode 100644 index 00000000..1e895ff6 --- /dev/null +++ b/libwvdrmengine/aidl_include/WVCryptoFactory.h @@ -0,0 +1,45 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_CRYPTO_FACTORY_H_ +#define WV_CRYPTO_FACTORY_H_ + +#include +#include +#include + +#include "WVTypes.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +struct WVCryptoFactory : public ::aidl::android::hardware::drm::BnCryptoFactory { + public: + WVCryptoFactory() {} + virtual ~WVCryptoFactory() {} + + ::ndk::ScopedAStatus createPlugin( + const ::aidl::android::hardware::drm::Uuid& in_uuid, + const std::vector& in_initData, + std::shared_ptr<::aidl::android::hardware::drm::ICryptoPlugin>* + _aidl_return) override; + + ::ndk::ScopedAStatus isCryptoSchemeSupported( + const ::aidl::android::hardware::drm::Uuid& in_uuid, + bool* _aidl_return) override; + + private: + WVDRM_DISALLOW_COPY_AND_ASSIGN(WVCryptoFactory); +}; + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm + +#endif // WV_CRYPTO_FACTORY_H_ diff --git a/libwvdrmengine/aidl_include/WVDrmFactory.h b/libwvdrmengine/aidl_include/WVDrmFactory.h new file mode 100644 index 00000000..f136fa3d --- /dev/null +++ b/libwvdrmengine/aidl_include/WVDrmFactory.h @@ -0,0 +1,71 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_DRM_FACTORY_H_ +#define WV_DRM_FACTORY_H_ + +#include +#include +#include + +#include "WVGenericCryptoInterface.h" +#include "WVTypes.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +struct WVDrmFactory : public ::aidl::android::hardware::drm::BnDrmFactory { + WVDrmFactory() {} + virtual ~WVDrmFactory() {} + + ::ndk::ScopedAStatus createPlugin( + const ::aidl::android::hardware::drm::Uuid& in_uuid, + const std::string& in_appPackageName, + std::shared_ptr<::aidl::android::hardware::drm::IDrmPlugin>* _aidl_return) + override; + + ::ndk::ScopedAStatus getSupportedCryptoSchemes( + std::vector<::aidl::android::hardware::drm::Uuid>* _aidl_return) override; + + ::ndk::ScopedAStatus isContentTypeSupported(const std::string& in_mimeType, + bool* _aidl_return) override; + + // This overloaded method is not part of the AIDL interface, it is provided + // for Widevine CDM. + bool isCryptoSchemeSupported( + const ::aidl::android::hardware::drm::Uuid& in_uuid); + + ::ndk::ScopedAStatus isCryptoSchemeSupported( + const ::aidl::android::hardware::drm::Uuid& in_uuid, + const std::string& in_mimeType, + ::aidl::android::hardware::drm::SecurityLevel in_securityLevel, + bool* _aidl_return) override; + + binder_status_t dump(int fd, const char** args, uint32_t numArgs) override; + + private: + WVDRM_DISALLOW_COPY_AND_ASSIGN(WVDrmFactory); + + static WVGenericCryptoInterface sOemCryptoInterface; + + static bool areSpoidsEnabled(); + static bool isBlankAppPackageNameAllowed(); + static int32_t firstApiLevel(); + static std::string stringToHex(const std::string& input); + static void printCdmMetrics(int fd); + static void printCdmProperties(int fd); + + friend class WVDrmFactoryTestPeer; +}; + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm + +#endif // WV_DRM_FACTORY_H_ diff --git a/libwvdrmengine/aidl_include/WVTypes.h b/libwvdrmengine/aidl_include/WVTypes.h new file mode 100644 index 00000000..3c81778c --- /dev/null +++ b/libwvdrmengine/aidl_include/WVTypes.h @@ -0,0 +1,23 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_TYPES_H_ +#define WV_TYPES_H_ + +namespace wvdrm { + +#define WVDRM_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ + void operator=(const TypeName&) = delete; + +#define WVDRM_DISALLOW_COPY_AND_ASSIGN_AND_NEW(TypeName) \ + TypeName() = delete; \ + TypeName(const TypeName&) = delete; \ + void operator=(const TypeName&) = delete; + +} // namespace wvdrm + +#endif // WV_TYPES_H_ diff --git a/libwvdrmengine/aidl_include/mapErrors-inl.h b/libwvdrmengine/aidl_include/mapErrors-inl.h new file mode 100644 index 00000000..045566e8 --- /dev/null +++ b/libwvdrmengine/aidl_include/mapErrors-inl.h @@ -0,0 +1,443 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_MAP_ERRORS_INL_H_ +#define WV_MAP_ERRORS_INL_H_ + +#include "WVErrors.h" +#include "media/stagefright/MediaErrors.h" +#include "utils/Errors.h" +#include "wv_cdm_types.h" + +namespace wvdrm { + +using ::aidl::android::hardware::drm::Status; + +template +static S mapCdmResponseType(wvcdm::CdmResponseType res) { + Status err = Status::ERROR_DRM_UNKNOWN; + switch (res) { + case wvcdm::KEY_ADDED: + case wvcdm::KEY_MESSAGE: + case wvcdm::KEY_CANCELED: + // KEY_ADDED, KEY_MESSAGE, and KEY_CANCELLED are all alternative + // success messages for certain CDM methods instead of NO_ERROR. + case wvcdm::NO_ERROR: + err = Status::OK; + break; + + case wvcdm::DECRYPT_NOT_READY: + case wvcdm::KEY_NOT_FOUND_IN_SESSION: + case wvcdm::NEED_KEY: + case wvcdm::NO_MATCHING_ENTITLEMENT_KEY: + // TODO(http://b/119690361): there are several NO_CONTENT_* errors. + // that should probably all turn into NO_LICENSE. Here, and below, and + // everywhere. + case wvcdm::NO_CONTENT_KEY_3: + return Status::ERROR_DRM_NO_LICENSE; + + case wvcdm::NEED_PROVISIONING: + return Status::ERROR_DRM_NOT_PROVISIONED; + + case wvcdm::DEVICE_REVOKED: + return Status::ERROR_DRM_DEVICE_REVOKED; + + case wvcdm::INSUFFICIENT_CRYPTO_RESOURCES: + return Status::ERROR_DRM_RESOURCE_BUSY; + + case wvcdm::RELEASE_USAGE_INFO_ERROR: + case wvcdm::RELEASE_USAGE_INFO_FAILED: + case wvcdm::SYSTEM_INVALIDATED_ERROR: + return Status::ERROR_DRM_INVALID_STATE; + + case wvcdm::SESSION_NOT_FOUND_FOR_DECRYPT: + case wvcdm::SESSION_NOT_FOUND_1: + case wvcdm::SESSION_NOT_FOUND_2: + case wvcdm::SESSION_NOT_FOUND_3: + case wvcdm::SESSION_NOT_FOUND_4: + case wvcdm::SESSION_NOT_FOUND_5: + case wvcdm::SESSION_NOT_FOUND_6: + case wvcdm::SESSION_NOT_FOUND_7: + case wvcdm::SESSION_NOT_FOUND_8: + case wvcdm::SESSION_NOT_FOUND_9: + case wvcdm::SESSION_NOT_FOUND_10: + case wvcdm::SESSION_NOT_FOUND_18: + case wvcdm::SESSION_NOT_FOUND_19: + case wvcdm::SESSION_NOT_FOUND_20: + case wvcdm::SESSION_NOT_FOUND_21: + case wvcdm::SESSION_NOT_FOUND_22: + case wvcdm::SESSION_NOT_FOUND_23: + return Status::ERROR_DRM_SESSION_NOT_OPENED; + + case wvcdm::DECRYPT_ERROR: + case wvcdm::SECURE_BUFFER_REQUIRED: + return Status::ERROR_DRM_CANNOT_HANDLE; + + case wvcdm::ANALOG_OUTPUT_ERROR: + case wvcdm::INSUFFICIENT_OUTPUT_PROTECTION: + return Status::ERROR_DRM_INSUFFICIENT_OUTPUT_PROTECTION; + + case wvcdm::KEYSET_ID_NOT_FOUND_4: + return Status::BAD_VALUE; + + // The following cases follow the order in wv_cdm_types.h + // to make it easier to keep track of newly defined errors. + case wvcdm::CERT_PROVISIONING_GET_KEYBOX_ERROR_1: + case wvcdm::INVALID_DECRYPT_PARAMETERS_ENG_1: + case wvcdm::INVALID_DECRYPT_PARAMETERS_ENG_3: + case wvcdm::INVALID_DEVICE_CERTIFICATE_TYPE: + case wvcdm::REMOVE_ALL_USAGE_INFO_ERROR_1: + case wvcdm::REMOVE_ALL_USAGE_INFO_ERROR_2: + case wvcdm::UNPROVISION_ERROR_4: + case wvcdm::PARSE_SERVICE_CERTIFICATE_ERROR: + case wvcdm::CLIENT_ID_RSA_INIT_ERROR: + case wvcdm::INCORRECT_CRYPTO_MODE: + case wvcdm::INVALID_PARAMETERS_ENG_5: + case wvcdm::COPY_OLD_USAGE_ENTRY_UNKNOWN_ERROR: + case wvcdm::UNEXPECTED_EMPTY_USAGE_ENTRY: + case wvcdm::INVALID_USAGE_ENTRY_NUMBER_MODIFICATION: + case wvcdm::REMOVE_ALL_USAGE_INFO_ERROR_6: + case wvcdm::REMOVE_ALL_USAGE_INFO_ERROR_7: + case wvcdm::DELETE_USAGE_ERROR_3: + case wvcdm::LOAD_SYSTEM_ID_ERROR: + case wvcdm::RSA_SIGNATURE_GENERATION_ERROR: + case wvcdm::REWRAP_DEVICE_RSA_KEY_ERROR: + case wvcdm::PARSE_OKP_RESPONSE_ERROR: + case wvcdm::OKP_ALREADY_PROVISIONED: + ALOGW("Returns UNKNOWN error for legacy status: %d", res); + return Status::ERROR_DRM_UNKNOWN; + + case wvcdm::KEY_PROHIBITED_FOR_SECURITY_LEVEL: + return Status::ERROR_DRM_INSUFFICIENT_SECURITY; + case wvcdm::OUTPUT_TOO_LARGE_ERROR: + return Status::ERROR_DRM_FRAME_TOO_LARGE; + case wvcdm::SESSION_LOST_STATE_ERROR: + return Status::ERROR_DRM_SESSION_LOST_STATE; + case wvcdm::LICENSE_REQUEST_NONCE_GENERATION_ERROR: + case wvcdm::LICENSE_RENEWAL_NONCE_GENERATION_ERROR: + case wvcdm::CERT_PROVISIONING_NONCE_GENERATION_ERROR: + case wvcdm::NONCE_GENERATION_ERROR: + // These are likely nonce flood errors + return Status::ERROR_DRM_RESOURCE_CONTENTION; + + case wvcdm::CANNOT_DECRYPT_ZERO_SUBSAMPLES: + err = Status::CANNOT_DECRYPT_ZERO_SUBSAMPLES; + break; + case wvcdm::CLIENT_ID_AES_ENCRYPT_ERROR: + case wvcdm::CLIENT_ID_AES_INIT_ERROR: + case wvcdm::CLIENT_ID_RSA_ENCRYPT_ERROR: + err = Status::CRYPTO_LIBRARY_ERROR; + break; + case wvcdm::PROVISIONING_NOT_ALLOWED_FOR_ATSC: + err = Status::ERROR_DRM_CANNOT_HANDLE; + break; + case wvcdm::CERT_PROVISIONING_REQUEST_ERROR_4: + case wvcdm::CLIENT_IDENTIFICATION_TOKEN_ERROR_1: + case wvcdm::CREATE_USAGE_ENTRY_UNKNOWN_ERROR: + case wvcdm::CREATE_USAGE_TABLE_ERROR: + case wvcdm::DEACTIVATE_USAGE_ENTRY_ERROR: + case wvcdm::EMPTY_LICENSE_RENEWAL: + case wvcdm::EXTRACT_SYSTEM_ID_FROM_OEM_CERT_ERROR: + case wvcdm::GENERATE_DERIVED_KEYS_ERROR: + case wvcdm::GENERATE_DERIVED_KEYS_ERROR_2: + case wvcdm::GENERATE_SIGNATURE_ERROR: + case wvcdm::GENERATE_USAGE_REPORT_ERROR: + case wvcdm::GET_DECRYPT_HASH_ERROR: + case wvcdm::GET_DEVICE_ID_ERROR: + case wvcdm::GET_HDCP_CAPABILITY_FAILED: + case wvcdm::GET_MAX_NUMBER_OF_OPEN_SESSIONS_ERROR: + case wvcdm::GET_NUMBER_OF_OPEN_SESSIONS_ERROR: + case wvcdm::GET_PROVISIONING_METHOD_ERROR: + case wvcdm::GET_SRM_VERSION_ERROR: + case wvcdm::GET_TOKEN_FROM_KEYBOX_ERROR: + case wvcdm::GET_TOKEN_FROM_OEM_CERT_ERROR: + case wvcdm::INVALID_DECRYPT_HASH_FORMAT: + case wvcdm::INVALID_SESSION_1: + case wvcdm::INVALID_SESSION_2: + case wvcdm::KEYBOX_TOKEN_TOO_SHORT: + case wvcdm::LOAD_USAGE_ENTRY_UNKNOWN_ERROR: + case wvcdm::LOAD_USAGE_HEADER_UNKNOWN_ERROR: + case wvcdm::MOVE_USAGE_ENTRY_UNKNOWN_ERROR: + case wvcdm::OPEN_CRYPTO_SESSION_ERROR: + case wvcdm::RANDOM_GENERATION_ERROR: + case wvcdm::SET_DECRYPT_HASH_ERROR: + case wvcdm::SHRINK_USAGE_TABLE_HEADER_UNKNOWN_ERROR: + case wvcdm::UNKNOWN_CLIENT_TOKEN_TYPE: + case wvcdm::UNKNOWN_SELECT_KEY_ERROR_1: + case wvcdm::UNKNOWN_SELECT_KEY_ERROR_2: + case wvcdm::UPDATE_USAGE_ENTRY_UNKNOWN_ERROR: + case wvcdm::USAGE_SUPPORT_GET_API_FAILED: + err = Status::GENERAL_OEM_ERROR; + break; + case wvcdm::CANNOT_DECRYPT_ZERO_SAMPLES: + case wvcdm::CERT_PROVISIONING_REQUEST_ERROR_1: + case wvcdm::CRYPTO_SESSION_NOT_INITIALIZED: + case wvcdm::CRYPTO_SESSION_NOT_OPEN: + case wvcdm::DEVICE_CANNOT_REPROVISION: + case wvcdm::DEVICE_CERTIFICATE_ERROR_1: + case wvcdm::DUPLICATE_SESSION_ID_SPECIFIED: + case wvcdm::EMPTY_KEYSET_ID_ENG_5: + case wvcdm::EMPTY_RESPONSE_ERROR_1: + case wvcdm::EMPTY_SESSION_ID: + case wvcdm::INCORRECT_USAGE_SUPPORT_TYPE_1: + case wvcdm::INCORRECT_USAGE_SUPPORT_TYPE_2: + case wvcdm::INVALID_IV_SIZE: + case wvcdm::INVALID_KEY_SYSTEM: + case wvcdm::INVALID_PARAMETERS_ENG_22: + case wvcdm::INVALID_PARAMETERS_ENG_23: + case wvcdm::INVALID_PARAMETERS_ENG_24: + case wvcdm::INVALID_PARAMETERS_LIC_1: + case wvcdm::INVALID_PARAMETERS_LIC_2: + case wvcdm::INVALID_PARAMETERS_LIC_6: + case wvcdm::INVALID_PARAMETERS_LIC_7: + case wvcdm::INVALID_PROVISIONING_PARAMETERS_1: + case wvcdm::INVALID_PROVISIONING_PARAMETERS_2: + case wvcdm::INVALID_PROVISIONING_REQUEST_PARAM_1: + case wvcdm::INVALID_PROVISIONING_REQUEST_PARAM_2: + case wvcdm::INVALID_SESSION_ID: + case wvcdm::KEYSET_ID_NOT_FOUND_1: + case wvcdm::KEYSET_ID_NOT_FOUND_2: + case wvcdm::KEYSET_ID_NOT_FOUND_3: + case wvcdm::KEY_CONFLICT_1: + case wvcdm::KEY_NOT_FOUND_2: + case wvcdm::KEY_REQUEST_ERROR_1: + case wvcdm::LICENSE_PARSER_NOT_INITIALIZED_1: + case wvcdm::LICENSE_PARSER_NOT_INITIALIZED_2: + case wvcdm::LICENSE_PARSER_NOT_INITIALIZED_3: + case wvcdm::LICENSE_PARSER_NOT_INITIALIZED_4: + case wvcdm::LICENSE_REQUEST_SERVICE_CERTIFICATE_GENERATION_ERROR: + case wvcdm::LICENSE_USAGE_ENTRY_MISSING: + case wvcdm::LOAD_ENTITLED_CONTENT_KEYS_ERROR: + case wvcdm::LOAD_USAGE_ENTRY_GENERATION_SKEW: + case wvcdm::LOAD_USAGE_ENTRY_INVALID_SESSION: + case wvcdm::LOAD_USAGE_ENTRY_SIGNATURE_FAILURE: + case wvcdm::LOAD_USAGE_HEADER_BAD_MAGIC: + case wvcdm::LOAD_USAGE_HEADER_GENERATION_SKEW: + case wvcdm::LOAD_USAGE_HEADER_SIGNATURE_FAILURE: + case wvcdm::LOAD_USAGE_INFO_MISSING: + case wvcdm::MOVE_USAGE_ENTRY_DESTINATION_IN_USE: + case wvcdm::NOT_IMPLEMENTED_ERROR: + case wvcdm::NOT_INITIALIZED_ERROR: + case wvcdm::NO_SRM_VERSION: + case wvcdm::NO_USAGE_ENTRIES: + case wvcdm::PARAMETER_NULL: + case wvcdm::PREPARE_CENC_CONTENT_ID_FAILED: + case wvcdm::PREPARE_WEBM_CONTENT_ID_FAILED: + case wvcdm::REINIT_ERROR: + case wvcdm::REMOVE_OFFLINE_LICENSE_ERROR_2: + case wvcdm::REMOVE_USAGE_INFO_ERROR_3: + case wvcdm::SESSION_NOT_FOUND_11: + case wvcdm::SESSION_NOT_FOUND_12: + case wvcdm::SESSION_NOT_FOUND_13: + case wvcdm::SESSION_NOT_FOUND_14: + case wvcdm::SESSION_NOT_FOUND_15: + case wvcdm::SESSION_NOT_FOUND_16: + case wvcdm::SHRINK_USAGE_TABLE_HEADER_ENTRY_IN_USE: + case wvcdm::STORAGE_PROHIBITED: + case wvcdm::STORE_LICENSE_ERROR_2: + case wvcdm::USAGE_ENTRY_NUMBER_MISMATCH: + case wvcdm::USAGE_GET_ENTRY_RETRIEVE_INVALID_STORAGE_TYPE: + case wvcdm::USAGE_INFORMATION_SUPPORT_FAILED: + case wvcdm::USAGE_INVALID_LOAD_ENTRY: + case wvcdm::USAGE_INVALID_NEW_ENTRY: + case wvcdm::USAGE_INVALID_PARAMETERS_1: + case wvcdm::USAGE_INVALID_PARAMETERS_2: + case wvcdm::USAGE_STORE_ENTRY_RETRIEVE_INVALID_STORAGE_TYPE: + case wvcdm::CLIENT_TOKEN_NOT_SET: + err = Status::GENERAL_PLUGIN_ERROR; + break; + case wvcdm::CLIENT_ID_GENERATE_RANDOM_ERROR: + err = Status::ERROR_DRM_RESOURCE_CONTENTION; + break; + case wvcdm::CENC_INIT_DATA_UNAVAILABLE: + case wvcdm::INIT_DATA_NOT_FOUND: + case wvcdm::INVALID_PARAMETERS_LIC_3: + case wvcdm::INVALID_PARAMETERS_LIC_4: + case wvcdm::UNSUPPORTED_INIT_DATA: + case wvcdm::UNSUPPORTED_INIT_DATA_FORMAT: + case wvcdm::WEBM_INIT_DATA_UNAVAILABLE: + err = Status::INIT_DATA_INVALID; + break; + case wvcdm::EMPTY_KEYSET_ID: + case wvcdm::EMPTY_KEYSET_ID_ENG_1: + case wvcdm::EMPTY_KEYSET_ID_ENG_2: + case wvcdm::EMPTY_KEYSET_ID_ENG_3: + case wvcdm::EMPTY_KEYSET_ID_ENG_4: + case wvcdm::EMPTY_LICENSE_RESPONSE_1: + case wvcdm::EMPTY_LICENSE_RESPONSE_2: + case wvcdm::EMPTY_PROVISIONING_RESPONSE: + case wvcdm::INVALID_PARAMETERS_ENG_13: + case wvcdm::INVALID_PARAMETERS_ENG_14: + case wvcdm::INVALID_PARAMETERS_ENG_15: + case wvcdm::INVALID_PARAMETERS_ENG_16: + case wvcdm::INVALID_QUERY_KEY: + case wvcdm::KEY_NOT_FOUND_1: + case wvcdm::SAMPLE_AND_SUBSAMPLE_SIZE_MISMATCH: + err = Status::BAD_VALUE; + break; + case wvcdm::KEY_NOT_FOUND_3: + case wvcdm::KEY_NOT_FOUND_4: + case wvcdm::KEY_NOT_FOUND_5: + case wvcdm::KEY_NOT_FOUND_6: + err = Status::KEY_NOT_LOADED; + break; + case wvcdm::ADD_KEY_ERROR: + case wvcdm::CORE_MESSAGE_NOT_FOUND: + case wvcdm::EMPTY_KEY_DATA_1: + case wvcdm::EMPTY_KEY_DATA_2: + case wvcdm::INVALID_LICENSE_RESPONSE: + case wvcdm::INVALID_LICENSE_TYPE: + case wvcdm::INVALID_SRM_LIST: + case wvcdm::KEY_SIZE_ERROR_1: + case wvcdm::KEY_SIZE_ERROR_2: + case wvcdm::LICENSE_ID_NOT_FOUND: + case wvcdm::LICENSE_RESPONSE_NOT_SIGNED: + case wvcdm::LICENSE_RESPONSE_PARSE_ERROR_1: + case wvcdm::LICENSE_RESPONSE_PARSE_ERROR_2: + case wvcdm::LICENSE_RESPONSE_PARSE_ERROR_3: + case wvcdm::LICENSE_RESPONSE_PARSE_ERROR_4: + case wvcdm::LICENSE_RESPONSE_PARSE_ERROR_5: + case wvcdm::LOAD_KEY_ERROR: + case wvcdm::LOAD_LICENSE_ERROR: + case wvcdm::LOAD_RENEWAL_ERROR: + case wvcdm::LOAD_SRM_ERROR: + case wvcdm::NOT_AN_ENTITLEMENT_SESSION: + case wvcdm::NO_CONTENT_KEY: + case wvcdm::NO_CONTENT_KEY_2: + case wvcdm::NO_DEVICE_KEY_1: + case wvcdm::REFRESH_KEYS_ERROR: + case wvcdm::SESSION_KEYS_NOT_FOUND: + case wvcdm::SIGNATURE_NOT_FOUND: + err = Status::LICENSE_PARSE_ERROR; + break; + case wvcdm::LICENSE_RENEWAL_PROHIBITED: + case wvcdm::OFFLINE_LICENSE_PROHIBITED: + err = Status::LICENSE_POLICY_ERROR; + break; + case wvcdm::PARSE_REQUEST_ERROR_2: + case wvcdm::RELEASE_LICENSE_ERROR_1: + case wvcdm::SESSION_KEYS_NOT_FOUND_2: + err = Status::LICENSE_RELEASE_ERROR; + break; + case wvcdm::KEY_ERROR: + case wvcdm::RELEASE_KEY_ERROR: + case wvcdm::RENEW_KEY_ERROR_1: + err = Status::LICENSE_REQUEST_REJECTED; + break; + case wvcdm::EMPTY_LICENSE_REQUEST_2: + case wvcdm::EMPTY_LICENSE_REQUEST_3: + case wvcdm::EMPTY_LICENSE_RESPONSE_3: + case wvcdm::EMPTY_LICENSE_RESPONSE_4: + case wvcdm::INVALID_LICENSE_REQUEST_TYPE_1: + case wvcdm::INVALID_LICENSE_REQUEST_TYPE_2: + case wvcdm::INVALID_LICENSE_TYPE_2: + case wvcdm::PARSE_REQUEST_ERROR_1: + case wvcdm::RESTORE_OFFLINE_LICENSE_ERROR_2: + case wvcdm::SIGNATURE_NOT_FOUND_2: + err = Status::LICENSE_RESTORE_ERROR; + break; + case wvcdm::GET_RELEASED_LICENSE_ERROR: + case wvcdm::RESTORE_OFFLINE_LICENSE_ERROR_3: + case wvcdm::USAGE_ENTRY_ALREADY_LOADED: + err = Status::LICENSE_STATE_ERROR; + break; + case wvcdm::DEVICE_CERTIFICATE_ERROR_2: + case wvcdm::DEVICE_CERTIFICATE_ERROR_3: + case wvcdm::DEVICE_CERTIFICATE_ERROR_4: + case wvcdm::LICENSE_PARSER_INIT_ERROR: + case wvcdm::PARSE_RESPONSE_ERROR_1: + case wvcdm::PARSE_RESPONSE_ERROR_2: + case wvcdm::PARSE_RESPONSE_ERROR_3: + case wvcdm::PARSE_RESPONSE_ERROR_4: + err = Status::MALFORMED_CERTIFICATE; + break; + case wvcdm::INVALID_DECRYPT_PARAMETERS_ENG_2: + case wvcdm::INVALID_DECRYPT_PARAMETERS_ENG_4: + err = Status::MEDIA_FRAMEWORK_ERROR; + break; + case wvcdm::PRIVACY_MODE_ERROR_1: + case wvcdm::PRIVACY_MODE_ERROR_2: + case wvcdm::PRIVACY_MODE_ERROR_3: + err = Status::MISSING_CERTIFICATE; + break; + case wvcdm::LOAD_DEVICE_RSA_KEY_ERROR: + err = Status::PROVISIONING_CERTIFICATE_ERROR; + break; + case wvcdm::CERT_PROVISIONING_EMPTY_SERVICE_CERTIFICATE: + case wvcdm::SERVICE_CERTIFICATE_PROVIDER_ID_EMPTY: + err = Status::PROVISIONING_CONFIGURATION_ERROR; + break; + case wvcdm::CERT_PROVISIONING_INVALID_CERT_TYPE: + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_1: + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_2: + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_3: + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_4: + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_9: + case wvcdm::LOAD_PROVISIONING_ERROR: + err = Status::PROVISIONING_PARSE_ERROR; + break; + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_10: + err = Status::PROVISIONING_REQUEST_REJECTED; + break; + case wvcdm::EMPTY_PROVISIONING_CERTIFICATE_1: + case wvcdm::EMPTY_PROVISIONING_CERTIFICATE_2: + err = Status::RETRYABLE_PROVISIONING_ERROR; + break; + case wvcdm::RELEASE_LICENSE_ERROR_2: + err = Status::SECURE_STOP_RELEASE_ERROR; + break; + case wvcdm::GET_LICENSE_ERROR: + case wvcdm::GET_OFFLINE_LICENSE_STATE_ERROR_1: + case wvcdm::GET_OFFLINE_LICENSE_STATE_ERROR_2: + case wvcdm::GET_USAGE_INFO_ERROR_1: + case wvcdm::GET_USAGE_INFO_ERROR_2: + case wvcdm::GET_USAGE_INFO_ERROR_3: + case wvcdm::GET_USAGE_INFO_ERROR_4: + case wvcdm::LIST_LICENSE_ERROR_1: + case wvcdm::LIST_LICENSE_ERROR_2: + case wvcdm::LIST_USAGE_ERROR_1: + case wvcdm::LIST_USAGE_ERROR_2: + case wvcdm::LOAD_USAGE_INFO_FILE_ERROR: + case wvcdm::REMOVE_OFFLINE_LICENSE_ERROR_1: + case wvcdm::REMOVE_USAGE_INFO_ERROR_2: + case wvcdm::SESSION_FILE_HANDLE_INIT_ERROR: + case wvcdm::UNPROVISION_ERROR_1: + case wvcdm::USAGE_GET_ENTRY_RETRIEVE_LICENSE_FAILED: + case wvcdm::USAGE_GET_ENTRY_RETRIEVE_USAGE_INFO_FAILED: + case wvcdm::USAGE_INFO_NOT_FOUND: + case wvcdm::USAGE_STORE_ENTRY_RETRIEVE_LICENSE_FAILED: + case wvcdm::USAGE_STORE_ENTRY_RETRIEVE_USAGE_INFO_FAILED: + err = Status::STORAGE_READ_FAILURE; + break; + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_7: + case wvcdm::CERT_PROVISIONING_RESPONSE_ERROR_8: + case wvcdm::DELETE_USAGE_ERROR_1: + case wvcdm::DELETE_USAGE_ERROR_2: + case wvcdm::RELEASE_KEY_REQUEST_ERROR: + case wvcdm::REMOVE_ALL_USAGE_INFO_ERROR_5: + case wvcdm::REMOVE_USAGE_INFO_ERROR_1: + case wvcdm::RENEW_KEY_ERROR_2: + case wvcdm::STORE_LICENSE_ERROR_1: + case wvcdm::STORE_USAGE_INFO_ERROR: + case wvcdm::UNPROVISION_ERROR_2: + case wvcdm::UNPROVISION_ERROR_3: + case wvcdm::USAGE_STORE_LICENSE_FAILED: + case wvcdm::USAGE_STORE_USAGE_INFO_FAILED: + err = Status::STORAGE_WRITE_FAILURE; + break; + default: + return Status::ERROR_DRM_UNKNOWN; + } + return static_cast(err); +} + +static inline bool isCdmResponseTypeSuccess(wvcdm::CdmResponseType res) { + return mapCdmResponseType(res) == Status::OK; +} + +} // namespace wvdrm + +#endif // WV_MAP_ERRORS_INL_H_ diff --git a/libwvdrmengine/aidl_include/wv_metrics.h b/libwvdrmengine/aidl_include/wv_metrics.h new file mode 100644 index 00000000..6dfe7297 --- /dev/null +++ b/libwvdrmengine/aidl_include/wv_metrics.h @@ -0,0 +1,19 @@ +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// +// Format widevine protobuf metrics + +#ifndef WV_METRICS_H_ +#define WV_METRICS_H_ + +#include + +#include "wv_metrics.pb.h" + +namespace wv_metrics { +void FormatWvCdmMetrics(const drm_metrics::WvCdmMetrics& metrics, + std::string& result); +} + +#endif // WV_METRICS_H_ diff --git a/libwvdrmengine/aidl_src/WVCreatePluginFactories.cpp b/libwvdrmengine/aidl_src/WVCreatePluginFactories.cpp new file mode 100644 index 00000000..e27382ee --- /dev/null +++ b/libwvdrmengine/aidl_src/WVCreatePluginFactories.cpp @@ -0,0 +1,25 @@ +// +// Copyright 2022 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#include "WVCreatePluginFactories.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +std::shared_ptr createDrmFactory() { + return std::make_shared(); +} + +std::shared_ptr createCryptoFactory() { + return std::make_shared(); +} + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm diff --git a/libwvdrmengine/aidl_src/WVCryptoFactory.cpp b/libwvdrmengine/aidl_src/WVCryptoFactory.cpp new file mode 100644 index 00000000..905a04f9 --- /dev/null +++ b/libwvdrmengine/aidl_src/WVCryptoFactory.cpp @@ -0,0 +1,65 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +//#define LOG_NDEBUG 0 +#define LOG_TAG "WVCdm" +#include "WVCryptoFactory.h" + +#include +#include +#include + +#include "Utils.h" +#include "WVCDMSingleton.h" +#include "WVCryptoPlugin.h" +#include "WVUUID.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +using ::aidl::android::hardware::drm::Status; +using ::aidl::android::hardware::drm::Uuid; + +::ndk::ScopedAStatus WVCryptoFactory::isCryptoSchemeSupported( + const Uuid& in_uuid, bool* _aidl_return) { + *_aidl_return = isWidevineUUID(in_uuid.uuid.data()); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVCryptoFactory::createPlugin( + const ::aidl::android::hardware::drm::Uuid& in_uuid, + const std::vector& in_initData, + std::shared_ptr<::aidl::android::hardware::drm::ICryptoPlugin>* + _aidl_return) { + const auto& self = android::IPCThreadState::self(); + const char* sid = self->getCallingSid(); + sid = sid ? (std::strstr(sid, "mediadrmserver") ? sid : "app") : "nullptr"; + ALOGI("[%s] calling %s", sid, __PRETTY_FUNCTION__); + + bool isSupported = false; + isCryptoSchemeSupported(in_uuid, &isSupported); + if (!isSupported) { + ALOGE( + "Widevine Drm HAL: failed to create crypto plugin, " + "invalid crypto scheme"); + *_aidl_return = nullptr; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + std::shared_ptr plugin = + ::ndk::SharedRefBase::make(in_initData.data(), + in_initData.size(), getCDM()); + AIBinder_setRequestingSid(plugin->asBinder().get(), true); + *_aidl_return = std::move(plugin); + return toNdkScopedAStatus(Status::OK); +} + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm diff --git a/libwvdrmengine/aidl_src/WVDrmFactory.cpp b/libwvdrmengine/aidl_src/WVDrmFactory.cpp new file mode 100644 index 00000000..7e7c5f55 --- /dev/null +++ b/libwvdrmengine/aidl_src/WVDrmFactory.cpp @@ -0,0 +1,289 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +//#define LOG_NDEBUG 0 +#define LOG_TAG "WVCdm-DrmFactory" + +#include "WVDrmFactory.h" + +#include +#include +#include + +#include "Utils.h" +#include "WVCDMSingleton.h" +#include "WVDrmPlugin.h" +#include "WVUUID.h" +#include "android-base/properties.h" +#include "cutils/properties.h" +#include "wv_cdm_constants.h" +#include "wv_content_decryption_module.h" +#include "wv_metrics.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +using std::string; +using std::vector; + +using ::aidl::android::hardware::drm::SecurityLevel; +using ::aidl::android::hardware::drm::Status; +using ::aidl::android::hardware::drm::Uuid; + +WVGenericCryptoInterface WVDrmFactory::sOemCryptoInterface; + +bool WVDrmFactory::isCryptoSchemeSupported(const Uuid& in_uuid) { + return isWidevineUUID(in_uuid.uuid.data()); +} + +::ndk::ScopedAStatus WVDrmFactory::isCryptoSchemeSupported( + const Uuid& in_uuid, const string& in_mimeType, + SecurityLevel in_securityLevel, bool* _aidl_return) { + bool isMimeTypeSupported = false; + isContentTypeSupported(in_mimeType, &isMimeTypeSupported); + if (!isWidevineUUID(in_uuid.uuid.data()) || !isMimeTypeSupported) { + *_aidl_return = false; + return ::ndk::ScopedAStatus::ok(); + } + + if (wvcdm::WvContentDecryptionModule::IsSecurityLevelSupported( + wvcdm::kSecurityLevelL1)) { + if (wvcdm::WvContentDecryptionModule::IsAudio(in_mimeType)) { + if (in_securityLevel < SecurityLevel::HW_SECURE_ALL) { + *_aidl_return = true; + return ::ndk::ScopedAStatus::ok(); + } + } else { + *_aidl_return = true; + return ::ndk::ScopedAStatus::ok(); + } + } + *_aidl_return = in_securityLevel <= SecurityLevel::SW_SECURE_DECODE; + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVDrmFactory::isContentTypeSupported( + const string& in_mimeType, bool* _aidl_return) { + *_aidl_return = + wvcdm::WvContentDecryptionModule::IsSupported(in_mimeType.c_str()); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVDrmFactory::createPlugin( + const Uuid& in_uuid, const string& in_appPackageName, + std::shared_ptr<::aidl::android::hardware::drm::IDrmPlugin>* _aidl_return) { + const auto& self = ::android::IPCThreadState::self(); + const char* sid = self->getCallingSid(); + sid = sid ? (std::strstr(sid, "mediadrmserver") ? sid : "app") : "nullptr"; + ALOGI("[%s][%s] calling %s", sid, in_appPackageName.c_str(), + __PRETTY_FUNCTION__); + + if (!isCryptoSchemeSupported(in_uuid)) { + ALOGE( + "Widevine Drm HAL: failed to create drm plugin, " + "invalid crypto scheme"); + *_aidl_return = nullptr; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + if (!isBlankAppPackageNameAllowed() && in_appPackageName.empty()) { + ALOGE( + "Widevine Drm HAL: Failed to create DRM Plugin, blank App Package " + "Name disallowed."); + *_aidl_return = nullptr; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + std::shared_ptr plugin = ::ndk::SharedRefBase::make( + getCDM(), in_appPackageName.c_str(), &sOemCryptoInterface, + areSpoidsEnabled()); + + AIBinder_setRequestingSid(plugin->asBinder().get(), true); + *_aidl_return = plugin; + return toNdkScopedAStatus(Status::OK); +} + +bool WVDrmFactory::areSpoidsEnabled() { + return firstApiLevel() >= 26; // Android O +} + +bool WVDrmFactory::isBlankAppPackageNameAllowed() { + return firstApiLevel() < 29; // Android Q +} + +int32_t WVDrmFactory::firstApiLevel() { + // Check what this device's first API level was. + int32_t firstApiLevel = + android::base::GetIntProperty("ro.product.first_api_level", 0); + if (firstApiLevel == 0) { + // First API Level is 0 on factory ROMs, but we can assume the current SDK + // version is the first if it's a factory ROM. + firstApiLevel = + android::base::GetIntProperty("ro.build.version.sdk", 0); + } + return firstApiLevel; +} + +::ndk::ScopedAStatus WVDrmFactory::getSupportedCryptoSchemes( + vector* _aidl_return) { + vector schemes; + Uuid scheme; + for (const auto& uuid : wvdrm::getSupportedCryptoSchemes()) { + scheme.uuid.assign(uuid.begin(), uuid.end()); + schemes.push_back(scheme); + } + *_aidl_return = schemes; + return ::ndk::ScopedAStatus::ok(); +} + +string WVDrmFactory::stringToHex(const string& input) { + // If input contains punctuations that are not part of + // a valid server url, we need to convert it to hex. + const string validChars = "/-._~%:"; + bool toHex = false; + for (const char ch : input) { + if (ispunct(ch) != 0 && validChars.find(ch) == string::npos) { + toHex = true; + break; + } + } + if (!toHex) return input; + + static constexpr char hex[] = "0123456789ABCDEF"; + + string output; + output.reserve(input.length() * 2); + for (const unsigned char ch : input) { + output.push_back(hex[ch >> 4]); + output.push_back(hex[ch & 15]); + } + return output; +} + +void WVDrmFactory::printCdmMetrics(int fd) { + dprintf(fd, "\n**** Widevine Cdm Metrics ****\n"); + + // Verify that the version of the library that we linked against is + // compatible with the version of the headers we compiled against. + GOOGLE_PROTOBUF_VERIFY_VERSION; + + android::sp cdm(getCDM()); + + vector metrics; + bool full_list_returned = true; + wvcdm::CdmResponseType result = + cdm->GetMetrics(&metrics, &full_list_returned); + if (metrics.empty()) { + dprintf(fd, + "Metrics not available, please retry while streaming a video\n"); + } else if (!full_list_returned) { + dprintf(fd, + "Not all metrics are returned due to some GetMetric error, " + "please check logcat for possible GetMetric errors.\n"); + } + if (result == wvcdm::NO_ERROR) { + for (auto& metric : metrics) { + dprintf(fd, "*** Metric size=%zu\n", metric.DebugString().size()); + string formatted; + wv_metrics::FormatWvCdmMetrics(metric, formatted); + dprintf(fd, "%s\n", formatted.c_str()); + } + } else { + dprintf(fd, "GetMetrics failed, error=%d\n", result); + } +} + +void WVDrmFactory::printCdmProperties(int fd) { + dprintf(fd, "\n**** Widevine CDM properties ****\n"); + + android::sp cdm(getCDM()); + + const bool isLevel1 = + cdm->IsSecurityLevelSupported(wvcdm::CdmSecurityLevel::kSecurityLevelL1); + dprintf(fd, "default security level: [%s]\n", isLevel1 ? "L1" : "L3"); + + const std::map cdmProperties = { + {"version- Widevine CDM:", wvcdm::QUERY_KEY_WVCDM_VERSION}, + {"version- current SRM:", wvcdm::QUERY_KEY_CURRENT_SRM_VERSION}, + {"version(major)- OEM Crypto API:", + wvcdm::QUERY_KEY_OEMCRYPTO_API_VERSION}, + {"version(minor)- OEM Crypto API:", + wvcdm::QUERY_KEY_OEMCRYPTO_API_MINOR_VERSION}, + {"id- device:", wvcdm::QUERY_KEY_DEVICE_ID}, + {"id- system:", wvcdm::QUERY_KEY_SYSTEM_ID}, + {"renewal server url:", wvcdm::QUERY_KEY_RENEWAL_SERVER_URL}, + {"hdcp level- max:", wvcdm::QUERY_KEY_MAX_HDCP_LEVEL}, + {"hdcp level- current:", wvcdm::QUERY_KEY_CURRENT_HDCP_LEVEL}, + {"num sessions- max supported:", wvcdm::QUERY_KEY_MAX_NUMBER_OF_SESSIONS}, + {"num sessions- opened:", wvcdm::QUERY_KEY_NUMBER_OF_OPEN_SESSIONS}, + {"resource rating tier:", wvcdm::QUERY_KEY_RESOURCE_RATING_TIER}, + {"support decrypt hash:", wvcdm::QUERY_KEY_DECRYPT_HASH_SUPPORT}, + {"support SRM update:", wvcdm::QUERY_KEY_SRM_UPDATE_SUPPORT}, + {"support usage table:", wvcdm::QUERY_KEY_USAGE_SUPPORT}, + {"max usage table entries:", wvcdm::QUERY_KEY_MAX_USAGE_TABLE_ENTRIES}, + {"OEM Crypto build info:", wvcdm::QUERY_KEY_OEMCRYPTO_BUILD_INFORMATION}, + {"provisioning id:", wvcdm::QUERY_KEY_PROVISIONING_ID}, + {"provisioning model:", wvcdm::QUERY_KEY_PROVISIONING_MODEL}, + {"analog capabilities:", wvcdm::QUERY_KEY_ANALOG_OUTPUT_CAPABILITIES}, + {"can disable analog output:", + wvcdm::QUERY_KEY_CAN_DISABLE_ANALOG_OUTPUT}, + }; + + string value; + for (const auto& property : cdmProperties) { + cdm->QueryStatus(wvcdm::RequestedSecurityLevel::kLevelDefault, + property.second, &value); + string outString = stringToHex(value); + dprintf(fd, "%s [%s]\n", property.first.c_str(), outString.c_str()); + value.clear(); + } +} + +binder_status_t WVDrmFactory::dump(int fd, const char** args, + uint32_t numArgs) { + if (fd < 0) { + ALOGE("%s: missing fd for writing", __FUNCTION__); + return STATUS_BAD_VALUE; + } + + dprintf(fd, "\nDefault to print all info if no arguments are used.\n"); + dprintf(fd, "Optional arguments are:\n"); + dprintf(fd, "\tm:cdm metrics | p:cdm properties\n"); + dprintf(fd, + "Usage: adb shell lshal debug " + "android.hardware.drm@1.3::IDrmFactory/widevine [m|p]\n"); + + bool dumpCdmProperties, dumpCdmMetrics = false; + if (numArgs == 0) { + // default to print all info if no arguments are given + dumpCdmProperties = dumpCdmMetrics = true; + } else { + for (auto&& str : std::vector{args, args + numArgs}) { + dprintf(fd, "args: %s\n", str.data()); + string option = str.data(); + if (option.find('m') != string::npos || + option.find('M') != string::npos) { + dumpCdmMetrics = true; + } + if (option.find('p') != string::npos || + option.find('P') != string::npos) { + dumpCdmProperties = true; + } + } + } + if (dumpCdmMetrics) printCdmMetrics(fd); + if (dumpCdmProperties) printCdmProperties(fd); + fsync(fd); + + return STATUS_OK; +} + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm diff --git a/libwvdrmengine/aidl_src/android.hardware.drm-service.widevine.rc b/libwvdrmengine/aidl_src/android.hardware.drm-service.widevine.rc new file mode 100644 index 00000000..3a8c1aae --- /dev/null +++ b/libwvdrmengine/aidl_src/android.hardware.drm-service.widevine.rc @@ -0,0 +1,11 @@ +on property:init.svc.mediadrm=running + mkdir /data/vendor/mediadrm 0770 media mediadrm + +service vendor.drm-widevine-hal /vendor/bin/hw/android.hardware.drm-service.widevine + interface aidl android.hardware.drm::ICryptoFactory/widevine + interface aidl android.hardware.drm::IDrmFactory/widevine + class hal + user media + group media mediadrm drmrpc system + ioprio rt 4 + writepid /dev/cpuset/foreground/tasks diff --git a/libwvdrmengine/aidl_src/service.cpp b/libwvdrmengine/aidl_src/service.cpp new file mode 100644 index 00000000..4c65d192 --- /dev/null +++ b/libwvdrmengine/aidl_src/service.cpp @@ -0,0 +1,53 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "WidevineAidlService" + +#include +#include +#include +#include +#include + +#include "WVCreatePluginFactories.h" +#include "WVCryptoFactory.h" +#include "WVDrmFactory.h" + +using ::wvdrm::hardware::drm::widevine::createCryptoFactory; +using ::wvdrm::hardware::drm::widevine::createDrmFactory; +using ::wvdrm::hardware::drm::widevine::WVCryptoFactory; +using ::wvdrm::hardware::drm::widevine::WVDrmFactory; + +int main(int /* argc */, char** /* argv */) { + ABinderProcess_setThreadPoolMaxThreadCount(8); + + std::shared_ptr drmFactory = createDrmFactory(); + const std::string drmInstance = + std::string(WVDrmFactory::descriptor) + "/widevine"; + binder_status_t status = AServiceManager_addService( + drmFactory->asBinder().get(), drmInstance.c_str()); + CHECK(status == STATUS_OK) + << "Failed to add Widevine Factory HAL, status=" << status; + + std::shared_ptr cryptoFactory = createCryptoFactory(); + const std::string cryptoInstance = + std::string(WVCryptoFactory::descriptor) + "/widevine"; + status = AServiceManager_addService(cryptoFactory->asBinder().get(), + cryptoInstance.c_str()); + CHECK(status == STATUS_OK) + << "Failed to add Widevine Crypto HAL, status=" << status; + + ABinderProcess_joinThreadPool(); +} diff --git a/libwvdrmengine/aidl_src/wv_metrics.cpp b/libwvdrmengine/aidl_src/wv_metrics.cpp new file mode 100644 index 00000000..8f2713c6 --- /dev/null +++ b/libwvdrmengine/aidl_src/wv_metrics.cpp @@ -0,0 +1,448 @@ +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// +// Format widevine protobuf metrics + +#include "wv_metrics.h" + +#include +#include +#include +#include +#include + +#include "OEMCryptoCENC.h" +#include "wv_cdm_types.h" + +using namespace drm_metrics; +using std::string; +using std::to_string; + +namespace { +const string kIndentPerLine = " "; + +string FormatCdmErrorTranslation(int error_code) { + std::stringstream os; + os << static_cast(error_code); + return " " + os.str(); +} + +string FormatOEMCryptoResult(int oemcrypto_result) { + std::stringstream os; + os << static_cast(oemcrypto_result); + return " " + os.str(); +} + +string FormatOEMCryptoInitializeMode(const ValueMetric& vm) { + std::map translations = { + {0, "USING_IN_APP"}, + {1, "FORCING_L3"}, + {2, "USING_L3_NO_L1_LIBRARY_PATH"}, + {3, "USING_L3_L1_OPEN_FAILED"}, + {4, "USING_L3_L1_LOAD_FAILED"}, + {5, "USING_L3_COULD_NOT_INITIALIZE_L1"}, + {6, "USING_L3_WRONG_L1_VERSION"}, + {7, "USING_L1_WITH_KEYBOX"}, + {8, "USING_L1_WITH_CERTIFICATE"}, + {9, "USING_L1_CERTIFICATE_MIX"}, + {10, "USING_L3_BAD_KEYBOX"}, + {11, "USING_L3_COULD_NOT_OPEN_FACTORY_KEYBOX"}, + {12, "USING_L3_COULD_NOT_INSTALL_KEYBOX"}, + {13, "USING_L1_INSTALLED_KEYBOX"}, + {14, "USING_L3_INVALID_L1"}, + {15, "USING_L1_WITH_PROVISIONING_3_0"}, + {16, "L3_INITIALIZATION_GENERAL_FAILED"}, + {17, "L3_INITIALIZATION_RNG_FAILED"}, + {18, "L3_INITIALIZATION_SAVE_DEVICE_KEYS_FAILED"}, + {19, "L3_INITIALIZATION_READ_DEVICE_KEYS_FAILED"}, + {20, "L3_INITIALIZATION_VERIFY_DEVIE_KEYS_FAILED"}}; + return translations[vm.int_value()]; +} + +string FormatOEMCryptoHdcpCapability(const ValueMetric& vm) { + std::map translations = { + {0, "HDCP_NONE"}, {1, "HDCP_V1"}, {2, "HDCP_V2"}, + {3, "HDCP_V2_1"}, {4, "HDCP_V2_2"}, {5, "HDCP_V2_3"}, + {0xff, "NO_DIGITAL_OUTPUT"}}; + return translations[vm.int_value()]; +} + +string FormatOEMCryptoProvisioningMethod(const ValueMetric& vm) { + std::map translations = {{0, "PROVISIONING_ERROR"}, + {1, "DRM_CERTIFICATE"}, + {2, "KEYBOX"}, + {3, "OEM_CERTIFICATE"}}; + return translations[vm.int_value()]; +} + +string FormatAttributes(const Attributes& attributes) { + string result; + if (attributes.has_error_code()) { + result.append("error_code:"); + result.append(to_string(attributes.error_code())); + result.append(FormatCdmErrorTranslation(attributes.error_code())); + } + if (attributes.has_error_code_bool()) { + if (result.size()) result.append(","); + result.append("success:"); + result.append(attributes.error_code_bool() ? "true" : "false"); + } + if (attributes.has_cdm_security_level()) { + if (result.size()) result.append(","); + result.append("cdm_security_level:"); + result.append(to_string(attributes.cdm_security_level())); + } + if (attributes.has_security_level()) { + if (result.size()) result.append(","); + result.append("security_level:"); + result.append(to_string(attributes.security_level())); + } + if (attributes.has_length()) { + if (result.size()) result.append(","); + result.append("length:"); + result.append(to_string(attributes.length())); + } + if (attributes.has_encryption_algorithm()) { + if (result.size()) result.append(","); + result.append("encryption_algorithm:"); + result.append(to_string(attributes.encryption_algorithm())); + } + if (attributes.has_signing_algorithm()) { + if (result.size()) result.append(","); + result.append("signing_algorithm:"); + result.append(to_string(attributes.signing_algorithm())); + } + if (attributes.has_oem_crypto_result()) { + if (result.size()) result.append(","); + result.append("oemcrypto_result:"); + result.append(to_string(attributes.oem_crypto_result())); + result.append(FormatOEMCryptoResult(attributes.oem_crypto_result())); + } + if (attributes.has_key_status_type()) { + if (result.size()) result.append(","); + result.append("key_status_type:"); + result.append(to_string(attributes.key_status_type())); + } + if (attributes.has_event_type()) { + if (result.size()) result.append(","); + result.append("event_type:"); + result.append(to_string(attributes.event_type())); + } + if (attributes.has_key_request_type()) { + if (result.size()) result.append(","); + result.append("key_request_type:"); + result.append(to_string(attributes.key_request_type())); + } + if (attributes.has_license_type()) { + if (result.size()) result.append(","); + result.append("license_type:"); + result.append(to_string(attributes.license_type())); + } + if (result.size()) { + return string(" {") + result + "}"; + } else { + return ""; + } +} + +string FormatCounterMetric(const CounterMetric& cm) { + string result; + if (cm.has_count()) { + result = string("count=") + to_string(cm.count()); + if (cm.has_attributes()) { + result.append(FormatAttributes(cm.attributes())); + } + } + return result; +} + +string FormatDistributionMetric(const DistributionMetric& dm) { + string result; + if (dm.has_min()) { + std::ostringstream buffer; + buffer << dm.min(); + result = string("min=") + buffer.str(); + } + if (dm.has_max()) { + std::ostringstream buffer; + buffer << dm.max(); + if (result.size()) result.append(" "); + result += string("max=") + buffer.str(); + } + if (dm.has_mean()) { + std::ostringstream buffer; + buffer << dm.mean(); + if (result.size()) result.append(" "); + result += string("mean=") + buffer.str(); + } + if (dm.has_variance()) { + std::ostringstream buffer; + buffer << dm.variance(); + if (result.size()) result.append(" "); + result += string("variance=") + buffer.str(); + } + if (dm.has_operation_count()) { + if (result.size()) result.append(" "); + result += string("count=") + to_string(dm.operation_count()); + } + if (dm.has_attributes()) { + result.append(FormatAttributes(dm.attributes())); + } + return result; +} + +string FormatValueMetric(const ValueMetric& vm) { + string result; + if (vm.has_error_code()) { + result.append("error(" + to_string(vm.error_code())); + result.append(FormatCdmErrorTranslation(vm.error_code())); + result.append(")"); + } + if (vm.has_int_value()) { + result.append(to_string(vm.int_value())); + } + if (vm.has_double_value()) { + std::ostringstream buffer; + buffer << vm.double_value(); + result.append(buffer.str()); + } + if (vm.has_string_value()) { + result.append("\""); + result.append(vm.string_value()); + result.append("\""); + } + return result; +} + +#define FORMAT_REPEATED_DISTRIBUTION(NAME, INDENT) \ + if (metrics.NAME##_size() == 1) { \ + result.append(INDENT + #NAME + ": "); \ + result.append(FormatDistributionMetric(metrics.NAME(0)) + "\n"); \ + } else { \ + for (int i = 0; i < metrics.NAME##_size(); i++) { \ + result.append(INDENT + #NAME "[" + to_string(i) + "]: "); \ + result.append(FormatDistributionMetric(metrics.NAME(i)) + "\n"); \ + } \ + } + +#define FORMAT_REPEATED_COUNTER(NAME, INDENT) \ + if (metrics.NAME##_size() == 1) { \ + result.append(INDENT + #NAME ": "); \ + result.append(FormatCounterMetric(metrics.NAME(0)) + "\n"); \ + } else { \ + for (int i = 0; i < metrics.NAME##_size(); i++) { \ + result.append(INDENT + #NAME "[" + to_string(i) + "]: "); \ + result.append(FormatCounterMetric(metrics.NAME(i)) + "\n"); \ + } \ + } + +#define FORMAT_OPTIONAL_VALUE(NAME, INDENT) \ + if (metrics.has_##NAME()) { \ + result.append(INDENT + #NAME ": " + FormatValueMetric(metrics.NAME()) + \ + "\n"); \ + } + +#define FORMAT_OPTIONAL_INITIALIZATION_MODE(NAME, INDENT) \ + if (metrics.has_##NAME()) { \ + result.append(INDENT + #NAME ": "); \ + result.append(FormatOEMCryptoInitializeMode(metrics.NAME()) + "\n"); \ + } + +#define FORMAT_OPTIONAL_HDCP_CAPABILITY(NAME, INDENT) \ + if (metrics.has_##NAME()) { \ + result.append(INDENT + #NAME ": "); \ + result.append(FormatOEMCryptoHdcpCapability(metrics.NAME()) + "\n"); \ + } + +#define FORMAT_OPTIONAL_PROVISIONING_METHOD(NAME, INDENT) \ + if (metrics.has_##NAME()) { \ + result.append(INDENT + #NAME ": "); \ + result.append(FormatOEMCryptoProvisioningMethod(metrics.NAME()) + "\n"); \ + } + +#define FORMAT_OPTIONAL_CRYPTO_METRICS(NAME, INDENT) \ + if (metrics.has_##NAME()) { \ + FormatCryptoMetrics(metrics.NAME(), INDENT + kIndentPerLine, result); \ + } + +void FormatCryptoMetrics(const WvCdmMetrics_CryptoMetrics metrics, + const string& indent, string& result) { + // Crypto Session Metrics. + FORMAT_OPTIONAL_VALUE(crypto_session_security_level, indent); + FORMAT_REPEATED_COUNTER(crypto_session_delete_all_usage_reports, indent); + FORMAT_REPEATED_COUNTER(crypto_session_delete_multiple_usage_information, + indent); + FORMAT_REPEATED_DISTRIBUTION(crypto_session_generic_decrypt_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(crypto_session_generic_encrypt_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(crypto_session_generic_sign_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(crypto_session_generic_verify_time_us, indent); + FORMAT_REPEATED_COUNTER(crypto_session_get_device_unique_id, indent); + FORMAT_REPEATED_COUNTER(crypto_session_get_token, indent); + FORMAT_OPTIONAL_VALUE(crypto_session_life_span, indent); + FORMAT_REPEATED_DISTRIBUTION( + crypto_session_load_certificate_private_key_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(crypto_session_open_time_us, indent); + FORMAT_OPTIONAL_VALUE(crypto_session_system_id, indent); + FORMAT_REPEATED_DISTRIBUTION(crypto_session_update_usage_information_time_us, + indent); + FORMAT_OPTIONAL_VALUE(crypto_session_usage_information_support, indent); + + // Usage Table Metrics + FORMAT_OPTIONAL_VALUE(usage_table_header_initial_size, indent); + FORMAT_REPEATED_COUNTER(usage_table_header_add_entry, indent); + FORMAT_REPEATED_COUNTER(usage_table_header_delete_entry, indent); + FORMAT_REPEATED_DISTRIBUTION(usage_table_header_update_entry_time_us, indent); + FORMAT_REPEATED_COUNTER(usage_table_header_load_entry, indent); + + // Usage Table LRU Metrics + FORMAT_OPTIONAL_VALUE(usage_table_header_lru_usage_info_count, indent); + FORMAT_OPTIONAL_VALUE(usage_table_header_lru_offline_license_count, indent); + FORMAT_OPTIONAL_VALUE(usage_table_header_lru_evicted_entry_staleness_s, + indent); + + // |usage_table_header_lru_evicted_entry_type| refers to the enumeration + // CdmUsageEntryStorageType in wv_cdm_types.h. + FORMAT_OPTIONAL_VALUE(usage_table_header_lru_evicted_entry_type, indent); + + // OemCrypto metrics. + FORMAT_OPTIONAL_VALUE(oemcrypto_api_version, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_close_session, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_copy_buffer_time_us, indent); + FORMAT_OPTIONAL_HDCP_CAPABILITY(oemcrypto_current_hdcp_capability, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_deactivate_usage_entry, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_decrypt_cenc_time_us, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_delete_usage_entry, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_delete_usage_table, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_derive_keys_from_session_key_time_us, + indent); + FORMAT_REPEATED_COUNTER(oemcrypto_force_delete_usage_entry, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generate_derived_keys_time_us, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_generate_nonce, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generate_rsa_signature_time_us, + indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generate_signature_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generic_decrypt_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generic_encrypt_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generic_sign_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_generic_verify_time_us, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_get_device_id, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_get_key_data_time_us, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_get_oem_public_certificate, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_get_random, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_initialize_time_us, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_is_anti_rollback_hw_present, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_is_keybox_valid, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_load_device_drm_key_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_load_entitled_keys_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_load_keys_time_us, indent); + FORMAT_OPTIONAL_HDCP_CAPABILITY(oemcrypto_max_hdcp_capability, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_max_number_of_sessions, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_number_of_open_sessions, indent); + FORMAT_OPTIONAL_PROVISIONING_METHOD(oemcrypto_provisioning_method, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_refresh_keys_time_us, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_report_usage, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_rewrap_device_rsa_key_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_rewrap_device_rsa_key_30_time_us, + indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_security_patch_level, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_select_key_time_us, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_usage_table_support, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_update_usage_table, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_update_usage_entry, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_create_usage_table_header, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_load_usage_table_header, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_shrink_usage_table_header, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_create_new_usage_entry, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_load_usage_entry, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_move_entry, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_create_old_usage_entry, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_copy_old_usage_entry, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_set_sandbox, indent); + FORMAT_REPEATED_COUNTER(oemcrypto_set_decrypt_hash, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_resource_rating_tier, indent); + + // Oemcrypto V16 metrics below + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_prep_and_sign_license_request_time_us, + indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_prep_and_sign_renewal_request_time_us, + indent); + FORMAT_REPEATED_DISTRIBUTION( + oemcrypto_prep_and_sign_provisioning_request_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_load_license_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_load_renewal_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(oemcrypto_load_provisioning_time_us, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_minor_api_version, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_maximum_usage_table_header_size, indent); +} + +void FormatSessionMetrics(const WvCdmMetrics_SessionMetrics& metrics, + const string& indent, string& result) { + FORMAT_OPTIONAL_VALUE(session_id, indent); + FORMAT_OPTIONAL_CRYPTO_METRICS(crypto_metrics, indent); + FORMAT_OPTIONAL_VALUE(cdm_session_life_span_ms, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_session_renew_key_time_us, indent); + FORMAT_REPEATED_COUNTER(cdm_session_restore_offline_session, indent); + FORMAT_REPEATED_COUNTER(cdm_session_restore_usage_session, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_session_license_request_latency_ms, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_build_info, indent); + FORMAT_OPTIONAL_VALUE(license_sdk_version, indent); + FORMAT_OPTIONAL_VALUE(license_service_version, indent); +} + +void FormatEngineMetrics(const WvCdmMetrics_EngineMetrics& metrics, + const string& indent, string& result) { + FORMAT_OPTIONAL_CRYPTO_METRICS(crypto_metrics, indent); + + // OEMCrypto Initialize Metrics. + FORMAT_OPTIONAL_INITIALIZATION_MODE(oemcrypto_initialization_mode, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_l1_api_version, indent); + FORMAT_OPTIONAL_VALUE(oemcrypto_l1_min_api_version, indent); + FORMAT_OPTIONAL_VALUE(level3_oemcrypto_initialization_error, indent); + FORMAT_OPTIONAL_VALUE(previous_oemcrypto_initialization_failure, indent); + + // CdmEngine Metrics. + FORMAT_OPTIONAL_VALUE(app_package_name, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_add_key_time_us, indent); + FORMAT_OPTIONAL_VALUE(cdm_engine_cdm_version, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_close_session, indent); + FORMAT_OPTIONAL_VALUE(cdm_engine_creation_time_millis, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_decrypt_time_us, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_find_session_for_key, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_generate_key_request_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_get_provisioning_request_time_us, + indent); + FORMAT_REPEATED_COUNTER(cdm_engine_get_secure_stop_ids, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_get_usage_info_time_us, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_handle_provisioning_response_time_us, + indent); + FORMAT_OPTIONAL_VALUE(cdm_engine_life_span_ms, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_open_key_set_session, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_open_session, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_query_key_status_time_us, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_release_all_usage_info, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_release_usage_info, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_remove_all_usage_info, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_remove_keys, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_remove_usage_info, indent); + FORMAT_REPEATED_DISTRIBUTION(cdm_engine_restore_key_time_us, indent); + FORMAT_REPEATED_COUNTER(cdm_engine_unprovision, indent); +} +} // anonymous namespace + +namespace wv_metrics { +void FormatWvCdmMetrics(const WvCdmMetrics& metrics, string& result) { + string indent = kIndentPerLine; + string next_indent = indent + kIndentPerLine; + + result.append("engine_metrics\n"); + if (metrics.has_engine_metrics()) { + FormatEngineMetrics(metrics.engine_metrics(), indent, result); + } + result.append("session_metrics\n"); + for (int i = 0; i < metrics.session_metrics_size(); i++) { + result.append(indent + "session[" + to_string(i) + "]\n"); + FormatSessionMetrics(metrics.session_metrics(i), next_indent, result); + } +} +} // namespace wv_metrics diff --git a/libwvdrmengine/cdm/core/include/cdm_engine.h b/libwvdrmengine/cdm/core/include/cdm_engine.h index f5b956a3..ce4b6822 100644 --- a/libwvdrmengine/cdm/core/include/cdm_engine.h +++ b/libwvdrmengine/cdm/core/include/cdm_engine.h @@ -146,7 +146,7 @@ class CdmEngine { const CdmSessionId& session_id, const std::string& service_certificate); // Query system information - virtual CdmResponseType QueryStatus(SecurityLevel security_level, + virtual CdmResponseType QueryStatus(RequestedSecurityLevel security_level, const std::string& query_token, std::string* query_response); @@ -184,13 +184,13 @@ class CdmEngine { virtual CdmResponseType GetProvisioningRequest( CdmCertificateType cert_type, const std::string& cert_authority, const std::string& service_certificate, - SecurityLevel requested_security_level, CdmProvisioningRequest* request, - std::string* default_url); + RequestedSecurityLevel requested_security_level, + CdmProvisioningRequest* request, std::string* default_url); // Verify and process a provisioning response. virtual CdmResponseType HandleProvisioningResponse( const CdmProvisioningResponse& response, - SecurityLevel requested_security_level, std::string* cert, + RequestedSecurityLevel requested_security_level, std::string* cert, std::string* wrapped_key); // Return true if there is a device certificate on the current @@ -398,7 +398,7 @@ class CdmEngine { bool ValidateKeySystem(const CdmKeySystem& key_system); CdmResponseType GetUsageInfo(const std::string& app_id, - SecurityLevel requested_security_level, + RequestedSecurityLevel requested_security_level, int* error_detail, CdmUsageInfo* usage_info); void OnKeyReleaseEvent(const CdmKeySetId& key_set_id); diff --git a/libwvdrmengine/cdm/core/include/cdm_engine_metrics_decorator.h b/libwvdrmengine/cdm/core/include/cdm_engine_metrics_decorator.h index 789c1d64..4d908af7 100644 --- a/libwvdrmengine/cdm/core/include/cdm_engine_metrics_decorator.h +++ b/libwvdrmengine/cdm/core/include/cdm_engine_metrics_decorator.h @@ -153,12 +153,11 @@ class CdmEngineMetricsImpl : public T { return sts; } - CdmResponseType GetProvisioningRequest(CdmCertificateType cert_type, - const std::string& cert_authority, - const std::string& service_certificate, - SecurityLevel requested_security_level, - CdmProvisioningRequest* request, - std::string* default_url) override { + CdmResponseType GetProvisioningRequest( + CdmCertificateType cert_type, const std::string& cert_authority, + const std::string& service_certificate, + RequestedSecurityLevel requested_security_level, + CdmProvisioningRequest* request, std::string* default_url) override { CdmResponseType sts; M_TIME(sts = T::GetProvisioningRequest( cert_type, cert_authority, service_certificate, @@ -169,7 +168,7 @@ class CdmEngineMetricsImpl : public T { CdmResponseType HandleProvisioningResponse( const CdmProvisioningResponse& response, - SecurityLevel requested_security_level, std::string* cert, + RequestedSecurityLevel requested_security_level, std::string* cert, std::string* wrapped_key) override { CdmResponseType sts; M_TIME(sts = T::HandleProvisioningResponse( diff --git a/libwvdrmengine/cdm/core/include/cdm_session.h b/libwvdrmengine/cdm/core/include/cdm_session.h index a584e9d4..e3f61e39 100644 --- a/libwvdrmengine/cdm/core/include/cdm_session.h +++ b/libwvdrmengine/cdm/core/include/cdm_session.h @@ -141,7 +141,7 @@ class CdmSession { virtual void OnKeyReleaseEvent(const CdmKeySetId& key_set_id); virtual void GetApplicationId(std::string* app_id); - virtual SecurityLevel GetRequestedSecurityLevel() { + virtual RequestedSecurityLevel GetRequestedSecurityLevel() { return requested_security_level_; } virtual CdmSecurityLevel GetSecurityLevel() { return security_level_; } @@ -283,7 +283,7 @@ class CdmSession { bool is_release_; bool is_temporary_; CdmSecurityLevel security_level_; - SecurityLevel requested_security_level_; + RequestedSecurityLevel requested_security_level_; // If |forced_level3_|, |security_level_| and |requested_security_level_| // MUST be set to kSecurityLevelL3 and kLevel3, respectively. bool forced_level3_ = false; diff --git a/libwvdrmengine/cdm/core/include/certificate_provisioning.h b/libwvdrmengine/cdm/core/include/certificate_provisioning.h index f276b48a..dde4d1e8 100644 --- a/libwvdrmengine/cdm/core/include/certificate_provisioning.h +++ b/libwvdrmengine/cdm/core/include/certificate_provisioning.h @@ -39,7 +39,8 @@ class CertificateProvisioning { // Construct a valid provisioning request. // The request will be sent to the provisioning server. CdmResponseType GetProvisioningRequest( - wvutil::FileSystem* file_system, SecurityLevel requested_security_level, + wvutil::FileSystem* file_system, + RequestedSecurityLevel requested_security_level, CdmCertificateType cert_type, const std::string& cert_authority, const std::string& origin, const std::string& spoid, CdmProvisioningRequest* request, std::string* default_url); @@ -75,7 +76,8 @@ class CertificateProvisioning { private: CdmResponseType GetProvisioningRequestInternal( - wvutil::FileSystem* file_system, SecurityLevel requested_security_level, + wvutil::FileSystem* file_system, + RequestedSecurityLevel requested_security_level, CdmCertificateType cert_type, const std::string& cert_authority, const std::string& origin, const std::string& spoid, CdmProvisioningRequest* request, std::string* default_url); diff --git a/libwvdrmengine/cdm/core/include/crypto_session.h b/libwvdrmengine/cdm/core/include/crypto_session.h index 3a73d686..f45a646f 100644 --- a/libwvdrmengine/cdm/core/include/crypto_session.h +++ b/libwvdrmengine/cdm/core/include/crypto_session.h @@ -91,10 +91,12 @@ class CryptoSession { // The overloaded methods with |requested_level| may be called // without a preceding call to Open. The other method must call Open first. virtual CdmSecurityLevel GetSecurityLevel(); - virtual CdmSecurityLevel GetSecurityLevel(SecurityLevel requested_level); + virtual CdmSecurityLevel GetSecurityLevel( + RequestedSecurityLevel requested_level); virtual bool GetApiVersion(uint32_t* version); - virtual bool GetApiVersion(SecurityLevel requested_level, uint32_t* version); - virtual bool GetApiMinorVersion(SecurityLevel requested_level, + virtual bool GetApiVersion(RequestedSecurityLevel requested_level, + uint32_t* version); + virtual bool GetApiMinorVersion(RequestedSecurityLevel requested_level, uint32_t* minor_version); // This method will return, for devices with a @@ -117,7 +119,7 @@ class CryptoSession { virtual uint8_t GetSecurityPatchLevel(); virtual CdmResponseType Open() { return Open(kLevelDefault); } - virtual CdmResponseType Open(SecurityLevel requested_security_level); + virtual CdmResponseType Open(RequestedSecurityLevel requested_security_level); virtual void Close(); virtual bool IsOpen() { return open_; } @@ -194,30 +196,30 @@ class CryptoSession { // preceding call to Open. The other methods must call Open first. virtual CdmResponseType GetHdcpCapabilities(HdcpCapability* current, HdcpCapability* max); - virtual CdmResponseType GetHdcpCapabilities(SecurityLevel security_level, - HdcpCapability* current, - HdcpCapability* max); + virtual CdmResponseType GetHdcpCapabilities( + RequestedSecurityLevel security_level, HdcpCapability* current, + HdcpCapability* max); virtual bool GetResourceRatingTier(uint32_t* tier); - virtual bool GetResourceRatingTier(SecurityLevel security_level, + virtual bool GetResourceRatingTier(RequestedSecurityLevel security_level, uint32_t* tier); virtual bool GetSupportedCertificateTypes(SupportedCertificateTypes* support); virtual CdmResponseType GetRandom(size_t data_length, uint8_t* random_data); - virtual CdmResponseType GetNumberOfOpenSessions(SecurityLevel security_level, - size_t* count); - virtual CdmResponseType GetMaxNumberOfSessions(SecurityLevel security_level, - size_t* max); + virtual CdmResponseType GetNumberOfOpenSessions( + RequestedSecurityLevel security_level, size_t* count); + virtual CdmResponseType GetMaxNumberOfSessions( + RequestedSecurityLevel security_level, size_t* max); virtual CdmResponseType GetSrmVersion(uint16_t* srm_version); - virtual bool GetBuildInformation(SecurityLevel security_level, + virtual bool GetBuildInformation(RequestedSecurityLevel security_level, std::string* info); virtual bool GetBuildInformation(std::string* info); - virtual bool GetMaximumUsageTableEntries(SecurityLevel security_level, - size_t* number_of_entries); + virtual bool GetMaximumUsageTableEntries( + RequestedSecurityLevel security_level, size_t* number_of_entries); - virtual bool GetDecryptHashSupport(SecurityLevel security_level, + virtual bool GetDecryptHashSupport(RequestedSecurityLevel security_level, uint32_t* hash_support); virtual CdmResponseType SetDecryptHash(uint32_t frame_number, @@ -253,7 +255,7 @@ class CryptoSession { // usage entries. // The first method will use a cached value if present. virtual bool HasUsageInfoSupport(bool* has_support); - virtual bool HasUsageInfoSupport(SecurityLevel security_level, + virtual bool HasUsageInfoSupport(RequestedSecurityLevel security_level, bool* has_support); // Usage report. @@ -271,13 +273,13 @@ class CryptoSession { // The following crypto methods do not require an open session to // complete the operations. virtual CdmResponseType CreateUsageTableHeader( - SecurityLevel requested_security_level, + RequestedSecurityLevel requested_security_level, CdmUsageTableHeader* usage_table_header); virtual CdmResponseType LoadUsageTableHeader( - SecurityLevel requested_security_level, + RequestedSecurityLevel requested_security_level, const CdmUsageTableHeader& usage_table_header); virtual CdmResponseType ShrinkUsageTableHeader( - SecurityLevel requested_security_level, uint32_t new_entry_count, + RequestedSecurityLevel requested_security_level, uint32_t new_entry_count, CdmUsageTableHeader* usage_table_header); // Usage entry. @@ -296,7 +298,8 @@ class CryptoSession { virtual metrics::CryptoMetrics* GetCryptoMetrics() { return metrics_; } virtual CdmResponseType GetProvisioningMethod( - SecurityLevel requested_security_level, CdmClientTokenType* token_type); + RequestedSecurityLevel requested_security_level, + CdmClientTokenType* token_type); // OTA Provisioning @@ -362,7 +365,7 @@ class CryptoSession { // creating a new UsageTableHeader if the global instance has not // been initialized. // Note: This function will lock the global static field lock in write mode. - bool SetUpUsageTableHeader(SecurityLevel requested_security_level); + bool SetUpUsageTableHeader(RequestedSecurityLevel requested_security_level); CdmResponseType GetTokenFromKeybox(std::string* token); CdmResponseType GetTokenFromOemCert(std::string* token); @@ -381,8 +384,8 @@ class CryptoSession { // Retrieves the OEMCrypto usage info support for the specified // |requested_security_level|. // Caller should acquire the OEMCrypto read lock before calling. - bool HasUsageInfoSupportInternal(SecurityLevel requested_security_level, - bool* has_support); + bool HasUsageInfoSupportInternal( + RequestedSecurityLevel requested_security_level, bool* has_support); // These methods fall back into each other in the order given, depending on // how much data they were given and how much data OEMCrypto can accept in one @@ -502,7 +505,7 @@ class CryptoSession { OEMCryptoBufferType destination_buffer_type_; bool is_destination_buffer_type_valid_; - SecurityLevel requested_security_level_; + RequestedSecurityLevel requested_security_level_; // Open session-cached result of OEMCrypto_SupportsUsageTable(). CachedBooleanProperty has_usage_info_support_ = kBooleanUnset; diff --git a/libwvdrmengine/cdm/core/include/device_files.h b/libwvdrmengine/cdm/core/include/device_files.h index fb566fe6..acf14b6f 100644 --- a/libwvdrmengine/cdm/core/include/device_files.h +++ b/libwvdrmengine/cdm/core/include/device_files.h @@ -17,7 +17,7 @@ #include "wv_cdm_types.h" #if defined(UNIT_TEST) -# include +#include #endif namespace wvutil { @@ -321,7 +321,7 @@ class DeviceFiles { static std::string GetFileNameSafeHash(const std::string& input); #if defined(UNIT_TEST) - FRIEND_TEST(DeviceFilesSecurityLevelTest, SecurityLevel); + FRIEND_TEST(DeviceFilesSecurityLevelTest, RequestedSecurityLevel); FRIEND_TEST(DeviceCertificateTest, ReadCertificate); FRIEND_TEST(DeviceFilesStoreTest, StoreLicense); FRIEND_TEST(DeviceFilesHlsAttributesTest, Delete); diff --git a/libwvdrmengine/cdm/core/include/oemcrypto_adapter.h b/libwvdrmengine/cdm/core/include/oemcrypto_adapter.h index f4a42c3f..da9e4f8d 100644 --- a/libwvdrmengine/cdm/core/include/oemcrypto_adapter.h +++ b/libwvdrmengine/cdm/core/include/oemcrypto_adapter.h @@ -27,49 +27,49 @@ OEMCryptoResult OEMCrypto_SetAllowTestKeybox(bool allow); // This attempts to open a session at the desired security level. // If one level is not available, the other will be used instead. OEMCryptoResult OEMCrypto_OpenSession(OEMCrypto_SESSION* session, - SecurityLevel level); + RequestedSecurityLevel level); OEMCryptoResult OEMCrypto_InstallKeybox(const uint8_t* keybox, size_t keyBoxLength, - SecurityLevel level); + RequestedSecurityLevel level); OEMCryptoResult OEMCrypto_GetDeviceID(uint8_t* deviceID, size_t* idLength, - SecurityLevel level); + RequestedSecurityLevel level); OEMCryptoResult OEMCrypto_GetKeyData(uint8_t* keyData, size_t* keyDataLength, - SecurityLevel level); -uint32_t OEMCrypto_APIVersion(SecurityLevel level); -uint32_t OEMCrypto_MinorAPIVersion(SecurityLevel level); -OEMCrypto_Security_Level OEMCrypto_SecurityLevel(SecurityLevel level); -OEMCryptoResult OEMCrypto_GetHDCPCapability(SecurityLevel level, + RequestedSecurityLevel level); +uint32_t OEMCrypto_APIVersion(RequestedSecurityLevel level); +uint32_t OEMCrypto_MinorAPIVersion(RequestedSecurityLevel level); +OEMCrypto_Security_Level OEMCrypto_SecurityLevel(RequestedSecurityLevel level); +OEMCryptoResult OEMCrypto_GetHDCPCapability(RequestedSecurityLevel level, OEMCrypto_HDCP_Capability* current, OEMCrypto_HDCP_Capability* maximum); -bool OEMCrypto_SupportsUsageTable(SecurityLevel level); -bool OEMCrypto_IsAntiRollbackHwPresent(SecurityLevel level); -OEMCryptoResult OEMCrypto_GetNumberOfOpenSessions(SecurityLevel level, +bool OEMCrypto_SupportsUsageTable(RequestedSecurityLevel level); +bool OEMCrypto_IsAntiRollbackHwPresent(RequestedSecurityLevel level); +OEMCryptoResult OEMCrypto_GetNumberOfOpenSessions(RequestedSecurityLevel level, size_t* count); -OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions(SecurityLevel level, +OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions(RequestedSecurityLevel level, size_t* maximum); -uint8_t OEMCrypto_Security_Patch_Level(SecurityLevel level); +uint8_t OEMCrypto_Security_Patch_Level(RequestedSecurityLevel level); OEMCrypto_ProvisioningMethod OEMCrypto_GetProvisioningMethod( - SecurityLevel level); -uint32_t OEMCrypto_SupportedCertificates(SecurityLevel level); -OEMCryptoResult OEMCrypto_CreateUsageTableHeader(SecurityLevel level, + RequestedSecurityLevel level); +uint32_t OEMCrypto_SupportedCertificates(RequestedSecurityLevel level); +OEMCryptoResult OEMCrypto_CreateUsageTableHeader(RequestedSecurityLevel level, uint8_t* header_buffer, size_t* header_buffer_length); -OEMCryptoResult OEMCrypto_LoadUsageTableHeader(SecurityLevel level, +OEMCryptoResult OEMCrypto_LoadUsageTableHeader(RequestedSecurityLevel level, const uint8_t* buffer, size_t buffer_length); -OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader(SecurityLevel level, +OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader(RequestedSecurityLevel level, uint32_t new_table_size, uint8_t* header_buffer, size_t* header_buffer_length); -uint32_t OEMCrypto_GetAnalogOutputFlags(SecurityLevel level); +uint32_t OEMCrypto_GetAnalogOutputFlags(RequestedSecurityLevel level); OEMCryptoResult OEMCrypto_BuildInformation(char* buffer, size_t* buffer_length, - SecurityLevel level); -uint32_t OEMCrypto_ResourceRatingTier(SecurityLevel level); -uint32_t OEMCrypto_SupportsDecryptHash(SecurityLevel level); -size_t OEMCrypto_MaximumUsageTableHeaderSize(SecurityLevel level); + RequestedSecurityLevel level); +uint32_t OEMCrypto_ResourceRatingTier(RequestedSecurityLevel level); +uint32_t OEMCrypto_SupportsDecryptHash(RequestedSecurityLevel level); +size_t OEMCrypto_MaximumUsageTableHeaderSize(RequestedSecurityLevel level); OEMCryptoResult OEMCrypto_GetOEMPublicCertificate(uint8_t* public_cert, size_t* public_cert_length, - SecurityLevel level); + RequestedSecurityLevel level); } // namespace wvcdm /* The following functions are deprecated in OEMCrypto v13. They are defined diff --git a/libwvdrmengine/cdm/core/include/usage_table_header.h b/libwvdrmengine/cdm/core/include/usage_table_header.h index 6e108e8e..33ea263e 100644 --- a/libwvdrmengine/cdm/core/include/usage_table_header.h +++ b/libwvdrmengine/cdm/core/include/usage_table_header.h @@ -19,7 +19,7 @@ #include "wv_cdm_types.h" #if defined(UNIT_TEST) -# include +#include #endif namespace wvcdm { @@ -282,7 +282,7 @@ class UsageTableHeader { std::unique_ptr device_files_; std::unique_ptr file_system_; CdmSecurityLevel security_level_ = kSecurityLevelUninitialized; - SecurityLevel requested_security_level_ = kLevelDefault; + RequestedSecurityLevel requested_security_level_ = kLevelDefault; CdmUsageTableHeader usage_table_header_; std::vector usage_entry_info_; diff --git a/libwvdrmengine/cdm/core/include/wv_cdm_types.h b/libwvdrmengine/cdm/core/include/wv_cdm_types.h index 5e08f63a..f5e3f822 100644 --- a/libwvdrmengine/cdm/core/include/wv_cdm_types.h +++ b/libwvdrmengine/cdm/core/include/wv_cdm_types.h @@ -480,7 +480,7 @@ enum CdmLicenseKeyType : int32_t { kLicenseKeyTypeEntitlement, }; -enum SecurityLevel : uint32_t { kLevelDefault, kLevel3 }; +enum RequestedSecurityLevel : uint32_t { kLevelDefault, kLevel3 }; enum CdmSecurityLevel : int32_t { kSecurityLevelUninitialized, @@ -833,7 +833,7 @@ const char* CdmOfflineLicenseStateToString( CdmOfflineLicenseState license_state); const char* CdmSecurityLevelToString(CdmSecurityLevel security_level); const char* CdmUsageEntryStorageTypeToString(CdmUsageEntryStorageType type); -const char* SecurityLevelToString(SecurityLevel security_level); +const char* RequestedSecurityLevelToString(RequestedSecurityLevel security_level); // Converts a generic, unknown enum value to a string representation // containing its numeric value. // The pointer returned from this function is thread_local. diff --git a/libwvdrmengine/cdm/core/src/cdm_engine.cpp b/libwvdrmengine/cdm/core/src/cdm_engine.cpp index bbb62a27..66d194b5 100644 --- a/libwvdrmengine/cdm/core/src/cdm_engine.cpp +++ b/libwvdrmengine/cdm/core/src/cdm_engine.cpp @@ -38,7 +38,7 @@ class UsagePropertySet : public CdmClientPropertySet { public: UsagePropertySet() {} ~UsagePropertySet() override {} - void set_security_level(SecurityLevel security_level) { + void set_security_level(RequestedSecurityLevel security_level) { if (kLevel3 == security_level) security_level_ = QUERY_VALUE_SECURITY_LEVEL_L3; else @@ -122,7 +122,7 @@ CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system, LOGD("forced_session_id = %s", IdPtrToString(forced_session_id)); } - SecurityLevel requested_security_level = kLevelDefault; + RequestedSecurityLevel requested_security_level = kLevelDefault; if (property_set && property_set->security_level() == QUERY_VALUE_SECURITY_LEVEL_L3) { requested_security_level = kLevel3; @@ -544,11 +544,11 @@ CdmResponseType CdmEngine::SetSessionServiceCertificate( return session->SetServiceCertificate(service_certificate); } -CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level, +CdmResponseType CdmEngine::QueryStatus(RequestedSecurityLevel security_level, const std::string& query_token, std::string* query_response) { LOGD("security_level = %s, query_token = %s", - SecurityLevelToString(security_level), IdToString(query_token)); + RequestedSecurityLevelToString(security_level), IdToString(query_token)); if (query_response == nullptr) { LOGE("Output |query_response| is null"); return PARAMETER_NULL; @@ -969,8 +969,8 @@ bool CdmEngine::IsSecurityLevelSupported(CdmSecurityLevel level) { CdmResponseType CdmEngine::GetProvisioningRequest( CdmCertificateType cert_type, const std::string& cert_authority, const std::string& service_certificate, - SecurityLevel requested_security_level, CdmProvisioningRequest* request, - std::string* default_url) { + RequestedSecurityLevel requested_security_level, + CdmProvisioningRequest* request, std::string* default_url) { LOGI("cert_type = %s", CdmCertificateTypeToString(cert_type)); if (!request) { LOGE("Output |request| is null"); @@ -1043,10 +1043,10 @@ CdmResponseType CdmEngine::GetProvisioningRequest( */ CdmResponseType CdmEngine::HandleProvisioningResponse( const CdmProvisioningResponse& response, - SecurityLevel requested_security_level, std::string* cert, + RequestedSecurityLevel requested_security_level, std::string* cert, std::string* wrapped_key) { LOGI("response_size = %zu, security_level = %s", response.size(), - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); if (response.empty()) { LOGE("Empty provisioning response"); cert_provisioning_.reset(); @@ -1440,7 +1440,7 @@ CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id, return PARAMETER_NULL; } // Return a random usage report from a random security level - SecurityLevel security_level = + RequestedSecurityLevel security_level = wvutil::CdmRandom::RandomBool() ? kLevelDefault : kLevel3; CdmResponseType status = UNKNOWN_ERROR; do { @@ -1460,12 +1460,11 @@ CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id, return status; } -CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id, - SecurityLevel requested_security_level, - int* error_detail, - CdmUsageInfo* usage_info) { +CdmResponseType CdmEngine::GetUsageInfo( + const std::string& app_id, RequestedSecurityLevel requested_security_level, + int* error_detail, CdmUsageInfo* usage_info) { LOGI("app_id = %s, security_level = %s", IdToString(app_id), - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); if (usage_info == nullptr) { LOGE("Output |usage_info| is null"); return PARAMETER_NULL; @@ -1550,7 +1549,7 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo( CdmResponseType status = NO_ERROR; DeviceFiles handle(file_system_); if (handle.Init(cdm_security_level)) { - const SecurityLevel security_level = + const RequestedSecurityLevel security_level = cdm_security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault; usage_property_set_->set_security_level(security_level); usage_session_.reset(new CdmSession(file_system_, metrics_->AddSession())); @@ -1624,7 +1623,7 @@ CdmResponseType CdmEngine::RemoveUsageInfo( for (int j = kSecurityLevelL1; j < kSecurityLevelUnknown; ++j) { DeviceFiles handle(file_system_); if (handle.Init(static_cast(j))) { - SecurityLevel security_level = + RequestedSecurityLevel security_level = static_cast(j) == kSecurityLevelL3 ? kLevel3 : kLevelDefault; usage_property_set_->set_security_level(security_level); diff --git a/libwvdrmengine/cdm/core/src/certificate_provisioning.cpp b/libwvdrmengine/cdm/core/src/certificate_provisioning.cpp index 50bd53ef..3c6bb0d9 100644 --- a/libwvdrmengine/cdm/core/src/certificate_provisioning.cpp +++ b/libwvdrmengine/cdm/core/src/certificate_provisioning.cpp @@ -173,7 +173,7 @@ CertificateProvisioning::GetProvisioningType() { * Returns NO_ERROR for success and CERT_PROVISIONING_REQUEST_ERROR_? if fails. */ CdmResponseType CertificateProvisioning::GetProvisioningRequest( - wvutil::FileSystem* file_system, SecurityLevel requested_security_level, + wvutil::FileSystem* file_system, RequestedSecurityLevel requested_security_level, CdmCertificateType cert_type, const std::string& cert_authority, const std::string& origin, const std::string& spoid, CdmProvisioningRequest* request, std::string* default_url) { @@ -183,7 +183,7 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest( } CdmResponseType CertificateProvisioning::GetProvisioningRequestInternal( - wvutil::FileSystem* file_system, SecurityLevel requested_security_level, + wvutil::FileSystem* file_system, RequestedSecurityLevel requested_security_level, CdmCertificateType cert_type, const std::string& cert_authority, const std::string& origin, const std::string& spoid, CdmProvisioningRequest* request, std::string* default_url) { diff --git a/libwvdrmengine/cdm/core/src/crypto_session.cpp b/libwvdrmengine/cdm/core/src/crypto_session.cpp index c2ae3cd3..6cefeaa3 100644 --- a/libwvdrmengine/cdm/core/src/crypto_session.cpp +++ b/libwvdrmengine/cdm/core/src/crypto_session.cpp @@ -299,7 +299,8 @@ CryptoSession::~CryptoSession() { } CdmResponseType CryptoSession::GetProvisioningMethod( - SecurityLevel requested_security_level, CdmClientTokenType* token_type) { + RequestedSecurityLevel requested_security_level, + CdmClientTokenType* token_type) { OEMCrypto_ProvisioningMethod method; WithOecReadLock("GetProvisioningMethod", [&] { method = OEMCrypto_GetProvisioningMethod(requested_security_level); @@ -467,7 +468,7 @@ void CryptoSession::DisableDelayedTermination() { } bool CryptoSession::SetUpUsageTableHeader( - SecurityLevel requested_security_level) { + RequestedSecurityLevel requested_security_level) { if (usage_table_header_ != nullptr) { LOGE("Usage table is already set up for the current crypto session"); return false; @@ -616,9 +617,9 @@ CdmSecurityLevel CryptoSession::GetSecurityLevel() { } CdmSecurityLevel CryptoSession::GetSecurityLevel( - SecurityLevel requested_security_level) { + RequestedSecurityLevel requested_security_level) { LOGV("Getting security level: requested_security_level = %s", - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); RETURN_IF_UNINITIALIZED(kSecurityLevelUninitialized); const OEMCrypto_Security_Level level = WithOecReadLock( "GetSecurityLevel", @@ -641,7 +642,7 @@ CdmSecurityLevel CryptoSession::GetSecurityLevel( "Ill-formed security level: " "level = \"L%u\", requested_security_level = %s", static_cast(level), - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); return kSecurityLevelUnknown; } @@ -731,10 +732,10 @@ bool CryptoSession::GetApiVersion(uint32_t* version) { return GetApiVersion(requested_security_level_, version); } -bool CryptoSession::GetApiVersion(SecurityLevel security_level, +bool CryptoSession::GetApiVersion(RequestedSecurityLevel security_level, uint32_t* version) { LOGV("Getting API version: security_level = %s", - SecurityLevelToString(security_level)); + RequestedSecurityLevelToString(security_level)); if (!version) { LOGE("Output parameter |version| not provided"); return false; @@ -749,10 +750,10 @@ bool CryptoSession::GetApiVersion(SecurityLevel security_level, return true; } -bool CryptoSession::GetApiMinorVersion(SecurityLevel security_level, +bool CryptoSession::GetApiMinorVersion(RequestedSecurityLevel security_level, uint32_t* minor_version) { LOGV("Getting API minor version: security_level = %s", - SecurityLevelToString(security_level)); + RequestedSecurityLevelToString(security_level)); if (!minor_version) { LOGE("Output parameter |minor_version| not provided"); return false; @@ -890,9 +891,10 @@ uint8_t CryptoSession::GetSecurityPatchLevel() { return patch; } -CdmResponseType CryptoSession::Open(SecurityLevel requested_security_level) { +CdmResponseType CryptoSession::Open( + RequestedSecurityLevel requested_security_level) { LOGD("Opening crypto session: requested_security_level = %s", - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); RETURN_IF_UNINITIALIZED(CRYPTO_SESSION_NOT_INITIALIZED); if (open_) return NO_ERROR; @@ -1872,8 +1874,8 @@ bool CryptoSession::HasUsageInfoSupport(bool* has_support) { }); } -bool CryptoSession::HasUsageInfoSupport(SecurityLevel requested_security_level, - bool* has_support) { +bool CryptoSession::HasUsageInfoSupport( + RequestedSecurityLevel requested_security_level, bool* has_support) { RETURN_IF_UNINITIALIZED(false); RETURN_IF_NULL(has_support, false); return WithOecReadLock("HasUsageInfoSupport", [&] { @@ -1882,9 +1884,9 @@ bool CryptoSession::HasUsageInfoSupport(SecurityLevel requested_security_level, } bool CryptoSession::HasUsageInfoSupportInternal( - SecurityLevel requested_security_level, bool* has_support) { + RequestedSecurityLevel requested_security_level, bool* has_support) { LOGV("requested_security_level = %s", - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); *has_support = WithOecReadLock("HasUsageInfoSupport", [&] { return OEMCrypto_SupportsUsageTable(requested_security_level); }); @@ -2109,11 +2111,11 @@ CdmResponseType CryptoSession::GetHdcpCapabilities(HdcpCapability* current, return GetHdcpCapabilities(requested_security_level_, current, max); } -CdmResponseType CryptoSession::GetHdcpCapabilities(SecurityLevel security_level, - HdcpCapability* current, - HdcpCapability* max) { +CdmResponseType CryptoSession::GetHdcpCapabilities( + RequestedSecurityLevel security_level, HdcpCapability* current, + HdcpCapability* max) { LOGV("Getting HDCP capabilities: id = %u, security_level = %s", - oec_session_id_, SecurityLevelToString(security_level)); + oec_session_id_, RequestedSecurityLevelToString(security_level)); RETURN_IF_UNINITIALIZED(CRYPTO_SESSION_NOT_INITIALIZED); RETURN_IF_NULL(current, PARAMETER_NULL); RETURN_IF_NULL(max, PARAMETER_NULL); @@ -2166,9 +2168,9 @@ CdmResponseType CryptoSession::GetRandom(size_t data_length, } CdmResponseType CryptoSession::GetNumberOfOpenSessions( - SecurityLevel security_level, size_t* count) { + RequestedSecurityLevel security_level, size_t* count) { LOGV("Getting number of open sessions: id = %u, security_level = %s", - oec_session_id_, SecurityLevelToString(security_level)); + oec_session_id_, RequestedSecurityLevelToString(security_level)); RETURN_IF_UNINITIALIZED(CRYPTO_SESSION_NOT_INITIALIZED); RETURN_IF_NULL(count, PARAMETER_NULL); @@ -2190,9 +2192,9 @@ CdmResponseType CryptoSession::GetNumberOfOpenSessions( } CdmResponseType CryptoSession::GetMaxNumberOfSessions( - SecurityLevel security_level, size_t* max) { + RequestedSecurityLevel security_level, size_t* max) { LOGV("Getting max number of sessions: id = %u, security_level = %s", - oec_session_id_, SecurityLevelToString(security_level)); + oec_session_id_, RequestedSecurityLevelToString(security_level)); RETURN_IF_UNINITIALIZED(CRYPTO_SESSION_NOT_INITIALIZED); RETURN_IF_NULL(max, PARAMETER_NULL); @@ -2248,10 +2250,10 @@ bool CryptoSession::GetResourceRatingTier(uint32_t* tier) { return GetResourceRatingTier(requested_security_level_, tier); } -bool CryptoSession::GetResourceRatingTier(SecurityLevel security_level, +bool CryptoSession::GetResourceRatingTier(RequestedSecurityLevel security_level, uint32_t* tier) { LOGV("Getting resource rating tier: security_level = %s", - SecurityLevelToString(security_level)); + RequestedSecurityLevelToString(security_level)); RETURN_IF_UNINITIALIZED(false); RETURN_IF_NULL(tier, false); @@ -2276,10 +2278,10 @@ bool CryptoSession::GetBuildInformation(std::string* info) { return GetBuildInformation(requested_security_level_, info); } -bool CryptoSession::GetBuildInformation(SecurityLevel security_level, +bool CryptoSession::GetBuildInformation(RequestedSecurityLevel security_level, std::string* info) { LOGV("Getting build information: security_level = %s", - SecurityLevelToString(security_level)); + RequestedSecurityLevelToString(security_level)); RETURN_IF_UNINITIALIZED(false); RETURN_IF_NULL(info, false); @@ -2308,10 +2310,10 @@ bool CryptoSession::GetBuildInformation(SecurityLevel security_level, return true; } -bool CryptoSession::GetMaximumUsageTableEntries(SecurityLevel security_level, - size_t* number_of_entries) { +bool CryptoSession::GetMaximumUsageTableEntries( + RequestedSecurityLevel security_level, size_t* number_of_entries) { LOGV("Getting maximum usage table entries: security_level = %s", - SecurityLevelToString(security_level)); + RequestedSecurityLevelToString(security_level)); RETURN_IF_UNINITIALIZED(false); if (number_of_entries == nullptr) { LOGE("Output parameter |number_of_entries| not provided"); @@ -2332,7 +2334,7 @@ bool CryptoSession::GetMaximumUsageTableEntries(SecurityLevel security_level, return *number_of_entries >= kMinimumUsageTableEntriesSupported; } -bool CryptoSession::GetDecryptHashSupport(SecurityLevel security_level, +bool CryptoSession::GetDecryptHashSupport(RequestedSecurityLevel security_level, uint32_t* decrypt_hash_support) { LOGV("Checking if decrypt hash is supported"); RETURN_IF_UNINITIALIZED(false); @@ -2649,10 +2651,10 @@ CdmResponseType CryptoSession::GenericVerify(const std::string& message, } CdmResponseType CryptoSession::CreateUsageTableHeader( - SecurityLevel requested_security_level, + RequestedSecurityLevel requested_security_level, CdmUsageTableHeader* usage_table_header) { LOGV("Creating usage table header: requested_security_level = %s", - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); RETURN_IF_NULL(usage_table_header, PARAMETER_NULL); usage_table_header->resize(kEstimatedInitialUsageTableHeader); @@ -2690,10 +2692,10 @@ CdmResponseType CryptoSession::CreateUsageTableHeader( } CdmResponseType CryptoSession::LoadUsageTableHeader( - SecurityLevel requested_security_level, + RequestedSecurityLevel requested_security_level, const CdmUsageTableHeader& usage_table_header) { LOGV("Loading usage table header: requested_security_level = %s", - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); const OEMCryptoResult result = WithOecWriteLock("LoadUsageTableHeader", [&] { return OEMCrypto_LoadUsageTableHeader( @@ -2731,10 +2733,10 @@ CdmResponseType CryptoSession::LoadUsageTableHeader( } CdmResponseType CryptoSession::ShrinkUsageTableHeader( - SecurityLevel requested_security_level, uint32_t new_entry_count, + RequestedSecurityLevel requested_security_level, uint32_t new_entry_count, CdmUsageTableHeader* usage_table_header) { LOGV("Shrinking usage table header: requested_security_level = %s", - SecurityLevelToString(requested_security_level)); + RequestedSecurityLevelToString(requested_security_level)); RETURN_IF_NULL(usage_table_header, PARAMETER_NULL); size_t usage_table_header_len = 0; diff --git a/libwvdrmengine/cdm/core/src/oemcrypto_adapter_dynamic.cpp b/libwvdrmengine/cdm/core/src/oemcrypto_adapter_dynamic.cpp index 967dfa92..01c94a0b 100644 --- a/libwvdrmengine/cdm/core/src/oemcrypto_adapter_dynamic.cpp +++ b/libwvdrmengine/cdm/core/src/oemcrypto_adapter_dynamic.cpp @@ -1267,7 +1267,8 @@ class Adapter { return result; } - const FunctionPointers* GetFunctionPointers(wvcdm::SecurityLevel level) { + const FunctionPointers* GetFunctionPointers( + wvcdm::RequestedSecurityLevel level) { if (level1_valid_ && level == kLevelDefault) return &level1_; return &level3_; } @@ -1282,7 +1283,7 @@ class Adapter { } OEMCryptoResult OpenSession(OEMCrypto_SESSION* session, - wvcdm::SecurityLevel level) { + wvcdm::RequestedSecurityLevel level) { LevelSession new_session; OEMCryptoResult result; if (level == kLevelDefault && level1_valid_) { @@ -1592,14 +1593,14 @@ OEMCryptoResult OEMCrypto_InitializeAndCheckKeybox( } OEMCryptoResult OEMCrypto_OpenSession(OEMCrypto_SESSION* session, - SecurityLevel level) { + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ERROR_OPEN_SESSION_FAILED; return gAdapter->OpenSession(session, level); } -OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert(const uint8_t* keybox, - size_t keyBoxLength, - SecurityLevel level) { +OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert( + const uint8_t* keybox, size_t keyBoxLength, + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1609,7 +1610,7 @@ OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert(const uint8_t* keybox, } OEMCrypto_ProvisioningMethod OEMCrypto_GetProvisioningMethod( - SecurityLevel level) { + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ProvisioningError; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ProvisioningError; @@ -1619,7 +1620,7 @@ OEMCrypto_ProvisioningMethod OEMCrypto_GetProvisioningMethod( } OEMCryptoResult OEMCrypto_GetDeviceID(uint8_t* deviceID, size_t* idLength, - SecurityLevel level) { + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1632,7 +1633,7 @@ OEMCryptoResult OEMCrypto_GetDeviceID(uint8_t* deviceID, size_t* idLength, } OEMCryptoResult OEMCrypto_GetKeyData(uint8_t* keyData, size_t* keyDataLength, - SecurityLevel level) { + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1644,7 +1645,7 @@ OEMCryptoResult OEMCrypto_GetKeyData(uint8_t* keyData, size_t* keyDataLength, return fcn->GetKeyData(keyData, keyDataLength); } -uint32_t OEMCrypto_APIVersion(SecurityLevel level) { +uint32_t OEMCrypto_APIVersion(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return 0; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return 0; @@ -1652,7 +1653,7 @@ uint32_t OEMCrypto_APIVersion(SecurityLevel level) { return fcn->APIVersion(); } -uint32_t OEMCrypto_MinorAPIVersion(SecurityLevel level) { +uint32_t OEMCrypto_MinorAPIVersion(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return 0; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return 0; @@ -1660,7 +1661,7 @@ uint32_t OEMCrypto_MinorAPIVersion(SecurityLevel level) { return fcn->MinorAPIVersion(); } -uint8_t OEMCrypto_Security_Patch_Level(SecurityLevel level) { +uint8_t OEMCrypto_Security_Patch_Level(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return 0; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return 0; @@ -1669,7 +1670,7 @@ uint8_t OEMCrypto_Security_Patch_Level(SecurityLevel level) { return fcn->SecurityPatchLevel(); } -OEMCrypto_Security_Level OEMCrypto_SecurityLevel(SecurityLevel level) { +OEMCrypto_Security_Level OEMCrypto_SecurityLevel(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_Level_Unknown; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_Level_Unknown; @@ -1691,7 +1692,7 @@ OEMCrypto_Security_Level OEMCrypto_SecurityLevel(SecurityLevel level) { } OEMCryptoResult OEMCrypto_GetHDCPCapability( - SecurityLevel level, OEMCrypto_HDCP_Capability* current, + wvcdm::RequestedSecurityLevel level, OEMCrypto_HDCP_Capability* current, OEMCrypto_HDCP_Capability* maximum) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); @@ -1715,7 +1716,7 @@ OEMCryptoResult OEMCrypto_GetHDCPCapability( } } -uint32_t OEMCrypto_GetAnalogOutputFlags(SecurityLevel level) { +uint32_t OEMCrypto_GetAnalogOutputFlags(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_Unknown_Analog_Output; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_Unknown_Analog_Output; @@ -1726,7 +1727,7 @@ uint32_t OEMCrypto_GetAnalogOutputFlags(SecurityLevel level) { } OEMCryptoResult OEMCrypto_BuildInformation(char* buffer, size_t* buffer_length, - SecurityLevel level) { + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1748,7 +1749,7 @@ OEMCryptoResult OEMCrypto_BuildInformation(char* buffer, size_t* buffer_length, return fcn->BuildInformation(buffer, buffer_length); } -uint32_t OEMCrypto_ResourceRatingTier(SecurityLevel level) { +uint32_t OEMCrypto_ResourceRatingTier(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return 0; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return 0; @@ -1757,7 +1758,7 @@ uint32_t OEMCrypto_ResourceRatingTier(SecurityLevel level) { return fcn->ResourceRatingTier(); } -uint32_t OEMCrypto_SupportsDecryptHash(SecurityLevel level) { +uint32_t OEMCrypto_SupportsDecryptHash(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_Hash_Not_Supported; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_Hash_Not_Supported; @@ -1766,7 +1767,8 @@ uint32_t OEMCrypto_SupportsDecryptHash(SecurityLevel level) { return fcn->SupportsDecryptHash(); } -size_t OEMCrypto_MaximumUsageTableHeaderSize(SecurityLevel level) { +size_t OEMCrypto_MaximumUsageTableHeaderSize( + wvcdm::RequestedSecurityLevel level) { if (!gAdapter.get()) return 0; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return 0; @@ -1775,7 +1777,7 @@ size_t OEMCrypto_MaximumUsageTableHeaderSize(SecurityLevel level) { return fcn->MaximumUsageTableHeaderSize(); } -bool OEMCrypto_SupportsUsageTable(SecurityLevel level) { +bool OEMCrypto_SupportsUsageTable(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return false; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return false; @@ -1784,7 +1786,7 @@ bool OEMCrypto_SupportsUsageTable(SecurityLevel level) { return fcn->SupportsUsageTable(); } -bool OEMCrypto_IsAntiRollbackHwPresent(SecurityLevel level) { +bool OEMCrypto_IsAntiRollbackHwPresent(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return false; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return false; @@ -1793,8 +1795,8 @@ bool OEMCrypto_IsAntiRollbackHwPresent(SecurityLevel level) { return fcn->IsAntiRollbackHwPresent(); } -OEMCryptoResult OEMCrypto_GetNumberOfOpenSessions(SecurityLevel level, - size_t* count) { +OEMCryptoResult OEMCrypto_GetNumberOfOpenSessions( + wvcdm::RequestedSecurityLevel level, size_t* count) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1802,8 +1804,8 @@ OEMCryptoResult OEMCrypto_GetNumberOfOpenSessions(SecurityLevel level, return fcn->GetNumberOfOpenSessions(count); } -OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions(SecurityLevel level, - size_t* maximum) { +OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions( + wvcdm::RequestedSecurityLevel level, size_t* maximum) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1818,7 +1820,7 @@ OEMCryptoResult OEMCrypto_GetMaxNumberOfSessions(SecurityLevel level, return result; } -uint32_t OEMCrypto_SupportedCertificates(SecurityLevel level) { +uint32_t OEMCrypto_SupportedCertificates(wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return 0; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return 0; @@ -1829,9 +1831,9 @@ uint32_t OEMCrypto_SupportedCertificates(SecurityLevel level) { return fcn->SupportedCertificates(); } -OEMCryptoResult OEMCrypto_CreateUsageTableHeader(SecurityLevel level, - uint8_t* header_buffer, - size_t* header_buffer_length) { +OEMCryptoResult OEMCrypto_CreateUsageTableHeader( + wvcdm::RequestedSecurityLevel level, uint8_t* header_buffer, + size_t* header_buffer_length) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1841,9 +1843,9 @@ OEMCryptoResult OEMCrypto_CreateUsageTableHeader(SecurityLevel level, return fcn->CreateUsageTableHeader(header_buffer, header_buffer_length); } -OEMCryptoResult OEMCrypto_LoadUsageTableHeader(SecurityLevel level, - const uint8_t* buffer, - size_t buffer_length) { +OEMCryptoResult OEMCrypto_LoadUsageTableHeader( + wvcdm::RequestedSecurityLevel level, const uint8_t* buffer, + size_t buffer_length) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1853,10 +1855,9 @@ OEMCryptoResult OEMCrypto_LoadUsageTableHeader(SecurityLevel level, return fcn->LoadUsageTableHeader(buffer, buffer_length); } -OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader(SecurityLevel level, - uint32_t new_table_size, - uint8_t* header_buffer, - size_t* header_buffer_length) { +OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader( + wvcdm::RequestedSecurityLevel level, uint32_t new_table_size, + uint8_t* header_buffer, size_t* header_buffer_length) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; @@ -1867,9 +1868,9 @@ OEMCryptoResult OEMCrypto_ShrinkUsageTableHeader(SecurityLevel level, header_buffer_length); } -OEMCryptoResult OEMCrypto_GetOEMPublicCertificate(uint8_t* public_cert, - size_t* public_cert_length, - SecurityLevel level) { +OEMCryptoResult OEMCrypto_GetOEMPublicCertificate( + uint8_t* public_cert, size_t* public_cert_length, + wvcdm::RequestedSecurityLevel level) { if (!gAdapter) return OEMCrypto_ERROR_UNKNOWN_FAILURE; const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level); if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION; diff --git a/libwvdrmengine/cdm/core/src/usage_table_header.cpp b/libwvdrmengine/cdm/core/src/usage_table_header.cpp index 4a86e75a..278f37c8 100644 --- a/libwvdrmengine/cdm/core/src/usage_table_header.cpp +++ b/libwvdrmengine/cdm/core/src/usage_table_header.cpp @@ -146,7 +146,7 @@ bool IsValidCdmSecurityLevelForUsageInfo(CdmSecurityLevel security_level) { security_level == kSecurityLevelL3; } -SecurityLevel CdmSecurityLevelToRequestedLevel( +RequestedSecurityLevel CdmSecurityLevelToRequestedLevel( CdmSecurityLevel security_level) { return security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault; } diff --git a/libwvdrmengine/cdm/core/src/wv_cdm_types.cpp b/libwvdrmengine/cdm/core/src/wv_cdm_types.cpp index 3a02e53d..4d9d1da3 100644 --- a/libwvdrmengine/cdm/core/src/wv_cdm_types.cpp +++ b/libwvdrmengine/cdm/core/src/wv_cdm_types.cpp @@ -108,7 +108,8 @@ const char* CdmUsageEntryStorageTypeToString(CdmUsageEntryStorageType type) { return UnknownValueRep(type); } -const char* SecurityLevelToString(SecurityLevel security_level) { +const char* RequestedSecurityLevelToString( + RequestedSecurityLevel security_level) { switch (security_level) { case kLevelDefault: return QUERY_VALUE_SECURITY_LEVEL_DEFAULT.c_str(); diff --git a/libwvdrmengine/cdm/core/test/cdm_engine_metrics_decorator_unittest.cpp b/libwvdrmengine/cdm/core/test/cdm_engine_metrics_decorator_unittest.cpp index 0ed651d3..c361022d 100644 --- a/libwvdrmengine/cdm/core/test/cdm_engine_metrics_decorator_unittest.cpp +++ b/libwvdrmengine/cdm/core/test/cdm_engine_metrics_decorator_unittest.cpp @@ -85,10 +85,10 @@ class MockCdmEngineImpl : public CdmEngine { (const CdmSessionId&, CdmQueryMap*), (override)); MOCK_METHOD(CdmResponseType, GetProvisioningRequest, (CdmCertificateType, const std::string&, const std::string&, - SecurityLevel, CdmProvisioningRequest*, std::string*), + wvcdm::RequestedSecurityLevel, CdmProvisioningRequest*, std::string*), (override)); MOCK_METHOD(CdmResponseType, HandleProvisioningResponse, - (const CdmProvisioningResponse&, SecurityLevel, std::string*, + (const CdmProvisioningResponse&, wvcdm::RequestedSecurityLevel, std::string*, std::string*), (override)); MOCK_METHOD(CdmResponseType, Unprovision, (CdmSecurityLevel), (override)); diff --git a/libwvdrmengine/cdm/core/test/cdm_engine_test.cpp b/libwvdrmengine/cdm/core/test/cdm_engine_test.cpp index d288c9c4..09f99a9e 100644 --- a/libwvdrmengine/cdm/core/test/cdm_engine_test.cpp +++ b/libwvdrmengine/cdm/core/test/cdm_engine_test.cpp @@ -170,7 +170,7 @@ class WvCdmEngineTest : public WvCdmEnginePreProvTest { CdmKeySetId key_set_id; InitializationData init_data(init_data_type_string, key_id); - if (wvutil::g_cutoff >= wvutil::LOG_DEBUG) init_data.DumpToLogs(); + if (wvutil::g_cutoff >= wvutil::CDM_LOG_DEBUG) init_data.DumpToLogs(); CdmKeyRequest key_request; diff --git a/libwvdrmengine/cdm/core/test/cdm_session_unittest.cpp b/libwvdrmengine/cdm/core/test/cdm_session_unittest.cpp index c9246881..bb1af40b 100644 --- a/libwvdrmengine/cdm/core/test/cdm_session_unittest.cpp +++ b/libwvdrmengine/cdm/core/test/cdm_session_unittest.cpp @@ -147,7 +147,7 @@ class MockCryptoSession : public TestCryptoSession { MOCK_METHOD(CdmClientTokenType, GetPreProvisionTokenType, (), (override)); MOCK_METHOD(CdmSecurityLevel, GetSecurityLevel, (), (override)); MOCK_METHOD(CdmResponseType, Open, (), (override)); - MOCK_METHOD(CdmResponseType, Open, (SecurityLevel), (override)); + MOCK_METHOD(CdmResponseType, Open, (wvcdm::RequestedSecurityLevel), (override)); MOCK_METHOD(CdmResponseType, LoadCertificatePrivateKey, (const CryptoWrappedKey&), (override)); MOCK_METHOD(bool, HasUsageInfoSupport, (bool*), (override)); diff --git a/libwvdrmengine/cdm/core/test/certificate_provisioning_unittest.cpp b/libwvdrmengine/cdm/core/test/certificate_provisioning_unittest.cpp index 9465318c..01dc0bd2 100644 --- a/libwvdrmengine/cdm/core/test/certificate_provisioning_unittest.cpp +++ b/libwvdrmengine/cdm/core/test/certificate_provisioning_unittest.cpp @@ -59,14 +59,14 @@ class MockCryptoSession : public TestCryptoSession { public: MockCryptoSession(metrics::CryptoMetrics* metrics) : TestCryptoSession(metrics) {} - MOCK_METHOD(CdmResponseType, Open, (SecurityLevel), (override)); + MOCK_METHOD(CdmResponseType, Open, (wvcdm::RequestedSecurityLevel), (override)); // Usage Table Header. MOCK_METHOD(CdmResponseType, CreateUsageTableHeader, - (SecurityLevel, CdmUsageTableHeader*), (override)); + (wvcdm::RequestedSecurityLevel, CdmUsageTableHeader*), (override)); MOCK_METHOD(CdmResponseType, LoadUsageTableHeader, - (SecurityLevel, const CdmUsageTableHeader&), (override)); + (wvcdm::RequestedSecurityLevel, const CdmUsageTableHeader&), (override)); MOCK_METHOD(CdmResponseType, ShrinkUsageTableHeader, - (SecurityLevel, uint32_t, CdmUsageTableHeader*), (override)); + (wvcdm::RequestedSecurityLevel, uint32_t, CdmUsageTableHeader*), (override)); // Usage Entry. MOCK_METHOD(CdmResponseType, CreateUsageEntry, (uint32_t*), (override)); MOCK_METHOD(CdmResponseType, LoadUsageEntry, (uint32_t, const CdmUsageEntry&), diff --git a/libwvdrmengine/cdm/core/test/device_files_unittest.cpp b/libwvdrmengine/cdm/core/test/device_files_unittest.cpp index 4d6d9293..8c6acb66 100644 --- a/libwvdrmengine/cdm/core/test/device_files_unittest.cpp +++ b/libwvdrmengine/cdm/core/test/device_files_unittest.cpp @@ -4474,7 +4474,7 @@ TEST_F(DeviceFilesTest, HasCertificateNone) { EXPECT_FALSE(device_files.HasCertificate(false)); } -TEST_P(DeviceFilesSecurityLevelTest, SecurityLevel) { +TEST_P(DeviceFilesSecurityLevelTest, RequestedSecurityLevel) { CdmSecurityLevel security_level = GetParam(); MockFileSystem file_system; std::string certificate(kTestCertificateWithFutureExpiration); diff --git a/libwvdrmengine/cdm/core/test/test_base.cpp b/libwvdrmengine/cdm/core/test/test_base.cpp index cb27d6f9..1543acd5 100644 --- a/libwvdrmengine/cdm/core/test/test_base.cpp +++ b/libwvdrmengine/cdm/core/test/test_base.cpp @@ -598,7 +598,7 @@ void TestLicenseHolder::GenerateKeyRequest( CdmAppParameterMap app_parameters; CdmKeySetId key_set_id; InitializationData init_data(init_data_type_string, key_id); - if (wvutil::g_cutoff >= wvutil::LOG_DEBUG) init_data.DumpToLogs(); + if (wvutil::g_cutoff >= wvutil::CDM_LOG_DEBUG) init_data.DumpToLogs(); CdmKeyRequest key_request; CdmResponseType result = cdm_engine_->GenerateKeyRequest( session_id_, key_set_id, init_data, kLicenseTypeStreaming, app_parameters, diff --git a/libwvdrmengine/cdm/core/test/usage_table_header_unittest.cpp b/libwvdrmengine/cdm/core/test/usage_table_header_unittest.cpp index 73770f98..7e739b8f 100644 --- a/libwvdrmengine/cdm/core/test/usage_table_header_unittest.cpp +++ b/libwvdrmengine/cdm/core/test/usage_table_header_unittest.cpp @@ -434,14 +434,14 @@ class MockCryptoSession : public TestCryptoSession { public: MockCryptoSession(metrics::CryptoMetrics* metrics) : TestCryptoSession(metrics) {} - MOCK_METHOD(CdmResponseType, Open, (SecurityLevel), (override)); + MOCK_METHOD(CdmResponseType, Open, (wvcdm::RequestedSecurityLevel), (override)); // Usage Table Header. MOCK_METHOD(CdmResponseType, CreateUsageTableHeader, - (SecurityLevel, CdmUsageTableHeader*), (override)); + (wvcdm::RequestedSecurityLevel, CdmUsageTableHeader*), (override)); MOCK_METHOD(CdmResponseType, LoadUsageTableHeader, - (SecurityLevel, const CdmUsageTableHeader&), (override)); + (wvcdm::RequestedSecurityLevel, const CdmUsageTableHeader&), (override)); MOCK_METHOD(CdmResponseType, ShrinkUsageTableHeader, - (SecurityLevel, uint32_t, CdmUsageTableHeader*), (override)); + (wvcdm::RequestedSecurityLevel, uint32_t, CdmUsageTableHeader*), (override)); // Usage Entry. MOCK_METHOD(CdmResponseType, CreateUsageEntry, (uint32_t*), (override)); MOCK_METHOD(CdmResponseType, LoadUsageEntry, (uint32_t, const CdmUsageEntry&), @@ -450,11 +450,11 @@ class MockCryptoSession : public TestCryptoSession { (CdmUsageTableHeader*, CdmUsageEntry*), (override)); MOCK_METHOD(CdmResponseType, MoveUsageEntry, (uint32_t), (override)); MOCK_METHOD(CdmResponseType, GetNumberOfOpenSessions, - (SecurityLevel, size_t*), (override)); + (wvcdm::RequestedSecurityLevel, size_t*), (override)); // Fake method for testing. Having an EXPECT_CALL causes complexities // for getting table capacity during initialization. - bool GetMaximumUsageTableEntries(SecurityLevel /*security_level*/, + bool GetMaximumUsageTableEntries(RequestedSecurityLevel /*security_level*/, size_t* number_of_entries) override { if (number_of_entries == nullptr || !maximum_usage_table_entries_set_) return false; @@ -609,13 +609,13 @@ class UsageTableHeaderInitializationTest public: static void SetUpTestCase() { InitVectorConstants(); } - SecurityLevel GetSecurityLevel() const { + RequestedSecurityLevel GetSecurityLevel() const { return (GetParam() == kSecurityLevelL3) ? kLevel3 : kLevelDefault; } }; TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_Success) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); EXPECT_CALL(*crypto_session_, GetNumberOfOpenSessions(security_level, NotNull())) .WillRepeatedly(DoAll(SetArgPointee<1>(0), Return(NO_ERROR))); @@ -634,7 +634,7 @@ TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_Success) { // to reinitialize the usage table should result in a failure. TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_FailureDueToReInit) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // First run, success. EXPECT_CALL(*crypto_session_, @@ -657,7 +657,7 @@ TEST_P(UsageTableHeaderInitializationTest, // Table MUST not be initialized before another session has been opened. TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_FailureDueToExistingSessions) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); EXPECT_CALL(*crypto_session_, GetNumberOfOpenSessions(security_level, NotNull())) .WillRepeatedly(DoAll(SetArgPointee<1>(1), Return(NO_ERROR))); @@ -667,7 +667,7 @@ TEST_P(UsageTableHeaderInitializationTest, // No existing usage table in storage, creating a new table succeeds. TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_CreateNew_AfterRetrieveFails) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Fail to retrieve existing table file @@ -698,7 +698,7 @@ TEST_P(UsageTableHeaderInitializationTest, // skew. Creating a new table succeeds. TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_CreateNew_AfterLoadFails) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Existing table file is retrieved @@ -735,7 +735,7 @@ TEST_P(UsageTableHeaderInitializationTest, // table fails for unknown reason. Initialization MUST fail. TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_CreateNew_CreateFails) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) No table info file exists EXPECT_CALL(*crypto_session_, @@ -759,7 +759,7 @@ TEST_P(UsageTableHeaderInitializationTest, // Initialization MUST fail. TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_CreateNew_StoreFails) { - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) No table info file exists EXPECT_CALL(*crypto_session_, @@ -786,7 +786,7 @@ TEST_P(UsageTableHeaderInitializationTest, TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_AtCapacity) { std::vector usage_entries = kOverFullUsageEntryInfoVector; usage_entries.resize(kDefaultTableCapacity); - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Existing table file is retrieved // 2) Loading existing header within OEMCrypto succeeds @@ -813,7 +813,7 @@ TEST_P(UsageTableHeaderInitializationTest, std::vector usage_entries = kOverFullUsageEntryInfoVector; constexpr size_t kHalfMinCapacity = kDefaultTableCapacity / 2; usage_entries.resize(kHalfMinCapacity); - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Existing table file is retrieved // 2) Loading existing header within OEMCrypto succeeds @@ -842,7 +842,7 @@ TEST_P(UsageTableHeaderInitializationTest, ASSERT_LT(kDefaultTableCapacity, kOverFullUsageEntryInfoVector.size()); const uint32_t table_start_size = static_cast(kOverFullUsageEntryInfoVector.size()); - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Existing table file is retrieved @@ -899,7 +899,7 @@ TEST_P(UsageTableHeaderInitializationTest, TEST_P(UsageTableHeaderInitializationTest, RestoreUsageTable_AboveCapacity_AddEntryFails) { ASSERT_LT(kDefaultTableCapacity, kOverFullUsageEntryInfoVector.size()); - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Existing table file is retrieved @@ -951,7 +951,7 @@ TEST_P(UsageTableHeaderInitializationTest, ASSERT_LT(kDefaultTableCapacity, kOverFullUsageEntryInfoVector.size()); const uint32_t table_start_size = static_cast(kOverFullUsageEntryInfoVector.size()); - const SecurityLevel security_level = GetSecurityLevel(); + const RequestedSecurityLevel security_level = GetSecurityLevel(); // Expectations for restore: // 1) Existing table file is retrieved diff --git a/libwvdrmengine/cdm/include/wv_content_decryption_module.h b/libwvdrmengine/cdm/include/wv_content_decryption_module.h index 3d118d1c..511a88bf 100644 --- a/libwvdrmengine/cdm/include/wv_content_decryption_module.h +++ b/libwvdrmengine/cdm/include/wv_content_decryption_module.h @@ -5,12 +5,12 @@ #ifndef CDM_BASE_WV_CONTENT_DECRYPTION_MODULE_H_ #define CDM_BASE_WV_CONTENT_DECRYPTION_MODULE_H_ +#include + #include #include #include -#include - #include "cdm_identifier.h" #include "disallow_copy_and_assign.h" #include "file_store.h" @@ -66,7 +66,7 @@ class WvContentDecryptionModule : public android::RefBase, public TimerHandler { virtual CdmResponseType RemoveKeys(const CdmSessionId& session_id); // Query system information - virtual CdmResponseType QueryStatus(SecurityLevel security_level, + virtual CdmResponseType QueryStatus(RequestedSecurityLevel security_level, const std::string& key, std::string* value); // Query session information @@ -88,12 +88,12 @@ class WvContentDecryptionModule : public android::RefBase, public TimerHandler { virtual CdmResponseType GetProvisioningRequest( CdmCertificateType cert_type, const std::string& cert_authority, const CdmIdentifier& identifier, const std::string& service_certificate, - SecurityLevel requested_security_level, CdmProvisioningRequest* request, - std::string* default_url); + RequestedSecurityLevel requested_security_level, + CdmProvisioningRequest* request, std::string* default_url); virtual CdmResponseType HandleProvisioningResponse( const CdmIdentifier& identifier, CdmProvisioningResponse& response, - SecurityLevel requested_security_level, std::string* cert, + RequestedSecurityLevel requested_security_level, std::string* cert, std::string* wrapped_key); virtual CdmResponseType Unprovision(CdmSecurityLevel level, diff --git a/libwvdrmengine/cdm/metrics/include/metrics_collections.h b/libwvdrmengine/cdm/metrics/include/metrics_collections.h index 3c6b0433..423a6972 100644 --- a/libwvdrmengine/cdm/metrics/include/metrics_collections.h +++ b/libwvdrmengine/cdm/metrics/include/metrics_collections.h @@ -156,7 +156,7 @@ class CryptoMetrics { crypto_session_load_certificate_private_key_; // This uses the requested security level. EventMetric + RequestedSecurityLevel> crypto_session_open_; ValueMetric crypto_session_system_id_; EventMetric diff --git a/libwvdrmengine/cdm/metrics/src/attribute_handler.cpp b/libwvdrmengine/cdm/metrics/src/attribute_handler.cpp index f1d3b842..a435e0df 100644 --- a/libwvdrmengine/cdm/metrics/src/attribute_handler.cpp +++ b/libwvdrmengine/cdm/metrics/src/attribute_handler.cpp @@ -33,8 +33,9 @@ void SetAttributeField void SetAttributeField(const SecurityLevel& security_level, - drm_metrics::Attributes* attributes) { + RequestedSecurityLevel>( + const RequestedSecurityLevel& security_level, + drm_metrics::Attributes* attributes) { attributes->set_security_level(security_level); } diff --git a/libwvdrmengine/cdm/metrics/test/counter_metric_unittest.cpp b/libwvdrmengine/cdm/metrics/test/counter_metric_unittest.cpp index 9eeb5d5d..098ec632 100644 --- a/libwvdrmengine/cdm/metrics/test/counter_metric_unittest.cpp +++ b/libwvdrmengine/cdm/metrics/test/counter_metric_unittest.cpp @@ -112,7 +112,7 @@ TEST(CounterMetricTest, FourFieldsSuccess) { drm_metrics::Attributes::kLengthFieldNumber, Pow2Bucket, drm_metrics::Attributes::kErrorCodeBoolFieldNumber, bool, drm_metrics::Attributes::kSecurityLevelFieldNumber, - SecurityLevel> + RequestedSecurityLevel> metric; metric.Increment(10LL, 7, Pow2Bucket(13), true, kLevel3); diff --git a/libwvdrmengine/cdm/src/wv_content_decryption_module.cpp b/libwvdrmengine/cdm/src/wv_content_decryption_module.cpp index a5620307..2ff88768 100644 --- a/libwvdrmengine/cdm/src/wv_content_decryption_module.cpp +++ b/libwvdrmengine/cdm/src/wv_content_decryption_module.cpp @@ -114,7 +114,7 @@ CdmResponseType WvContentDecryptionModule::GenerateKeyRequest( cdm_by_session_id_[key_set_id] = cdm_engine; } - const SecurityLevel requested_security_level = + const wvcdm::RequestedSecurityLevel requested_security_level = property_set && property_set->security_level().compare( wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3) == 0 ? wvcdm::kLevel3 @@ -181,7 +181,8 @@ CdmResponseType WvContentDecryptionModule::RemoveKeys( } CdmResponseType WvContentDecryptionModule::QueryStatus( - SecurityLevel security_level, const std::string& key, std::string* value) { + RequestedSecurityLevel security_level, const std::string& key, + std::string* value) { CdmEngine* cdm_engine = EnsureCdmForIdentifier(kDefaultCdmIdentifier); return cdm_engine->QueryStatus(security_level, key, value); } @@ -217,8 +218,8 @@ bool WvContentDecryptionModule::IsSecurityLevelSupported( CdmResponseType WvContentDecryptionModule::GetProvisioningRequest( CdmCertificateType cert_type, const std::string& cert_authority, const CdmIdentifier& identifier, const std::string& service_certificate, - SecurityLevel requested_security_level, CdmProvisioningRequest* request, - std::string* default_url) { + RequestedSecurityLevel requested_security_level, + CdmProvisioningRequest* request, std::string* default_url) { CdmEngine* cdm_engine = EnsureCdmForIdentifier(identifier); return cdm_engine->GetProvisioningRequest( cert_type, cert_authority, service_certificate, requested_security_level, @@ -227,7 +228,7 @@ CdmResponseType WvContentDecryptionModule::GetProvisioningRequest( CdmResponseType WvContentDecryptionModule::HandleProvisioningResponse( const CdmIdentifier& identifier, CdmProvisioningResponse& response, - SecurityLevel requested_security_level, std::string* cert, + RequestedSecurityLevel requested_security_level, std::string* cert, std::string* wrapped_key) { CdmEngine* cdm_engine = EnsureCdmForIdentifier(identifier); return cdm_engine->HandleProvisioningResponse( diff --git a/libwvdrmengine/cdm/test/cdm_extended_duration_test.cpp b/libwvdrmengine/cdm/test/cdm_extended_duration_test.cpp index 78827ddf..49f13633 100644 --- a/libwvdrmengine/cdm/test/cdm_extended_duration_test.cpp +++ b/libwvdrmengine/cdm/test/cdm_extended_duration_test.cpp @@ -4,7 +4,10 @@ #include #include +#include +#include #include +#include #include @@ -284,7 +287,7 @@ class WvCdmExtendedDurationTest : public WvCdmTestBase { CdmAppParameterMap app_parameters; CdmKeyRequest key_request; const std::string init_data_type = "video/mp4"; - if (wvutil::g_cutoff >= wvutil::LOG_DEBUG) { + if (wvutil::g_cutoff >= wvutil::CDM_LOG_DEBUG) { InitializationData parsed_init_data(init_data_type, init_data); parsed_init_data.DumpToLogs(); } @@ -681,7 +684,7 @@ class WvCdmExtendedDurationTest : public WvCdmTestBase { EXPECT_TRUE(StringToInt64(query_info[key], playback_duration_remaining)); } - uint32_t QueryStatus(SecurityLevel security_level, const std::string& key) { + uint32_t QueryStatus(RequestedSecurityLevel security_level, const std::string& key) { std::string str; EXPECT_EQ(wvcdm::NO_ERROR, decryptor_->QueryStatus(security_level, key, &str)); diff --git a/libwvdrmengine/cdm/test/cdm_feature_test.cpp b/libwvdrmengine/cdm/test/cdm_feature_test.cpp index 252c6aaa..88d59e32 100644 --- a/libwvdrmengine/cdm/test/cdm_feature_test.cpp +++ b/libwvdrmengine/cdm/test/cdm_feature_test.cpp @@ -17,14 +17,14 @@ // CDM functionality across a broad range of OEMCrypto implementations // and are not intended to be run by partners. +#include #include #include -#include - -#include #include #include +#include + #include "OEMCryptoCENC.h" #include "arraysize.h" #include "config_test_env.h" @@ -338,7 +338,7 @@ class WvCdmFeatureTest : public WvCdmTestBase { CdmKeyRequest key_request; std::string key_set_id; license_type_ = license_type; - if (wvutil::g_cutoff >= wvutil::LOG_DEBUG) { + if (wvutil::g_cutoff >= wvutil::CDM_LOG_DEBUG) { InitializationData parsed_init_data(init_data_type, init_data); parsed_init_data.DumpToLogs(); } diff --git a/libwvdrmengine/cdm/test/coverage-test.mk b/libwvdrmengine/cdm/test/coverage-test.mk index ec388acf..b2de5221 100644 --- a/libwvdrmengine/cdm/test/coverage-test.mk +++ b/libwvdrmengine/cdm/test/coverage-test.mk @@ -55,7 +55,7 @@ LOCAL_C_INCLUDES += external/protobuf/src LOCAL_STATIC_LIBRARIES := \ libcdm \ libcdm_protos \ - libcdm_utils \ + libcdm_utils_hidl \ libjsmn \ libgmock \ libgtest \ diff --git a/libwvdrmengine/cdm/test/integration-test.mk b/libwvdrmengine/cdm/test/integration-test.mk index 55673b4a..a5075993 100644 --- a/libwvdrmengine/cdm/test/integration-test.mk +++ b/libwvdrmengine/cdm/test/integration-test.mk @@ -45,7 +45,7 @@ LOCAL_C_INCLUDES += external/protobuf/src LOCAL_STATIC_LIBRARIES := \ libcdm \ libcdm_protos \ - libcdm_utils \ + libcdm_utils_hidl \ libjsmn \ libgmock \ libgtest \ diff --git a/libwvdrmengine/cdm/test/request_license_test.cpp b/libwvdrmengine/cdm/test/request_license_test.cpp index 15542349..2de36756 100644 --- a/libwvdrmengine/cdm/test/request_license_test.cpp +++ b/libwvdrmengine/cdm/test/request_license_test.cpp @@ -603,7 +603,7 @@ SessionSharingSubSampleInfo session_sharing_sub_samples[] = { struct UsageInfoSubSampleInfo { SubSampleInfo* sub_sample; uint32_t usage_info; - wvcdm::SecurityLevel security_level; + wvcdm::RequestedSecurityLevel security_level; std::string app_id; }; @@ -1757,7 +1757,7 @@ class WvCdmRequestLicenseTest : public WvCdmTestBase { CdmKeyRequest key_request; std::string key_set_id; license_type_ = license_type; - if (wvutil::g_cutoff >= wvutil::LOG_DEBUG) { + if (wvutil::g_cutoff >= wvutil::CDM_LOG_DEBUG) { InitializationData parsed_init_data(init_data_type, init_data); parsed_init_data.DumpToLogs(); } @@ -1982,7 +1982,7 @@ class WvCdmRequestLicenseTest : public WvCdmTestBase { } bool IsProvisioned(const CdmIdentifier& identifier, - SecurityLevel requested_security_level) { + RequestedSecurityLevel requested_security_level) { TestWvCdmClientPropertySet property_set_L3; TestWvCdmClientPropertySet* property_set = nullptr; @@ -2018,7 +2018,7 @@ class WvCdmRequestLicenseTest : public WvCdmTestBase { void Provision() { Provision(kDefaultCdmIdentifier, kLevelDefault); } void Provision(const CdmIdentifier& identifier, - SecurityLevel requested_security_level, + RequestedSecurityLevel requested_security_level, CdmProvisioningResponse* provisioning_response = nullptr) { TestWvCdmClientPropertySet property_set_L3; TestWvCdmClientPropertySet* property_set = nullptr; @@ -2086,7 +2086,8 @@ class WvCdmRequestLicenseTest : public WvCdmTestBase { return security_level; } - uint32_t QueryStatus(SecurityLevel security_level, const std::string& key) { + uint32_t QueryStatus(RequestedSecurityLevel security_level, + const std::string& key) { std::string str; EXPECT_EQ(wvcdm::NO_ERROR, decryptor_->QueryStatus(security_level, key, &str)); diff --git a/libwvdrmengine/cdm/test/unit-test.mk b/libwvdrmengine/cdm/test/unit-test.mk index 98401333..28985e61 100644 --- a/libwvdrmengine/cdm/test/unit-test.mk +++ b/libwvdrmengine/cdm/test/unit-test.mk @@ -42,7 +42,7 @@ LOCAL_C_INCLUDES += external/protobuf/src LOCAL_STATIC_LIBRARIES := \ libcdm \ libcdm_protos \ - libcdm_utils \ + libcdm_utils_hidl \ libjsmn \ libgmock \ libgtest \ diff --git a/libwvdrmengine/cdm/util/include/log.h b/libwvdrmengine/cdm/util/include/log.h index f4c11dab..f4d5e729 100644 --- a/libwvdrmengine/cdm/util/include/log.h +++ b/libwvdrmengine/cdm/util/include/log.h @@ -22,13 +22,13 @@ namespace wvutil { typedef enum { // This log level should only be used for |g_cutoff|, in order to silence all // logging. It should never be passed to |Log()| as a log level. - LOG_SILENT = -1, + CDM_LOG_SILENT = -1, - LOG_ERROR = 0, - LOG_WARN = 1, - LOG_INFO = 2, - LOG_DEBUG = 3, - LOG_VERBOSE = 4, + CDM_LOG_ERROR = 0, + CDM_LOG_WARN = 1, + CDM_LOG_INFO = 2, + CDM_LOG_DEBUG = 3, + CDM_LOG_VERBOSE = 4, } LogPriority; extern LogPriority g_cutoff; @@ -93,15 +93,15 @@ CORE_UTIL_EXPORT void Log(const char* file, const char* function, int line, // Log APIs #ifndef LOGE # define LOGE(...) \ - Log(__FILE__, __func__, __LINE__, wvutil::LOG_ERROR, __VA_ARGS__) + Log(__FILE__, __func__, __LINE__, wvutil::CDM_LOG_ERROR, __VA_ARGS__) # define LOGW(...) \ - Log(__FILE__, __func__, __LINE__, wvutil::LOG_WARN, __VA_ARGS__) + Log(__FILE__, __func__, __LINE__, wvutil::CDM_LOG_WARN, __VA_ARGS__) # define LOGI(...) \ - Log(__FILE__, __func__, __LINE__, wvutil::LOG_INFO, __VA_ARGS__) + Log(__FILE__, __func__, __LINE__, wvutil::CDM_LOG_INFO, __VA_ARGS__) # define LOGD(...) \ - Log(__FILE__, __func__, __LINE__, wvutil::LOG_DEBUG, __VA_ARGS__) + Log(__FILE__, __func__, __LINE__, wvutil::CDM_LOG_DEBUG, __VA_ARGS__) # define LOGV(...) \ - Log(__FILE__, __func__, __LINE__, wvutil::LOG_VERBOSE, __VA_ARGS__) + Log(__FILE__, __func__, __LINE__, wvutil::CDM_LOG_VERBOSE, __VA_ARGS__) #endif } // namespace wvutil diff --git a/libwvdrmengine/cdm/util/src/log.cpp b/libwvdrmengine/cdm/util/src/log.cpp index 95866a40..b87ca043 100644 --- a/libwvdrmengine/cdm/util/src/log.cpp +++ b/libwvdrmengine/cdm/util/src/log.cpp @@ -11,23 +11,27 @@ * at the top of your source file) to change that behavior. */ #ifndef LOG_NDEBUG -# ifdef NDEBUG -# define LOG_NDEBUG 1 -# else -# define LOG_NDEBUG 0 -# endif +#ifdef NDEBUG +#define LOG_NDEBUG 1 +#else +#define LOG_NDEBUG 0 +#endif #endif #define LOG_TAG "WVCdm" #define LOG_BUF_SIZE 5120 #include "log.h" -#include -#include +#ifdef IS_HIDL +#include +#else // AIDL is the default +#include +#endif #include #include #include +#include #include #include @@ -51,7 +55,7 @@ int64_t GetCurrentTimeMs() { } } // namespace -LogPriority g_cutoff = LOG_VERBOSE; +LogPriority g_cutoff = CDM_LOG_VERBOSE; LogBuffer g_logbuf; @@ -72,7 +76,11 @@ void ClearLoggingUid() { uint32_t GetLoggingUid() { return tl_logging_uid_; } uint32_t GetIpcCallingUid() { +#ifdef IS_HIDL const auto self = android::hardware::IPCThreadState::selfOrNull(); +#else // AIDL is the default + const auto self = android::IPCThreadState::selfOrNull(); +#endif return self ? self->getCallingUid() : UNKNOWN_UID; } @@ -97,32 +105,32 @@ void Log(const char* file, const char* function, int line, LogPriority level, android_LogPriority prio = ANDROID_LOG_VERBOSE; switch (level) { - case LOG_SILENT: - return; // It is nonsensical to pass LOG_SILENT. - case LOG_ERROR: + case CDM_LOG_SILENT: + return; // It is nonsensical to pass CDM_LOG_SILENT. + case CDM_LOG_ERROR: prio = ANDROID_LOG_ERROR; break; - case LOG_WARN: + case CDM_LOG_WARN: prio = ANDROID_LOG_WARN; break; - case LOG_INFO: + case CDM_LOG_INFO: prio = ANDROID_LOG_INFO; break; - case LOG_DEBUG: + case CDM_LOG_DEBUG: prio = ANDROID_LOG_DEBUG; break; #if LOG_NDEBUG - case LOG_VERBOSE: + case CDM_LOG_VERBOSE: return; #else - case LOG_VERBOSE: + case CDM_LOG_VERBOSE: prio = ANDROID_LOG_VERBOSE; break; #endif } __android_log_write(prio, LOG_TAG, buf); - if (level <= LOG_INFO) { + if (level <= CDM_LOG_INFO) { uint32_t uid = tl_logging_uid_set_ ? tl_logging_uid_ : GetIpcCallingUid(); g_logbuf.addLog({uid, GetCurrentTimeMs(), level, buf}); } diff --git a/libwvdrmengine/include_hidl/TypeConvert.h b/libwvdrmengine/include_hidl/TypeConvert.h index 1e129e71..7d3fd659 100644 --- a/libwvdrmengine/include_hidl/TypeConvert.h +++ b/libwvdrmengine/include_hidl/TypeConvert.h @@ -19,9 +19,9 @@ #include +#include "HidlTypes.h" #include "log.h" #include "media/stagefright/MediaErrors.h" -#include "HidlTypes.h" #include "utils/Errors.h" namespace android { @@ -32,15 +32,15 @@ namespace widevine { inline ::drm::V1_4::LogPriority toHidlPriority(wvutil::LogPriority p) { switch (p) { - case wvutil::LogPriority::LOG_ERROR: + case wvutil::LogPriority::CDM_LOG_ERROR: return ::drm::V1_4::LogPriority::ERROR; - case wvutil::LogPriority::LOG_WARN: + case wvutil::LogPriority::CDM_LOG_WARN: return ::drm::V1_4::LogPriority::WARN; - case wvutil::LogPriority::LOG_INFO: + case wvutil::LogPriority::CDM_LOG_INFO: return ::drm::V1_4::LogPriority::INFO; - case wvutil::LogPriority::LOG_DEBUG: + case wvutil::LogPriority::CDM_LOG_DEBUG: return ::drm::V1_4::LogPriority::DEBUG; - case wvutil::LogPriority::LOG_VERBOSE: + case wvutil::LogPriority::CDM_LOG_VERBOSE: return ::drm::V1_4::LogPriority::VERBOSE; default: return ::drm::V1_4::LogPriority::UNKNOWN; @@ -48,7 +48,7 @@ inline ::drm::V1_4::LogPriority toHidlPriority(wvutil::LogPriority p) { return ::drm::V1_4::LogPriority::UNKNOWN; } -template +template hidl_vec toHidlVec(const std::vector &vec); template<> @@ -58,9 +58,9 @@ inline hidl_vec<::drm::V1_4::LogMessage> toHidlVec(const std::vector toHidlVec(const std::vector(vec2); } -template const hidl_vec toHidlVec(const std::vector &vec) { - hidl_vec hVec; - hVec.setToExternal(const_cast(vec.data()), vec.size()); - return hVec; +template +const hidl_vec toHidlVec(const std::vector &vec) { + hidl_vec hVec; + hVec.setToExternal(const_cast(vec.data()), vec.size()); + return hVec; } -template hidl_vec toHidlVec(std::vector &vec) { - hidl_vec hVec; - hVec.setToExternal(vec.data(), vec.size()); - return hVec; +template +hidl_vec toHidlVec(std::vector &vec) { + hidl_vec hVec; + hVec.setToExternal(vec.data(), vec.size()); + return hVec; } -template const std::vector toVector(const hidl_vec &hVec) { - std::vector vec; - vec.assign(hVec.data(), hVec.data() + hVec.size()); - return *const_cast *>(&vec); +template +const std::vector toVector(const hidl_vec &hVec) { + std::vector vec; + vec.assign(hVec.data(), hVec.data() + hVec.size()); + return *const_cast *>(&vec); } -template std::vector toVector(hidl_vec &hVec) { - std::vector vec; - vec.assign(hVec.data(), hVec.data() + hVec.size()); - return vec; +template +std::vector toVector(hidl_vec &hVec) { + std::vector vec; + vec.assign(hVec.data(), hVec.data() + hVec.size()); + return vec; } -template const std::vector toVector( - const hidl_array &hArray) { - std::vector vec; - vec.assign(hArray.data(), hArray.data() + hArray.size()); - return vec; +template +const std::vector toVector(const hidl_array &hArray) { + std::vector vec; + vec.assign(hArray.data(), hArray.data() + hArray.size()); + return vec; } -template std::vector toVector( - hidl_array &hArray) { - std::vector vec; - vec.assign(hArray.data(), hArray.data() + hArray.size()); - return vec; +template +std::vector toVector(hidl_array &hArray) { + std::vector vec; + vec.assign(hArray.data(), hArray.data() + hArray.size()); + return vec; } } // namespace widevine @@ -112,4 +116,4 @@ template std::vector toVector( } // namespace hardware } // namespace android -#endif // WVDRM_ANDROID_HARDWARE_DRM_V1_0_TYPECONVERT +#endif // WVDRM_ANDROID_HARDWARE_DRM_V1_0_TYPECONVERT diff --git a/libwvdrmengine/level3/arm/libl3oemcrypto.cpp b/libwvdrmengine/level3/arm/libl3oemcrypto.cpp index c00173d6..fd655d6f 100644 --- a/libwvdrmengine/level3/arm/libl3oemcrypto.cpp +++ b/libwvdrmengine/level3/arm/libl3oemcrypto.cpp @@ -72605,7 +72605,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { pcjvysqq(12) = wssbanwq; if (!pcjvysqq(12)) goto pfszseio; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Initialize without previous terminate."); delete wssbanwq; } @@ -72617,7 +72617,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { pcjvysqq(13) = !wssbanwq; if (!pcjvysqq(13)) goto eukkunjy; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Memory Full. Cannot initialize."); return OEMCrypto_ERROR_INIT_FAILED; } @@ -72626,7 +72626,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { } wssbanwq->valdayag(); wssbanwq->qkinveng(false); - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3 Library " "22593" " " @@ -77757,7 +77757,7 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { { pcjvysqq(13) = nfftdizt(1) != OEMCrypto_SUCCESS; if (!pcjvysqq(13)) goto qmmpauwe; - { wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 has leaked memory."); } + { wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 has leaked memory."); } qmmpauwe:; } @@ -77770,12 +77770,12 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { wssbanwq->qkinveng(false); delete wssbanwq; wssbanwq = nullptr; - wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 Terminate."); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate."); } goto rdgvmkty; jnutneqm:; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate without initialize."); } rdgvmkty:; @@ -77959,7 +77959,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( (*qpevmftl(0)).buffers.input_data_length == 0; if (!pcjvysqq(15)) goto ujqsidfb; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): OEMCrypto_ERROR_INVALID_CONTEXT."); return OEMCrypto_ERROR_INVALID_CONTEXT; } @@ -78012,7 +78012,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( pcjvysqq(7) = mjitdsat(22) != (*qpevmftl(0)).buffers.input_data_length; if (!pcjvysqq(7)) goto nkdoymam; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): Sample and subsample lengths do " "not match."); return OEMCrypto_ERROR_INVALID_CONTEXT; @@ -78970,12 +78970,12 @@ OEMCryptoResult wvoec3::Level3_LoadCasECMKeys( OEMCryptoResult wvoec3::Level3_ProductionReady() { return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Idle(OEMCrypto_IdleState amndrbyt, uint32_t tuwbdepq) { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "no OEMCrypto activity for some time so entering idle state"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Wake() { - wvutil::Log("", "", 0, wvutil::LOG_INFO, "OEMCrypto operations resuming"); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "OEMCrypto operations resuming"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_ReuseUsageEntry(OEMCrypto_SESSION hiafcijl, diff --git a/libwvdrmengine/level3/arm64/libl3oemcrypto.cpp b/libwvdrmengine/level3/arm64/libl3oemcrypto.cpp index ba2c6e55..4fa5673c 100644 --- a/libwvdrmengine/level3/arm64/libl3oemcrypto.cpp +++ b/libwvdrmengine/level3/arm64/libl3oemcrypto.cpp @@ -71016,7 +71016,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { gkbaixuw(6) = abosaqzi; if (!gkbaixuw(6)) goto ocplyqum; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Initialize without previous terminate."); delete abosaqzi; } @@ -71028,7 +71028,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { gkbaixuw(11) = !abosaqzi; if (!gkbaixuw(11)) goto ruvbjzfp; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Memory Full. Cannot initialize."); return OEMCrypto_ERROR_INIT_FAILED; } @@ -71037,7 +71037,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { } abosaqzi->ryqthqkc(); abosaqzi->xogtuwyr(false); - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3 Library " "22594" " " @@ -76168,7 +76168,7 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { { gkbaixuw(11) = bdjdcpvb(1) != OEMCrypto_SUCCESS; if (!gkbaixuw(11)) goto zoqretyr; - { wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 has leaked memory."); } + { wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 has leaked memory."); } zoqretyr:; } @@ -76181,12 +76181,12 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { abosaqzi->xogtuwyr(false); delete abosaqzi; abosaqzi = nullptr; - wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 Terminate."); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate."); } goto iebfsbxm; hktmklkr:; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate without initialize."); } iebfsbxm:; @@ -76370,7 +76370,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( (*sfozxhrd(0)).buffers.input_data_length == 0; if (!gkbaixuw(14)) goto chkzhosj; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): OEMCrypto_ERROR_INVALID_CONTEXT."); return OEMCrypto_ERROR_INVALID_CONTEXT; } @@ -76423,7 +76423,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( gkbaixuw(4) = jahibttx(22) != (*sfozxhrd(0)).buffers.input_data_length; if (!gkbaixuw(4)) goto kjjcysbz; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): Sample and subsample lengths do " "not match."); return OEMCrypto_ERROR_INVALID_CONTEXT; @@ -77381,12 +77381,12 @@ OEMCryptoResult wvoec3::Level3_LoadCasECMKeys( OEMCryptoResult wvoec3::Level3_ProductionReady() { return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Idle(OEMCrypto_IdleState gqmrlgqy, uint32_t gyfjltks) { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "no OEMCrypto activity for some time so entering idle state"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Wake() { - wvutil::Log("", "", 0, wvutil::LOG_INFO, "OEMCrypto operations resuming"); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "OEMCrypto operations resuming"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_ReuseUsageEntry(OEMCrypto_SESSION dxjjtwmq, diff --git a/libwvdrmengine/level3/src/level3_file_system_android.cpp b/libwvdrmengine/level3/src/level3_file_system_android.cpp index 5d2182e4..b6f0a032 100644 --- a/libwvdrmengine/level3/src/level3_file_system_android.cpp +++ b/libwvdrmengine/level3/src/level3_file_system_android.cpp @@ -3,6 +3,7 @@ #include #include #include + #include #include @@ -33,7 +34,7 @@ OEMCrypto_Level3AndroidFileSystem::OEMCrypto_Level3AndroidFileSystem() base_path_[pos] = '\0'; if (mkdir(base_path_.c_str(), 0775) != 0 && errno != EEXIST) { wvutil::Log( - "", "", 0, wvutil::LOG_ERROR, + "", "", 0, wvutil::CDM_LOG_ERROR, "Could not create base directories for Level3FileSystem, error: %s\n", strerror(errno)); } diff --git a/libwvdrmengine/level3/x86/libl3oemcrypto.cpp b/libwvdrmengine/level3/x86/libl3oemcrypto.cpp index 812d589b..c5da74e6 100644 --- a/libwvdrmengine/level3/x86/libl3oemcrypto.cpp +++ b/libwvdrmengine/level3/x86/libl3oemcrypto.cpp @@ -66739,7 +66739,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { wjefhnew(5) = yfvdrlzm; if (!wjefhnew(5)) goto drsqaxuq; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Initialize without previous terminate."); delete yfvdrlzm; } @@ -66751,7 +66751,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { wjefhnew(3) = !yfvdrlzm; if (!wjefhnew(3)) goto amidxzlx; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Memory Full. Cannot initialize."); return OEMCrypto_ERROR_INIT_FAILED; } @@ -66760,7 +66760,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { } yfvdrlzm->eudrzjws(); yfvdrlzm->yuisicqx(false); - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3 Library " "22595" " " @@ -71891,7 +71891,7 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { { wjefhnew(3) = oqlkuqrv(1) != OEMCrypto_SUCCESS; if (!wjefhnew(3)) goto daviuyli; - { wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 has leaked memory."); } + { wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 has leaked memory."); } daviuyli:; } @@ -71904,12 +71904,12 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { yfvdrlzm->yuisicqx(false); delete yfvdrlzm; yfvdrlzm = nullptr; - wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 Terminate."); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate."); } goto iehvrxmr; wuuqxvbz:; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate without initialize."); } iehvrxmr:; @@ -72093,7 +72093,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( (*jvztisel(0)).buffers.input_data_length == 0; if (!wjefhnew(7)) goto fvhtpexx; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): OEMCrypto_ERROR_INVALID_CONTEXT."); return OEMCrypto_ERROR_INVALID_CONTEXT; } @@ -72146,7 +72146,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( wjefhnew(14) = qxolabjj(22) != (*jvztisel(0)).buffers.input_data_length; if (!wjefhnew(14)) goto zteseqlz; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): Sample and subsample lengths do " "not match."); return OEMCrypto_ERROR_INVALID_CONTEXT; @@ -73104,12 +73104,12 @@ OEMCryptoResult wvoec3::Level3_LoadCasECMKeys( OEMCryptoResult wvoec3::Level3_ProductionReady() { return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Idle(OEMCrypto_IdleState chwhlfvb, uint32_t fqntjcao) { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "no OEMCrypto activity for some time so entering idle state"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Wake() { - wvutil::Log("", "", 0, wvutil::LOG_INFO, "OEMCrypto operations resuming"); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "OEMCrypto operations resuming"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_ReuseUsageEntry(OEMCrypto_SESSION umxxtuqq, diff --git a/libwvdrmengine/level3/x86_64/libl3oemcrypto.cpp b/libwvdrmengine/level3/x86_64/libl3oemcrypto.cpp index 8a4f6afd..46d3d99e 100644 --- a/libwvdrmengine/level3/x86_64/libl3oemcrypto.cpp +++ b/libwvdrmengine/level3/x86_64/libl3oemcrypto.cpp @@ -62874,7 +62874,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { nipzhrzp(8) = oxnltpjo; if (!nipzhrzp(8)) goto hxvhrouu; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Initialize without previous terminate."); delete oxnltpjo; } @@ -62886,7 +62886,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { nipzhrzp(13) = !oxnltpjo; if (!nipzhrzp(13)) goto qposqnst; { - wvutil::Log("", "", 0, wvutil::LOG_ERROR, + wvutil::Log("", "", 0, wvutil::CDM_LOG_ERROR, "Memory Full. Cannot initialize."); return OEMCrypto_ERROR_INIT_FAILED; } @@ -62895,7 +62895,7 @@ OEMCryptoResult wvoec3::Level3_Initialize() { } oxnltpjo->mjliflra(); oxnltpjo->cgyzlfok(false); - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3 Library " "22596" " " @@ -68026,7 +68026,7 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { { nipzhrzp(13) = mpyitnut(1) != OEMCrypto_SUCCESS; if (!nipzhrzp(13)) goto yakxyukj; - { wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 has leaked memory."); } + { wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 has leaked memory."); } yakxyukj:; } @@ -68039,12 +68039,12 @@ OEMCryptoResult wvoec3::Level3_Terminate(void) { oxnltpjo->cgyzlfok(false); delete oxnltpjo; oxnltpjo = nullptr; - wvutil::Log("", "", 0, wvutil::LOG_INFO, "L3 Terminate."); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate."); } goto idyrdqke; qeycvpqm:; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "L3 Terminate without initialize."); } idyrdqke:; @@ -68228,7 +68228,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( (*xumlwwbg(0)).buffers.input_data_length == 0; if (!nipzhrzp(9)) goto vpeijjhx; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): OEMCrypto_ERROR_INVALID_CONTEXT."); return OEMCrypto_ERROR_INVALID_CONTEXT; } @@ -68281,7 +68281,7 @@ OEMCryptoResult wvoec3::Level3_DecryptCENC( nipzhrzp(12) = uqtvdcwf(21) != (*xumlwwbg(0)).buffers.input_data_length; if (!nipzhrzp(12)) goto urzhgrgw; { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "Level3_DecryptCENC(): Sample and subsample lengths do " "not match."); return OEMCrypto_ERROR_INVALID_CONTEXT; @@ -69239,12 +69239,12 @@ OEMCryptoResult wvoec3::Level3_LoadCasECMKeys( OEMCryptoResult wvoec3::Level3_ProductionReady() { return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Idle(OEMCrypto_IdleState uhqndanx, uint32_t xepyuhtd) { - wvutil::Log("", "", 0, wvutil::LOG_INFO, + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "no OEMCrypto activity for some time so entering idle state"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_Wake() { - wvutil::Log("", "", 0, wvutil::LOG_INFO, "OEMCrypto operations resuming"); + wvutil::Log("", "", 0, wvutil::CDM_LOG_INFO, "OEMCrypto operations resuming"); return OEMCrypto_SUCCESS; } OEMCryptoResult wvoec3::Level3_ReuseUsageEntry(OEMCrypto_SESSION bripfgai, diff --git a/libwvdrmengine/manifest_android.hardware.drm-service.widevine.xml b/libwvdrmengine/manifest_android.hardware.drm-service.widevine.xml new file mode 100644 index 00000000..6d68ff35 --- /dev/null +++ b/libwvdrmengine/manifest_android.hardware.drm-service.widevine.xml @@ -0,0 +1,23 @@ + + + + + android.hardware.drm + 1 + ICryptoFactory/widevine + IDrmFactory/widevine + + diff --git a/libwvdrmengine/mediacrypto/Android.bp b/libwvdrmengine/mediacrypto/Android.bp index 5f840200..c66eb004 100644 --- a/libwvdrmengine/mediacrypto/Android.bp +++ b/libwvdrmengine/mediacrypto/Android.bp @@ -64,5 +64,48 @@ cc_library_static { cflags: ["-Wthread-safety"], proprietary: true, - +} + +// Builds libwvdrmcryptoplugin_aidl +// +cc_library_static { + name: "libwvdrmcryptoplugin_aidl", + + srcs: ["aidl_src/WVCryptoPlugin.cpp"], + + include_dirs: [ + "frameworks/av/include", + "frameworks/native/include", + "vendor/widevine/libwvdrmengine/cdm/core/include", + "vendor/widevine/libwvdrmengine/cdm/include", + "vendor/widevine/libwvdrmengine/cdm/metrics/include", + "vendor/widevine/libwvdrmengine/cdm/util/include", + "vendor/widevine/libwvdrmengine/aidl_include", + "vendor/widevine/libwvdrmengine/include", + "vendor/widevine/libwvdrmengine/mediacrypto/aidl_include", + "vendor/widevine/libwvdrmengine/oemcrypto/include", + ], + + header_libs: [ + "libstagefright_headers", + "libutils_headers", + ], + + static_libs: [ + "android.hardware.common-V2-ndk", + "libaidlcommonsupport", + "libcdm_protos", + ], + + shared_libs: [ + "android.hardware.drm-V1-ndk", + "libbase", + "libcrypto", + "libhwbinder", + "liblog", + ], + + cflags: ["-Wthread-safety"], + + proprietary: true, } diff --git a/libwvdrmengine/mediacrypto/aidl_include/WVCryptoPlugin.h b/libwvdrmengine/mediacrypto/aidl_include/WVCryptoPlugin.h new file mode 100644 index 00000000..b1da2eec --- /dev/null +++ b/libwvdrmengine/mediacrypto/aidl_include/WVCryptoPlugin.h @@ -0,0 +1,93 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_CRYPTO_PLUGIN_H_ +#define WV_CRYPTO_PLUGIN_H_ + +#include +#include +#include +#include + +#include + +#include "WVTypes.h" +#include "log.h" +#include "wv_content_decryption_module.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +struct SharedBufferBase { + uint8_t* mBase; + int64_t mSize; + SharedBufferBase(const ::aidl::android::hardware::common::Ashmem& mem); + ~SharedBufferBase(); +}; + +struct WVCryptoPlugin : public ::aidl::android::hardware::drm::BnCryptoPlugin { + WVCryptoPlugin(const void* data, size_t size, + const ::android::sp& cdm); + virtual ~WVCryptoPlugin(); + + ::ndk::ScopedAStatus requiresSecureDecoderComponent( + const std::string& in_mime, bool* _aidl_return) override; + + ::ndk::ScopedAStatus notifyResolution(int32_t in_width, + int32_t in_height) override; + + ::ndk::ScopedAStatus setMediaDrmSession( + const std::vector& in_sessionId) override; + + ::ndk::ScopedAStatus setSharedBufferBase( + const ::aidl::android::hardware::common::Ashmem& in_base, + int32_t in_bufferId) override; + + ::ndk::ScopedAStatus decrypt( + bool in_secure, const std::vector& in_keyId, + const std::vector& in_iv, + ::aidl::android::hardware::drm::Mode in_mode, + const ::aidl::android::hardware::drm::Pattern& in_pattern, + const std::vector<::aidl::android::hardware::drm::SubSample>& + in_subSamples, + const ::aidl::android::hardware::drm::SharedBuffer& in_source, + int64_t in_offset, + const ::aidl::android::hardware::drm::DestinationBuffer& in_destination, + ::aidl::android::hardware::drm::DecryptResult* _aidl_return) override; + + ::ndk::ScopedAStatus getLogMessages( + std::vector<::aidl::android::hardware::drm::LogMessage>* _aidl_return) + override; + + private: + WVDRM_DISALLOW_COPY_AND_ASSIGN_AND_NEW(WVCryptoPlugin); + + // List this field first so it is destructed last; ensure logging uid + // is cleared right before plugin is destructed. + wvutil::LoggingUidSetter mLoggingUidSetter; + + wvcdm::CdmSessionId mSessionId; + std::map> mSharedBufferMap + GUARDED_BY(mSharedBufferLock); + + ::android::sp const mCDM; + uint32_t mUserId; + + ::aidl::android::hardware::drm::Status attemptDecrypt( + const wvcdm::CdmDecryptionParametersV16& params, + bool haveEncryptedSubsamples, std::string* errorDetailMsg); + + std::mutex mSharedBufferLock; +}; + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm + +#endif // WV_CRYPTO_PLUGIN_H_ diff --git a/libwvdrmengine/mediacrypto/aidl_src/WVCryptoPlugin.cpp b/libwvdrmengine/mediacrypto/aidl_src/WVCryptoPlugin.cpp new file mode 100644 index 00000000..be00c3cf --- /dev/null +++ b/libwvdrmengine/mediacrypto/aidl_src/WVCryptoPlugin.cpp @@ -0,0 +1,350 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +//#define LOG_NDEBUG 0 +#define LOG_TAG "WVCdm" +#include "WVCryptoPlugin.h" + +#include +#include +#include + +#include +#include + +#include "OEMCryptoCENC.h" +#include "Utils.h" +#include "WVErrors.h" +#include "log.h" +#include "mapErrors-inl.h" +#include "openssl/sha.h" +#include "wv_cdm_constants.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +using ::aidl::android::hardware::drm::BufferType; +using ::aidl::android::hardware::drm::Mode; +using ::aidl::android::hardware::drm::SharedBuffer; +using ::aidl::android::hardware::drm::Status; +using ::aidl::android::hardware::drm::SubSample; + +using wvcdm::CdmDecryptionParametersV16; +using wvcdm::CdmDecryptionSample; +using wvcdm::CdmDecryptionSubsample; +using wvcdm::CdmQueryMap; +using wvcdm::CdmResponseType; +using wvcdm::CdmSessionId; +using wvcdm::KeyId; +using wvcdm::WvContentDecryptionModule; + +WVCryptoPlugin::WVCryptoPlugin( + const void* data, size_t size, + const ::android::sp& cdm) + : mCDM(cdm), mUserId(wvutil::UNKNOWN_UID) { + if (data != nullptr) { + mSessionId.assign(static_cast(data), size); + } + if (!mCDM->IsOpenSession(mSessionId)) { + mSessionId.clear(); + } else { + mCDM->GetSessionUserId(mSessionId, &mUserId); + } +} + +WVCryptoPlugin::~WVCryptoPlugin() { + if (wvutil::UNKNOWN_UID != mUserId) { + wvutil::SetLoggingUid(mUserId); + } +} + +SharedBufferBase::SharedBufferBase( + const ::aidl::android::hardware::common::Ashmem& mem) + : mBase(nullptr), mSize(mem.size) { + if (mem.fd.get() < 0) { + return; + } + auto addr = mmap(nullptr, mem.size, PROT_READ | PROT_WRITE, MAP_SHARED, + mem.fd.get(), 0); + if (addr == MAP_FAILED) { + ALOGE("mmap err: fd %d; errno %s", mem.fd.get(), strerror(errno)); + } else { + mBase = static_cast(addr); + } +} + +SharedBufferBase::~SharedBufferBase() { + if (munmap(mBase, mSize)) { + ALOGE("munmap err: base %p; errno %s", mBase, strerror(errno)); + } +} + +::ndk::ScopedAStatus WVCryptoPlugin::requiresSecureDecoderComponent( + const std::string& in_mime, bool* _aidl_return) { + if (!strncasecmp(in_mime.c_str(), "video/", 6)) { + // Type is video, so query CDM to see if we require a secure decoder. + CdmQueryMap status; + + CdmResponseType res = mCDM->QuerySessionStatus(mSessionId, &status); + + if (!::wvdrm::isCdmResponseTypeSuccess(res)) { + ALOGE("Error querying CDM status: %u", res); + *_aidl_return = false; + return ::ndk::ScopedAStatus::ok(); + } + + *_aidl_return = status[wvcdm::QUERY_KEY_SECURITY_LEVEL] == + wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1; + return ::ndk::ScopedAStatus::ok(); + } else { + // Type is not video, so never require a secure decoder. + *_aidl_return = false; + return ::ndk::ScopedAStatus::ok(); + } +} + +::ndk::ScopedAStatus WVCryptoPlugin::notifyResolution(int32_t in_width, + int32_t in_height) { + mCDM->NotifyResolution(mSessionId, in_width, in_height); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVCryptoPlugin::setMediaDrmSession( + const std::vector& in_sessionId) { + if (in_sessionId.size() == 0) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCDM->IsOpenSession(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } else { + mSessionId = cdmSessionId; + return toNdkScopedAStatus(Status::OK); + } +} + +::ndk::ScopedAStatus WVCryptoPlugin::setSharedBufferBase( + const ::aidl::android::hardware::common::Ashmem& in_base, + int32_t in_bufferId) { + std::lock_guard shared_buffer_lock(mSharedBufferLock); + + mSharedBufferMap[in_bufferId] = std::make_shared(in_base); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVCryptoPlugin::decrypt( + bool in_secure, const std::vector& in_keyId, + const std::vector& in_iv, + ::aidl::android::hardware::drm::Mode in_mode, + const ::aidl::android::hardware::drm::Pattern& in_pattern, + const std::vector& in_subSamples, + const ::aidl::android::hardware::drm::SharedBuffer& in_source, + int64_t in_offset, + const ::aidl::android::hardware::drm::DestinationBuffer& in_destination, + ::aidl::android::hardware::drm::DecryptResult* _aidl_return) { + _aidl_return->bytesWritten = 0; + + uint8_t* srcPtr = nullptr; + void* destPtr = nullptr; + // Convert parameters to the form the CDM wishes to consume them in. + const KeyId cryptoKey(reinterpret_cast(in_keyId.data()), + wvcdm::KEY_ID_SIZE); + + // start scope for lock_guard + { + std::lock_guard lock(mSharedBufferLock); + if (mSharedBufferMap.find(in_source.bufferId) == mSharedBufferMap.end()) { + _aidl_return->detailedError = "source decrypt buffer base not set"; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + if (in_destination.type == BufferType::SHARED_MEMORY) { + const SharedBuffer& dest = in_destination.nonsecureMemory; + if (mSharedBufferMap.find(dest.bufferId) == mSharedBufferMap.end()) { + _aidl_return->detailedError = "destination decrypt buffer base not set"; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + } + + if (in_mode != Mode::UNENCRYPTED && in_mode != Mode::AES_CTR && + in_mode != Mode::AES_CBC) { + _aidl_return->detailedError = + "The requested encryption mode is not supported by Widevine CDM."; + return toNdkScopedAStatus(Status::BAD_VALUE); + } else if (in_mode == Mode::AES_CTR && + (in_pattern.encryptBlocks != 0 || in_pattern.skipBlocks != 0)) { + _aidl_return->detailedError = + "The 'cens' schema is not supported by Widevine CDM."; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + auto src = mSharedBufferMap[in_source.bufferId]; + if (src->mBase == nullptr) { + _aidl_return->detailedError = "source is a nullptr"; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + size_t totalSrcSize = 0; + if (__builtin_add_overflow(in_source.offset, in_offset, &totalSrcSize) || + __builtin_add_overflow(totalSrcSize, in_source.size, &totalSrcSize) || + totalSrcSize > src->mSize) { + android_errorWriteLog(0x534e4554, "176496160"); + _aidl_return->detailedError = "invalid source buffer size"; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + srcPtr = src->mBase + in_source.offset + in_offset; + + if (in_destination.type == BufferType::SHARED_MEMORY) { + const SharedBuffer& destBuffer = in_destination.nonsecureMemory; + auto dest = mSharedBufferMap[destBuffer.bufferId]; + if (dest->mBase == nullptr) { + _aidl_return->detailedError = "destination is a nullptr"; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + size_t totalDstSize = 0; + if (__builtin_add_overflow(destBuffer.offset, destBuffer.size, + &totalDstSize) || + totalDstSize > dest->mSize) { + android_errorWriteLog(0x534e4554, "176444622"); + _aidl_return->detailedError = "invalid buffer size"; + return toNdkScopedAStatus(Status::ERROR_DRM_FRAME_TOO_LARGE); + } + destPtr = static_cast(dest->mBase + + in_destination.nonsecureMemory.offset); + } else if (in_destination.type == BufferType::NATIVE_HANDLE) { + native_handle_t* handle = + android::makeFromAidl(in_destination.secureMemory); + destPtr = static_cast(handle); + } + } // lock_guard scope + + // Set up the decrypt params + CdmDecryptionParametersV16 params; + params.key_id = cryptoKey; + params.is_secure = in_secure; + if (in_mode == Mode::AES_CTR) { + params.cipher_mode = wvcdm::kCipherModeCtr; + } else if (in_mode == Mode::AES_CBC) { + params.cipher_mode = wvcdm::kCipherModeCbc; + } + params.pattern.encrypt_blocks = in_pattern.encryptBlocks; + params.pattern.skip_blocks = in_pattern.skipBlocks; + + // Set up the sample + // Android's API only supports one at a time + params.samples.emplace_back(); + CdmDecryptionSample& sample = params.samples.back(); + sample.encrypt_buffer = srcPtr; + sample.decrypt_buffer = destPtr; + sample.decrypt_buffer_offset = 0; + sample.iv = in_iv; + + // Set up the subsamples + // We abuse std::transform() here to also do some side-effects: Tallying the + // total size of the sample and checking if any of the data is protected. + size_t totalSize = 0; + bool hasProtectedData = false; + sample.subsamples.reserve(in_subSamples.size()); + std::transform( + in_subSamples.data(), in_subSamples.data() + in_subSamples.size(), + std::back_inserter(sample.subsamples), + [&](const SubSample& subSample) -> CdmDecryptionSubsample { + totalSize += + subSample.numBytesOfClearData + subSample.numBytesOfEncryptedData; + hasProtectedData |= subSample.numBytesOfEncryptedData > 0; + return CdmDecryptionSubsample(subSample.numBytesOfClearData, + subSample.numBytesOfEncryptedData); + }); + + sample.encrypt_buffer_length = totalSize; + sample.decrypt_buffer_size = totalSize; + + if (in_mode == Mode::UNENCRYPTED && hasProtectedData) { + _aidl_return->detailedError = + "Protected ranges found in allegedly clear data."; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + // Decrypt + std::string errorDetailMsg; + Status res = attemptDecrypt(params, hasProtectedData, &errorDetailMsg); + if (res != Status::OK) { + _aidl_return->detailedError = errorDetailMsg; + return toNdkScopedAStatus(res); + } + + _aidl_return->bytesWritten = totalSize; + _aidl_return->detailedError = errorDetailMsg; + return toNdkScopedAStatus(Status::OK); +} + +Status WVCryptoPlugin::attemptDecrypt(const CdmDecryptionParametersV16& params, + bool hasProtectedData, + std::string* errorDetailMsg) { + CdmResponseType res = mCDM->DecryptV16(mSessionId, hasProtectedData, params); + + if (::wvdrm::isCdmResponseTypeSuccess(res)) { + return Status::OK; + } else { + ALOGE("Decrypt error in session %s during a sample %s protected data: %d", + mSessionId.c_str(), hasProtectedData ? "with" : "without", res); + switch (res) { + case wvcdm::INSUFFICIENT_CRYPTO_RESOURCES: + errorDetailMsg->assign( + "Error decrypting data: insufficient crypto resources"); + break; + case wvcdm::NEED_KEY: + case wvcdm::KEY_NOT_FOUND_IN_SESSION: + errorDetailMsg->assign( + "Error decrypting data: requested key has not been loaded"); + break; + case wvcdm::DECRYPT_NOT_READY: + errorDetailMsg->assign( + "Error decrypting data: license validity period is in the future"); + break; + case wvcdm::SESSION_NOT_FOUND_FOR_DECRYPT: + errorDetailMsg->assign( + "Error decrypting data: session not found, possibly reclaimed"); + break; + case wvcdm::DECRYPT_ERROR: + errorDetailMsg->assign("Error decrypting data: unspecified error"); + break; + case wvcdm::INSUFFICIENT_OUTPUT_PROTECTION: + case wvcdm::ANALOG_OUTPUT_ERROR: + errorDetailMsg->assign( + "Error decrypting data: insufficient output protection"); + break; + case wvcdm::KEY_PROHIBITED_FOR_SECURITY_LEVEL: + errorDetailMsg->assign( + "Error decrypting data: key prohibited for security level"); + break; + default: + break; + } + + return ::wvdrm::mapCdmResponseType(res); + } +} + +::ndk::ScopedAStatus WVCryptoPlugin::getLogMessages( + std::vector<::aidl::android::hardware::drm::LogMessage>* _aidl_return) { + const std::vector& logs(wvutil::g_logbuf.getLogs()); + std::vector<::aidl::android::hardware::drm::LogMessage> msgs; + for (auto log : logs) { + msgs.push_back({log.time_ms_, ::wvdrm::toAidlLogPriority(log.priority_), + log.message_}); + } + *_aidl_return = msgs; + return ::wvdrm::toNdkScopedAStatus(Status::OK); +} + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm diff --git a/libwvdrmengine/mediacrypto/test/Android.mk b/libwvdrmengine/mediacrypto/test/Android.mk index 979fe75b..77d6aeda 100644 --- a/libwvdrmengine/mediacrypto/test/Android.mk +++ b/libwvdrmengine/mediacrypto/test/Android.mk @@ -21,7 +21,7 @@ LOCAL_C_INCLUDES := \ LOCAL_STATIC_LIBRARIES := \ libcdm \ libcdm_protos \ - libcdm_utils \ + libcdm_utils_hidl \ libjsmn \ libgmock \ libgmock_main \ diff --git a/libwvdrmengine/mediadrm/Android.bp b/libwvdrmengine/mediadrm/Android.bp index ef3ee364..091e5b0e 100644 --- a/libwvdrmengine/mediadrm/Android.bp +++ b/libwvdrmengine/mediadrm/Android.bp @@ -66,5 +66,48 @@ cc_library_static { ], proprietary: true, - +} + +// Builds libwvdrmdrmplugin_aidl +// +cc_library_static { + name: "libwvdrmdrmplugin_aidl", + + srcs: [ + "aidl_src/WVDrmPlugin.cpp", + "aidl_src/WVGenericCryptoInterface.cpp", + "aidl_src/wv_metrics_adapter.cpp", + ], + + include_dirs: [ + "frameworks/av/include", + "frameworks/native/include", + "vendor/widevine/libwvdrmengine/cdm/core/include", + "vendor/widevine/libwvdrmengine/cdm/include", + "vendor/widevine/libwvdrmengine/cdm/metrics/include", + "vendor/widevine/libwvdrmengine/cdm/util/include", + "vendor/widevine/libwvdrmengine/aidl_include", + "vendor/widevine/libwvdrmengine/include", + "vendor/widevine/libwvdrmengine/mediadrm/aidl_include", + "vendor/widevine/libwvdrmengine/oemcrypto/include", + ], + + header_libs: [ + "libstagefright_headers", + "libstagefright_foundation_headers", + "libutils_headers", + ], + + static_libs: ["libcdm_protos"], + + shared_libs: [ + "libbase", + "libbinder", + "libbinder_ndk", + "libcrypto", + "liblog", + "android.hardware.drm-V1-ndk", + ], + + proprietary: true, } diff --git a/libwvdrmengine/mediadrm/aidl_include/WVDrmPlugin.h b/libwvdrmengine/mediadrm/aidl_include/WVDrmPlugin.h new file mode 100644 index 00000000..ae44f496 --- /dev/null +++ b/libwvdrmengine/mediadrm/aidl_include/WVDrmPlugin.h @@ -0,0 +1,465 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_DRM_PLUGIN_H_ +#define WV_DRM_PLUGIN_H_ + +#include +#include +#include +#include + +#include +#include + +#include "OEMCryptoCENC.h" +#include "WVGenericCryptoInterface.h" +#include "WVTypes.h" +#include "cdm_client_property_set.h" +#include "cdm_identifier.h" +#include "log.h" +#include "wv_cdm_event_listener.h" +#include "wv_content_decryption_module.h" + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +using ::aidl::android::hardware::drm::Status; + +using wvcdm::CdmIdentifier; +using wvcdm::CdmKeyStatusMap; +using wvcdm::CdmResponseType; +using wvcdm::CdmSessionId; +using wvcdm::WvContentDecryptionModule; + +const OEMCrypto_Algorithm kInvalidCryptoAlgorithm = + static_cast(-1); + +struct WVDrmPlugin : public ::aidl::android::hardware::drm::BnDrmPlugin, + wvcdm::WvCdmEventListener { + WVDrmPlugin(const android::sp& cdm, + const std::string& appPackageName, + WVGenericCryptoInterface* crypto, bool useSpoid); + + virtual ~WVDrmPlugin(); + + void Close(); + + ::ndk::ScopedAStatus closeSession( + const std::vector& in_sessionId) override; + ::ndk::ScopedAStatus decrypt(const std::vector& in_sessionId, + const std::vector& in_keyId, + const std::vector& in_input, + const std::vector& in_iv, + std::vector* _aidl_return) override; + ::ndk::ScopedAStatus encrypt(const std::vector& in_sessionId, + const std::vector& in_keyId, + const std::vector& in_input, + const std::vector& in_iv, + std::vector* _aidl_return) override; + ::ndk::ScopedAStatus getHdcpLevels( + ::aidl::android::hardware::drm::HdcpLevels* _aidl_return) override; + ::ndk::ScopedAStatus getKeyRequest( + const std::vector& in_scope, + const std::vector& in_initData, const std::string& in_mimeType, + ::aidl::android::hardware::drm::KeyType in_keyType, + const std::vector<::aidl::android::hardware::drm::KeyValue>& + in_optionalParameters, + ::aidl::android::hardware::drm::KeyRequest* _aidl_return) override; + ::ndk::ScopedAStatus getLogMessages( + std::vector<::aidl::android::hardware::drm::LogMessage>* _aidl_return) + override; + ::ndk::ScopedAStatus getMetrics( + std::vector<::aidl::android::hardware::drm::DrmMetricGroup>* _aidl_return) + override; + ::ndk::ScopedAStatus getNumberOfSessions( + ::aidl::android::hardware::drm::NumberOfSessions* _aidl_return) override; + ::ndk::ScopedAStatus getOfflineLicenseKeySetIds( + std::vector<::aidl::android::hardware::drm::KeySetId>* _aidl_return) + override; + ::ndk::ScopedAStatus getOfflineLicenseState( + const ::aidl::android::hardware::drm::KeySetId& in_keySetId, + ::aidl::android::hardware::drm::OfflineLicenseState* _aidl_return) + override; + ::ndk::ScopedAStatus getPropertyByteArray( + const std::string& in_propertyName, + std::vector* _aidl_return) override; + ::ndk::ScopedAStatus getPropertyString(const std::string& in_propertyName, + std::string* _aidl_return) override; + ::ndk::ScopedAStatus getProvisionRequest( + const std::string& in_certificateType, + const std::string& in_certificateAuthority, + ::aidl::android::hardware::drm::ProvisionRequest* _aidl_return) override; + ::ndk::ScopedAStatus getSecureStop( + const ::aidl::android::hardware::drm::SecureStopId& in_secureStopId, + ::aidl::android::hardware::drm::SecureStop* _aidl_return) override; + ::ndk::ScopedAStatus getSecureStopIds( + std::vector<::aidl::android::hardware::drm::SecureStopId>* _aidl_return) + override; + ::ndk::ScopedAStatus getSecureStops( + std::vector<::aidl::android::hardware::drm::SecureStop>* _aidl_return) + override; + ::ndk::ScopedAStatus getSecurityLevel( + const std::vector& in_sessionId, + ::aidl::android::hardware::drm::SecurityLevel* _aidl_return) override; + ::ndk::ScopedAStatus openSession( + ::aidl::android::hardware::drm::SecurityLevel in_securityLevel, + std::vector* _aidl_return) override; + ::ndk::ScopedAStatus provideKeyResponse( + const std::vector& in_scope, + const std::vector& in_response, + ::aidl::android::hardware::drm::KeySetId* _aidl_return) override; + ::ndk::ScopedAStatus provideProvisionResponse( + const std::vector& in_response, + ::aidl::android::hardware::drm::ProvideProvisionResponseResult* + _aidl_return) override; + ::ndk::ScopedAStatus queryKeyStatus( + const std::vector& in_sessionId, + std::vector<::aidl::android::hardware::drm::KeyValue>* _aidl_return) + override; + ::ndk::ScopedAStatus releaseAllSecureStops() override; + ::ndk::ScopedAStatus releaseSecureStop( + const ::aidl::android::hardware::drm::SecureStopId& in_secureStopId) + override; + ::ndk::ScopedAStatus releaseSecureStops( + const ::aidl::android::hardware::drm::OpaqueData& in_ssRelease) override; + ::ndk::ScopedAStatus removeAllSecureStops() override; + ::ndk::ScopedAStatus removeKeys( + const std::vector& in_sessionId) override; + ::ndk::ScopedAStatus removeOfflineLicense( + const ::aidl::android::hardware::drm::KeySetId& in_keySetId) override; + ::ndk::ScopedAStatus removeSecureStop( + const ::aidl::android::hardware::drm::SecureStopId& in_secureStopId) + override; + ::ndk::ScopedAStatus requiresSecureDecoder( + const std::string& in_mime, + ::aidl::android::hardware::drm::SecurityLevel in_level, + bool* _aidl_return) override; + ::ndk::ScopedAStatus requiresSecureDecoderDefault( + const std::string& in_mime, bool* _aidl_return) override; + ::ndk::ScopedAStatus restoreKeys( + const std::vector& in_sessionId, + const ::aidl::android::hardware::drm::KeySetId& in_keySetId) override; + ::ndk::ScopedAStatus setCipherAlgorithm( + const std::vector& in_sessionId, + const std::string& in_algorithm) override; + ::ndk::ScopedAStatus setListener( + const std::shared_ptr<::aidl::android::hardware::drm::IDrmPluginListener>& + in_listener) override; + ::ndk::ScopedAStatus setMacAlgorithm( + const std::vector& in_sessionId, + const std::string& in_algorithm) override; + ::ndk::ScopedAStatus setPlaybackId(const std::vector& in_sessionId, + const std::string& in_playbackId) override; + ::ndk::ScopedAStatus setPropertyByteArray( + const std::string& in_propertyName, + const std::vector& in_value) override; + ::ndk::ScopedAStatus setPropertyString(const std::string& in_propertyName, + const std::string& in_value) override; + ::ndk::ScopedAStatus sign(const std::vector& in_sessionId, + const std::vector& in_keyId, + const std::vector& in_message, + std::vector* _aidl_return) override; + ::ndk::ScopedAStatus signRSA(const std::vector& in_sessionId, + const std::string& in_algorithm, + const std::vector& in_message, + const std::vector& in_wrappedkey, + std::vector* _aidl_return) override; + ::ndk::ScopedAStatus verify(const std::vector& in_sessionId, + const std::vector& in_keyId, + const std::vector& in_message, + const std::vector& in_signature, + bool* _aidl_return) override; + + // The following methods do not use hidl interface, it is used internally. + virtual Status unprovisionDevice(); + + virtual void OnSessionRenewalNeeded(const CdmSessionId& cdmSessionId); + virtual void OnSessionKeysChange(const CdmSessionId& cdmSessionId, + const CdmKeyStatusMap& cdmKeysStatus, + bool hasNewUsableKey); + virtual void OnExpirationUpdate(const CdmSessionId& cdmSessionId, + int64_t newExpiryTimeSeconds); + virtual void OnSessionLostState(const CdmSessionId& cdmSessionId); + + private: + WVDRM_DISALLOW_COPY_AND_ASSIGN_AND_NEW(WVDrmPlugin); + + // List this field first so it is destructed last; ensure logging uid + // is cleared right before plugin is destructed. + wvutil::LoggingUidSetter mLoggingUidSetter; + + struct CryptoSession { + public: + CryptoSession() + : mOecSessionId(-1), + mCipherAlgorithm(kInvalidCryptoAlgorithm), + mMacAlgorithm(kInvalidCryptoAlgorithm) {} + + CryptoSession(OEMCrypto_SESSION sessionId) + : mOecSessionId(sessionId), + mCipherAlgorithm(kInvalidCryptoAlgorithm), + mMacAlgorithm(kInvalidCryptoAlgorithm) {} + + OEMCrypto_SESSION oecSessionId() const { return mOecSessionId; } + + OEMCrypto_Algorithm cipherAlgorithm() const { return mCipherAlgorithm; } + + void setCipherAlgorithm(OEMCrypto_Algorithm newAlgorithm) { + mCipherAlgorithm = newAlgorithm; + } + + OEMCrypto_Algorithm macAlgorithm() const { return mMacAlgorithm; } + + void setMacAlgorithm(OEMCrypto_Algorithm newAlgorithm) { + mMacAlgorithm = newAlgorithm; + } + + private: + OEMCrypto_SESSION mOecSessionId; + OEMCrypto_Algorithm mCipherAlgorithm; + OEMCrypto_Algorithm mMacAlgorithm; + }; + + class WVClientPropertySet : public wvcdm::CdmClientPropertySet { + public: + WVClientPropertySet() + : mUsePrivacyMode(false), + mShareKeys(false), + mSessionSharingId(0), + mUseAtscMode(false) {} + + virtual ~WVClientPropertySet() {} + + virtual const std::string& security_level() const { return mSecurityLevel; } + + void set_security_level(const std::string& securityLevel) { + mSecurityLevel = securityLevel; + } + + virtual bool use_privacy_mode() const { return mUsePrivacyMode; } + + void set_use_privacy_mode(bool usePrivacyMode) { + mUsePrivacyMode = usePrivacyMode; + } + + virtual const std::string& service_certificate() const { + return mServiceCertificate; + } + + virtual void set_service_certificate( + const std::string& serviceCertificate) { + mServiceCertificate = serviceCertificate; + } + + virtual const std::string& device_provisioning_service_certificate() const { + // Android does not support service certificates for provisioning. + return mEmptyString; + } + + virtual void set_device_provisioning_service_certificate( + const std::string&) { + // Ignore. Android does not support service certificates for provisioning + // TODO(b/69562876): Android SHOULD support service cert for provisioning + } + + virtual bool is_session_sharing_enabled() const { return mShareKeys; } + + void set_is_session_sharing_enabled(bool shareKeys) { + mShareKeys = shareKeys; + } + + virtual uint32_t session_sharing_id() const { return mSessionSharingId; } + + virtual void set_session_sharing_id(uint32_t id) { mSessionSharingId = id; } + + virtual const std::string& app_id() const { return mAppId; } + + void set_app_id(const std::string& appId) { mAppId = appId; } + + virtual bool use_atsc_mode() const { return mUseAtscMode; } + + void set_use_atsc_mode(bool useAtscMode) { mUseAtscMode = useAtscMode; } + + private: + DISALLOW_EVIL_CONSTRUCTORS(WVClientPropertySet); + + std::string mSecurityLevel; + bool mUsePrivacyMode; + std::string mServiceCertificate; + bool mShareKeys; + uint32_t mSessionSharingId; + std::string mAppId; + bool mUseAtscMode; + const std::string mEmptyString; + } mPropertySet; + + class CdmIdentifierBuilder { + public: + CdmIdentifierBuilder(bool useSpoid, const WVDrmPlugin& parent, + const std::string& appPackageName); + + // Fills in the passed-in struct with the CDM Identifier for the current + // combination of Origin, Application, and Device. This is needed by some + // calls into the CDM in order to identify which CDM instance should receive + // the call. Calling this will seal the CDM Identifier Builder, thus making + // it an error to change the origin. + Status getCdmIdentifier(CdmIdentifier* identifier); + + // Gets the application-safe device-unique ID. On non-SPOID devices, this is + // the device-unique ID from OEMCrypto. On SPOID devices, this is the SPOID. + // On SPOID devices, calling this will seal the CDM Identifier Builder, thus + // making it an error to change the origin. + Status getDeviceUniqueId(std::string* id); + Status getProvisioningUniqueId(std::string* id); + + const std::string& origin() const { return mCdmIdentifier.origin; } + bool set_origin(const std::string& id); + + // This sets the app package name to allow apps to access ATSC licenses + bool set_use_atsc_mode(bool enable); + + // Indicates whether the builder can still be modified. This returns false + // until a call to getCdmIdentifier. + bool is_sealed() { return mIsIdentifierSealed; } + + uint32_t user_id() const { return mCdmIdentifier.user_id; } + + private: + WVDRM_DISALLOW_COPY_AND_ASSIGN(CdmIdentifierBuilder); + + CdmIdentifier mCdmIdentifier; + bool mIsIdentifierSealed; + + bool mUseSpoid; + std::string mAppPackageName; + const WVDrmPlugin& mParent; + + Status calculateSpoid(); + Status calculateSpoid(const std::string& deviceID, std::string* spoid); + + // Gets the device-unique ID from OEMCrypto. This must be private, since + // this value must not be exposed to applications on SPOID devices. Code + // outside this class should use getDeviceUniqueId() to get the + // application-safe device-unique ID. + Status getOemcryptoDeviceId(std::string* id); + Status getOemcryptoDeviceId(wvcdm::RequestedSecurityLevel securityLevel, + std::string* id); + + // The unique identifier is meant to ensure that two clients with the + // same spoid, origin and app package name still get different cdm engine + // instances. This is a stepping stone to simplifying the implementation. + // Note that we do not have a lock or mutex around this object. We assume + // that locking is handled external to this object. + uint32_t getNextUniqueId(); + } mCdmIdentifierBuilder; + + // Properly close plugins on SIGTERM then exit + class Terminator { + public: + static void Register(WVDrmPlugin* plugin) { instance().DoRegister(plugin); } + static void Forget(WVDrmPlugin* plugin) { instance().DoForget(plugin); } + static void Terminate(int /*signal*/) { instance().DoTerminate(); } + + private: + WVDRM_DISALLOW_COPY_AND_ASSIGN(Terminator); + + Terminator() { signal(SIGTERM, Terminate); } + + static Terminator& instance() { + static Terminator instance; + return instance; + } + + void DoRegister(WVDrmPlugin* plugin) { + android::Mutex::Autolock lock(mLock); + mPlugins.push_back(plugin); + } + + void DoForget(WVDrmPlugin* plugin) { + android::Mutex::Autolock lock(mLock); + mPlugins.remove(plugin); + } + + void DoTerminate() { + android::Mutex::Autolock lock(mLock); + for_each(mPlugins.begin(), mPlugins.end(), + [](WVDrmPlugin* plugin) { plugin->Close(); }); + exit(0); + } + + std::list mPlugins; + android::Mutex mLock; + }; + + android::sp const mCDM; + WVGenericCryptoInterface* mCrypto; + std::map mCryptoSessions; + std::shared_ptr<::aidl::android::hardware::drm::IDrmPluginListener> mListener; + + std::string mProvisioningServiceCertificate; + + wvcdm::CdmSessionId mDecryptHashSessionId; + + std::string mAppPackageName; + + Status queryProperty(const std::string& property, + std::string& stringValue) const; + + Status queryProperty(wvcdm::RequestedSecurityLevel securityLevel, + const std::string& property, + std::string& stringValue) const; + + Status queryProperty(const std::string& property, + std::vector& vector_value) const; + + bool isProvisioned(wvcdm::CdmSecurityLevel securityLevel, + const std::string& origin, const std::string& spoid, + bool atsc_mode_enabled) const; + + Status mapAndNotifyOfCdmResponseType(const std::vector& sessionId, + CdmResponseType res); + + void notifyOfCdmResponseType(const std::vector& sessionId, + CdmResponseType res); + + Status mapAndNotifyOfOEMCryptoResult(const std::vector& sessionId, + OEMCryptoResult res); + + Status mapOEMCryptoResult(OEMCryptoResult res); + + ::aidl::android::hardware::drm::SecurityLevel mapSecurityLevel( + const std::string& level); + + wvcdm::RequestedSecurityLevel getRequestedSecurityLevel() const; + + Status openSessionCommon(std::vector& sessionId); + + bool initDataResemblesPSSH(const std::vector& initData); + + Status unprovision(const CdmIdentifier& identifier); + + void sendEvent(::aidl::android::hardware::drm::EventType in_eventType, + const std::vector& in_sessionId, + const std::vector& in_data); + void sendExpirationUpdate(const std::vector& in_sessionId, + int64_t in_expiryTimeInMS); + void sendKeysChange( + const std::vector& in_sessionId, + const std::vector<::aidl::android::hardware::drm::KeyStatus>& + in_keyStatusList, + bool in_hasNewUsableKey); + void sendSessionLostState(const std::vector& in_sessionId); +}; + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm + +#endif // WV_DRM_PLUGIN_H_ diff --git a/libwvdrmengine/mediadrm/aidl_include/WVGenericCryptoInterface.h b/libwvdrmengine/mediadrm/aidl_include/WVGenericCryptoInterface.h new file mode 100644 index 00000000..d4712779 --- /dev/null +++ b/libwvdrmengine/mediadrm/aidl_include/WVGenericCryptoInterface.h @@ -0,0 +1,94 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_GENERIC_CRYPTO_INTERFACE_H_ +#define WV_GENERIC_CRYPTO_INTERFACE_H_ + +#include + +#include + +#include "OEMCryptoCENC.h" +#include "media/stagefright/foundation/ABase.h" + +namespace wvdrm { + +class WVGenericCryptoInterface { + public: + WVGenericCryptoInterface() {} + virtual ~WVGenericCryptoInterface() {} + + virtual OEMCryptoResult selectKey(const OEMCrypto_SESSION session, + const uint8_t* key_id, + size_t key_id_length) { + return OEMCrypto_SelectKey(session, key_id, key_id_length, + OEMCrypto_CipherMode_CBC); + } + + virtual OEMCryptoResult encrypt(OEMCrypto_SESSION session, + const uint8_t* in_buffer, + size_t buffer_length, const uint8_t* iv, + OEMCrypto_Algorithm algorithm, + uint8_t* out_buffer) { + return OEMCrypto_Generic_Encrypt(session, in_buffer, buffer_length, iv, + algorithm, out_buffer); + } + + virtual OEMCryptoResult decrypt(OEMCrypto_SESSION session, + const uint8_t* in_buffer, + size_t buffer_length, const uint8_t* iv, + OEMCrypto_Algorithm algorithm, + uint8_t* out_buffer) { + return OEMCrypto_Generic_Decrypt(session, in_buffer, buffer_length, iv, + algorithm, out_buffer); + } + + virtual OEMCryptoResult sign(OEMCrypto_SESSION session, + const uint8_t* in_buffer, size_t buffer_length, + OEMCrypto_Algorithm algorithm, + uint8_t* signature, size_t* signature_length) { + return OEMCrypto_Generic_Sign(session, in_buffer, buffer_length, algorithm, + signature, signature_length); + } + + virtual OEMCryptoResult verify(OEMCrypto_SESSION session, + const uint8_t* in_buffer, size_t buffer_length, + OEMCrypto_Algorithm algorithm, + const uint8_t* signature, + size_t signature_length) { + return OEMCrypto_Generic_Verify(session, in_buffer, buffer_length, + algorithm, signature, signature_length); + } + + virtual OEMCryptoResult signRSA(const uint8_t* wrapped_rsa_key, + size_t wrapped_rsa_key_length, + const uint8_t* message, size_t message_length, + std::vector& signature, + RSA_Padding_Scheme padding_scheme); + + virtual OEMCryptoResult loadDeviceRSAKey(OEMCrypto_SESSION session, + const uint8_t* wrapped_rsa_key, + size_t wrapped_rsa_key_length) { + return OEMCrypto_LoadDRMPrivateKey(session, OEMCrypto_RSA_Private_Key, + wrapped_rsa_key, wrapped_rsa_key_length); + } + + virtual OEMCryptoResult generateRSASignature( + OEMCrypto_SESSION session, const uint8_t* message, size_t message_length, + uint8_t* signature, size_t* signature_length, + RSA_Padding_Scheme padding_scheme) { + return OEMCrypto_GenerateRSASignature(session, message, message_length, + signature, signature_length, + padding_scheme); + } + + private: + DISALLOW_EVIL_CONSTRUCTORS(WVGenericCryptoInterface); +}; + +} // namespace wvdrm + +#endif // WV_GENERIC_CRYPTO_INTERFACE_H_ diff --git a/libwvdrmengine/mediadrm/aidl_include/wv_metrics_adapter.h b/libwvdrmengine/mediadrm/aidl_include/wv_metrics_adapter.h new file mode 100644 index 00000000..3f5a11a2 --- /dev/null +++ b/libwvdrmengine/mediadrm/aidl_include/wv_metrics_adapter.h @@ -0,0 +1,108 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#ifndef WV_METRICS_ADAPTER_H_ +#define WV_METRICS_ADAPTER_H_ + +#include + +#include + +#include "wv_metrics.pb.h" + +namespace wvcdm { + +class WvMetricsAdapter; + +// This class is used to convert from the metrics.proto format for metrics +// to the format specified in the aidl.android.hardware.drm DrmMetricGroup +// type. This class converts the common metric types into a single group. +// +// Example: +// drm_metrics::DistributionMetric distribution; +// distribution.set_operation_count(1); +// WvMetricsGroupBuilder builder; +// builder.AddDistributions("test distribution", { distribution }); +// +// DrmMetricGroup group = builder.Build(); +class WvMetricsGroupBuilder { + public: + // Adds a group of distributions with the given base name. + void AddDistributions( + const std::string& name, + const google::protobuf::RepeatedPtrField& + distributions); + + // Adds a group of counter metrics with the given base name. + void AddCounters( + const std::string& name, + const google::protobuf::RepeatedPtrField& + counters); + + // Adds a value metric. + void AddValue(const std::string& name, + const drm_metrics::ValueMetric& value_or_error); + + // Builds the metric group containing all of the previously added metrics. + ::aidl::android::hardware::drm::DrmMetricGroup Build(); + + private: + friend class WvMetricsAdapter; + std::vector<::aidl::android::hardware::drm::DrmMetric> metrics_; + + WvMetricsGroupBuilder(); + // Adds a distribution with the given name and distribution values. + void AddDistribution(const std::string& name, + const drm_metrics::DistributionMetric& distribution); + // Adds a counter metric + void AddCounter(const std::string& name, + const drm_metrics::CounterMetric& counter); + void AddAttributes( + const drm_metrics::Attributes& attributes_proto, + std::vector<::aidl::android::hardware::drm::DrmMetricNamedValue>* + attributes); +}; + +// This class handles adding the engine and session metric collections. This +// will generate one DrmMetricGroup for each EngineMetric added and one for +// each SessionMetric added. This class also supports a static utility method to +// convert a WvCdmMetrics proto to a vector of DrmMetricGroup instances. +class WvMetricsAdapter { + public: + // Utility method to quickly convert a WvCdmMetrics proto to a DrmMetricGroup + // vector. + static void ToWvMetrics( + const drm_metrics::WvCdmMetrics& proto_metrics, + std::vector<::aidl::android::hardware::drm::DrmMetricGroup>* wv_metrics); + + WvMetricsAdapter(); + ~WvMetricsAdapter(); + + // Adds the EngineMetrics instance to the Adapter. It will be converted and + // stored. The converted metrics can be fetched via GetWvGroupVector. + void AddEngineMetrics( + const drm_metrics::WvCdmMetrics::EngineMetrics& proto_metrics); + + // Adds the SessionMetrics instance to the Adapter. It will be converted and + // stored. The converted metrics can be fetched via GetWvGroupVector. + void AddSessionMetrics( + const drm_metrics::WvCdmMetrics::SessionMetrics& proto_metrics); + + // Returns the converted DrmMetricGroup vector containing all of the + // previously added engine and session metrics collections. + const std::vector<::aidl::android::hardware::drm::DrmMetricGroup> + GetWvGroupVector(); + + private: + void AddCryptoMetrics( + const drm_metrics::WvCdmMetrics::CryptoMetrics& proto_metrics, + WvMetricsGroupBuilder* group_builder); + std::vector<::aidl::android::hardware::drm::DrmMetricGroup> group_vector_; +}; + +} // namespace wvcdm + +#endif // WV_METRICS_ADAPTER_H_ diff --git a/libwvdrmengine/mediadrm/aidl_src/WVDrmPlugin.cpp b/libwvdrmengine/mediadrm/aidl_src/WVDrmPlugin.cpp new file mode 100644 index 00000000..c10c2769 --- /dev/null +++ b/libwvdrmengine/mediadrm/aidl_src/WVDrmPlugin.cpp @@ -0,0 +1,2163 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +//#define LOG_NDEBUG 0 +#define LOG_TAG "WVCdm" + +#include "WVDrmPlugin.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "Utils.h" +#include "android-base/macros.h" +#include "log.h" +#include "mapErrors-inl.h" +#include "media/stagefright/MediaErrors.h" +#include "openssl/sha.h" +#include "wv_cdm_constants.h" +#include "wv_metrics.pb.h" +#include "wv_metrics_adapter.h" + +namespace { + +static const char* const kResetSecurityLevel = ""; +static const char* const kEnable = "enable"; +static const char* const kDisable = "disable"; +static const std::string kPsshTag = "pssh"; +static const char* const kSpecialUnprovisionResponse = "unprovision"; +static const std::string kKeyAppPackageName = "application_name"; +static const std::string kKeyOrigin = "origin"; + +} // namespace + +namespace wvdrm { +namespace hardware { +namespace drm { +namespace widevine { + +using std::string; +using std::vector; + +using ::aidl::android::hardware::drm::DrmMetric; +using ::aidl::android::hardware::drm::DrmMetricGroup; +using ::aidl::android::hardware::drm::DrmMetricNamedValue; +using ::aidl::android::hardware::drm::DrmMetricValue; +using ::aidl::android::hardware::drm::EventType; +using ::aidl::android::hardware::drm::HdcpLevel; +using ::aidl::android::hardware::drm::KeyRequestType; +using ::aidl::android::hardware::drm::KeySetId; +using ::aidl::android::hardware::drm::KeyStatus; +using ::aidl::android::hardware::drm::KeyStatusType; +using ::aidl::android::hardware::drm::KeyType; +using ::aidl::android::hardware::drm::KeyValue; +using ::aidl::android::hardware::drm::OfflineLicenseState; +using ::aidl::android::hardware::drm::SecureStop; +using ::aidl::android::hardware::drm::SecureStopId; +using ::aidl::android::hardware::drm::SecurityLevel; +using ::aidl::android::hardware::drm::Status; + +using wvcdm::CdmAppParameterMap; +using wvcdm::CdmCertificateType; +using wvcdm::CdmInitData; +using wvcdm::CdmKeyRequest; +using wvcdm::CdmKeyRequestType; +using wvcdm::CdmKeyResponse; +using wvcdm::CdmKeySetId; +using wvcdm::CdmKeyStatus; +using wvcdm::CdmLicenseType; +using wvcdm::CdmProvisioningRequest; +using wvcdm::CdmProvisioningResponse; +using wvcdm::CdmQueryMap; +using wvcdm::CdmSecureStopId; +using wvcdm::CdmSecurityLevel; +using wvcdm::CdmUsageInfo; +using wvcdm::CdmUsageInfoReleaseMessage; +using wvcdm::kDefaultCdmIdentifier; +using wvcdm::KeyId; +using wvcdm::RequestedSecurityLevel; + +namespace { + +vector StrToVector(const std::string& str) { + vector vec(str.begin(), str.end()); + return vec; +} + +KeyRequestType ConvertFromCdmKeyRequestType(CdmKeyRequestType keyRequestType) { + switch (keyRequestType) { + case wvcdm::kKeyRequestTypeInitial: + return KeyRequestType::INITIAL; + case wvcdm::kKeyRequestTypeRenewal: + return KeyRequestType::RENEWAL; + case wvcdm::kKeyRequestTypeRelease: + return KeyRequestType::RELEASE; + case wvcdm::kKeyRequestTypeNone: + return KeyRequestType::NONE; + case wvcdm::kKeyRequestTypeUpdate: + return KeyRequestType::UPDATE; + default: + return KeyRequestType::UNKNOWN; + } +} + +KeyStatusType ConvertFromCdmKeyStatus(CdmKeyStatus keyStatus) { + switch (keyStatus) { + case wvcdm::kKeyStatusUsable: + return KeyStatusType::USABLE; + case wvcdm::kKeyStatusExpired: + return KeyStatusType::EXPIRED; + case wvcdm::kKeyStatusOutputNotAllowed: + return KeyStatusType::OUTPUTNOTALLOWED; + case wvcdm::kKeyStatusPending: + case wvcdm::kKeyStatusUsableInFuture: + return KeyStatusType::USABLEINFUTURE; + case wvcdm::kKeyStatusInternalError: + default: + return KeyStatusType::INTERNALERROR; + } +} + +HdcpLevel mapHdcpLevel(const std::string& level) { + if (level == wvcdm::QUERY_VALUE_HDCP_V1) + return HdcpLevel::HDCP_V1; + else if (level == wvcdm::QUERY_VALUE_HDCP_V2_0) + return HdcpLevel::HDCP_V2; + else if (level == wvcdm::QUERY_VALUE_HDCP_V2_1) + return HdcpLevel::HDCP_V2_1; + else if (level == wvcdm::QUERY_VALUE_HDCP_V2_2) + return HdcpLevel::HDCP_V2_2; + else if (level == wvcdm::QUERY_VALUE_HDCP_V2_3) + return HdcpLevel::HDCP_V2_3; + else if (level == wvcdm::QUERY_VALUE_HDCP_NONE) + return HdcpLevel::HDCP_NONE; + else if (level == wvcdm::QUERY_VALUE_HDCP_NO_DIGITAL_OUTPUT) + return HdcpLevel::HDCP_NO_OUTPUT; + else { + ALOGE("Invalid HDCP level=%s", level.c_str()); + return HdcpLevel::HDCP_NONE; + } +} + +} // namespace + +WVDrmPlugin::WVDrmPlugin(const android::sp& cdm, + const std::string& appPackageName, + WVGenericCryptoInterface* crypto, bool useSpoid) + : mCdmIdentifierBuilder(useSpoid, *this, appPackageName), + mCDM(cdm), + mCrypto(crypto), + mCryptoSessions(), + mAppPackageName(appPackageName) { + Terminator::Register(this); +} + +WVDrmPlugin::~WVDrmPlugin() { + wvutil::SetLoggingUid(mCdmIdentifierBuilder.user_id()); + Terminator::Forget(this); + Close(); +} + +void WVDrmPlugin::Close() { + typedef std::map::iterator mapIterator; + for (mapIterator iter = mCryptoSessions.begin(); + iter != mCryptoSessions.end(); ++iter) { + CdmResponseType res = mCDM->CloseSession(iter->first); + if (!isCdmResponseTypeSuccess(res)) { + ALOGE("Failed to close session while destroying WVDrmPlugin"); + } + } + mCryptoSessions.clear(); + if (mCdmIdentifierBuilder.is_sealed()) { + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + ALOGE("Failed to get cdm identifier %d", status); + } else { + status = mapCdmResponseType(mCDM->CloseCdm(identifier)); + if (status != Status::OK) { + ALOGE("Failed to close cdm. status %d", status); + } + } + } +} + +Status WVDrmPlugin::openSessionCommon(vector& sessionId) { + Status status = Status::OK; + + CdmIdentifier identifier; + status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + return status; + } + + CdmSessionId cdmSessionId; + CdmResponseType res = mCDM->OpenSession("com.widevine", &mPropertySet, + identifier, this, &cdmSessionId); + + if (!isCdmResponseTypeSuccess(res)) { + status = mapAndNotifyOfCdmResponseType(sessionId, res); + return status; + } + + bool success = false; + + // Construct a CryptoSession + CdmQueryMap info; + res = mCDM->QueryOemCryptoSessionId(cdmSessionId, &info); + + if (isCdmResponseTypeSuccess(res) && + info.count(wvcdm::QUERY_KEY_OEMCRYPTO_SESSION_ID)) { + OEMCrypto_SESSION oecSessionId = + std::stoul(info[wvcdm::QUERY_KEY_OEMCRYPTO_SESSION_ID]); + mCryptoSessions[cdmSessionId] = CryptoSession(oecSessionId); + success = true; + } else { + ALOGE("Unable to query key control info."); + } + + if (success) { + // Marshal Session ID + sessionId = StrToVector(cdmSessionId); + return Status::OK; + } else { + mCDM->CloseSession(cdmSessionId); + + if (!isCdmResponseTypeSuccess(res)) { + // We got an error code we can return. + status = mapAndNotifyOfCdmResponseType(sessionId, res); + } else { + // We got a failure that did not give us an error code, such as a failure + // of AttachEventListener() or the key being missing from the map. + ALOGW("Returns UNKNOWN error for legacy status kErrorCDMGeneric"); + status = Status::ERROR_DRM_UNKNOWN; + } + } + return status; +} + +SecurityLevel WVDrmPlugin::mapSecurityLevel(const std::string& level) { + SecurityLevel securityLevel = SecurityLevel::UNKNOWN; + + if (wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1 == level) { + securityLevel = SecurityLevel::HW_SECURE_ALL; + } else if (wvcdm::QUERY_VALUE_SECURITY_LEVEL_L2 == level) { + securityLevel = SecurityLevel::HW_SECURE_CRYPTO; + } else if (wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3 == level) { + securityLevel = SecurityLevel::SW_SECURE_CRYPTO; + } // else QUERY_VALUE_SECURITY_LEVEL_UNKNOWN returns Security::UNKNOWN + + return securityLevel; +} + +::ndk::ScopedAStatus WVDrmPlugin::openSession(SecurityLevel in_securityLevel, + vector* _aidl_return) { + vector sessionId; + + if (SecurityLevel::UNKNOWN == in_securityLevel) { + *_aidl_return = sessionId; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + std::string native_security_level; + Status status = + queryProperty(wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, + native_security_level); + if (Status::OK != status) { + *_aidl_return = sessionId; + return toNdkScopedAStatus(status); + } + + if (wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3 == native_security_level && + in_securityLevel >= SecurityLevel::SW_SECURE_DECODE) { + *_aidl_return = sessionId; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + std::string wvcdm_security_level = + (SecurityLevel::SW_SECURE_CRYPTO == in_securityLevel) + ? wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3 + : wvcdm::QUERY_VALUE_SECURITY_LEVEL_DEFAULT; + + setPropertyString("securityLevel", std::string(wvcdm_security_level)); + + SecurityLevel securityLevel = in_securityLevel; + if (SecurityLevel::DEFAULT == in_securityLevel) { + std::string level; + Status status = queryProperty(wvcdm::kLevelDefault, + wvcdm::QUERY_KEY_SECURITY_LEVEL, level); + if (status == Status::OK) { + securityLevel = mapSecurityLevel(level); + } else { + ALOGE("openSession: failed to query security level, status=%d", status); + } + } + + status = openSessionCommon(sessionId); + if (Status::OK == status) { + SecurityLevel currentSecurityLevel = SecurityLevel::UNKNOWN; + const auto ret = getSecurityLevel(sessionId, ¤tSecurityLevel); + if (!ret.isOk() || securityLevel != currentSecurityLevel) { + ALOGE("Failed to open session with the requested security level=%d", + securityLevel); + closeSession(sessionId); + sessionId.clear(); + status = Status::ERROR_DRM_INVALID_STATE; + } + } + *_aidl_return = sessionId; + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::closeSession( + const vector& in_sessionId) { + if (!in_sessionId.size()) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + CdmResponseType res = mCDM->CloseSession(cdmSessionId); + mCryptoSessions.erase(cdmSessionId); + if (!isCdmResponseTypeSuccess(res)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::getKeyRequest( + const vector& in_scope, const vector& in_initData, + const std::string& in_mimeType, + ::aidl::android::hardware::drm::KeyType in_keyType, + const vector<::aidl::android::hardware::drm::KeyValue>& + in_optionalParameters, + ::aidl::android::hardware::drm::KeyRequest* _aidl_return) { + if (!in_scope.size()) { + _aidl_return->request = vector(); + _aidl_return->requestType = KeyRequestType::UNKNOWN; + _aidl_return->defaultUrl = ""; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + KeyRequestType requestType = KeyRequestType::UNKNOWN; + Status status = Status::OK; + std::string defaultUrl; + vector request; + + CdmIdentifier identifier; + status = + static_cast(mCdmIdentifierBuilder.getCdmIdentifier(&identifier)); + if (status != Status::OK) { + _aidl_return->request = request; + _aidl_return->requestType = KeyRequestType::UNKNOWN; + _aidl_return->defaultUrl = ""; + return toNdkScopedAStatus(status); + } + + CdmLicenseType cdmLicenseType; + CdmSessionId cdmSessionId; + CdmKeySetId cdmKeySetId; + if (in_keyType == KeyType::OFFLINE) { + cdmLicenseType = wvcdm::kLicenseTypeOffline; + cdmSessionId.assign(in_scope.begin(), in_scope.end()); + } else if (in_keyType == KeyType::STREAMING) { + cdmLicenseType = wvcdm::kLicenseTypeStreaming; + cdmSessionId.assign(in_scope.begin(), in_scope.end()); + } else if (in_keyType == KeyType::RELEASE) { + cdmLicenseType = wvcdm::kLicenseTypeRelease; + cdmKeySetId.assign(in_scope.begin(), in_scope.end()); + } else { + _aidl_return->request = request; + _aidl_return->requestType = KeyRequestType::UNKNOWN; + _aidl_return->defaultUrl = ""; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + std::string cdmInitDataType = in_mimeType; + // Provide backwards-compatibility for apps that pass non-EME-compatible + // MIME types. + if (!WvContentDecryptionModule::IsSupported(cdmInitDataType)) { + cdmInitDataType = wvcdm::ISO_BMFF_VIDEO_MIME_TYPE; + } + + CdmInitData processedInitData; + if (in_initData.size() > 0 && + WvContentDecryptionModule::IsCenc(cdmInitDataType) && + !initDataResemblesPSSH(in_initData)) { + // This data was passed in the old format, pre-unwrapped. We need to wrap + // the init data in a new PSSH header. + static const uint8_t psshPrefix[] = { + 0, 0, 0, 0, // Total size + 'p', 's', 's', 'h', // "PSSH" + 0, 0, 0, 0, // Flags - must be zero + 0xED, 0xEF, 0x8B, 0xA9, 0x79, 0xD6, 0x4A, 0xCE, // Widevine UUID + 0xA3, 0xC8, 0x27, 0xDC, 0xD5, 0x1D, 0x21, 0xED, + 0, 0, 0, 0 // Size of initData + }; + processedInitData.assign(reinterpret_cast(psshPrefix), + sizeof(psshPrefix) / sizeof(uint8_t)); + processedInitData.append(reinterpret_cast(in_initData.data()), + in_initData.size()); + const size_t kPsshBoxSizeLocation = 0; + const size_t kInitDataSizeLocation = sizeof(psshPrefix) - sizeof(uint32_t); + uint32_t psshBoxSize = htonl(processedInitData.size()); + uint32_t initDataSize = htonl(in_initData.size()); + memcpy(&processedInitData[kPsshBoxSizeLocation], &psshBoxSize, + sizeof(uint32_t)); + memcpy(&processedInitData[kInitDataSizeLocation], &initDataSize, + sizeof(uint32_t)); + } else { + // For other formats, we can pass the init data through unmodified. + processedInitData.assign(reinterpret_cast(in_initData.data()), + in_initData.size()); + } + + CdmAppParameterMap cdmParameters; + for (size_t i = 0; i < in_optionalParameters.size(); ++i) { + const std::string& key(in_optionalParameters[i].key); + const std::string& value(in_optionalParameters[i].value); + + std::string cdmKey(key.c_str(), key.size()); + std::string cdmValue(value.c_str(), value.size()); + + cdmParameters[cdmKey] = cdmValue; + } + + // Inserting additional client ID parameters here, this will appear + // in the license request. + // Note: This will overwrite user parameters of the same key. + cdmParameters[kKeyAppPackageName] = mAppPackageName; + cdmParameters[kKeyOrigin] = mCdmIdentifierBuilder.origin(); + + CdmKeyRequest keyRequest; + CdmResponseType res = mCDM->GenerateKeyRequest( + cdmSessionId, cdmKeySetId, cdmInitDataType, processedInitData, + cdmLicenseType, cdmParameters, &mPropertySet, identifier, &keyRequest); + + requestType = ConvertFromCdmKeyRequestType(keyRequest.type); + + if (isCdmResponseTypeSuccess(res)) { + defaultUrl.clear(); + defaultUrl.assign(keyRequest.url.data(), keyRequest.url.size()); + + request = StrToVector(keyRequest.message); + } + + if (in_keyType == KeyType::RELEASE) { + // When releasing keys, we do not have a session ID. + status = mapCdmResponseType(res); + } else { + // For all other requests, we have a session ID. + status = mapAndNotifyOfCdmResponseType(in_scope, res); + } + _aidl_return->request = request; + _aidl_return->requestType = requestType; + _aidl_return->defaultUrl = defaultUrl; + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::provideKeyResponse( + const vector& in_scope, const vector& in_response, + ::aidl::android::hardware::drm::KeySetId* _aidl_return) { + if (in_scope.size() == 0 || in_response.size() == 0) { + *_aidl_return = {}; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmKeySetId cdmKeySetId; + CdmSessionId cdmSessionId; + CdmKeyResponse cdmResponse(in_response.begin(), in_response.end()); + + bool isRequest = (memcmp(in_scope.data(), wvcdm::SESSION_ID_PREFIX, + sizeof(wvcdm::SESSION_ID_PREFIX) - 1) == 0); + bool isRelease = (memcmp(in_scope.data(), wvcdm::KEY_SET_ID_PREFIX, + sizeof(wvcdm::KEY_SET_ID_PREFIX) - 1) == 0); + + vector keySetId; + + if (isRequest) { + cdmSessionId.assign(in_scope.begin(), in_scope.end()); + } else if (isRelease) { + cdmKeySetId.assign(in_scope.begin(), in_scope.end()); + } else { + _aidl_return->keySetId = keySetId; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + CdmResponseType res = mCDM->AddKey(cdmSessionId, cdmResponse, &cdmKeySetId); + + if (isRequest && isCdmResponseTypeSuccess(res)) { + keySetId = StrToVector(cdmKeySetId); + } + + Status status = Status::OK; + if (isRelease) { + // When releasing keys, we do not have a session ID. + status = mapCdmResponseType(res); + } else { + // For all other requests, we have a session ID. + status = mapAndNotifyOfCdmResponseType(in_scope, res); + // For "NEED_KEY," we still want to send the notification, but then we + // don't return the error. This is because "NEED_KEY" from AddKey() is an + // expected behavior when sending a privacy certificate. + if (res == wvcdm::NEED_KEY && mPropertySet.use_privacy_mode()) { + status = Status::OK; + } + } + _aidl_return->keySetId = keySetId; + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::removeKeys( + const vector& in_sessionId) { + if (!in_sessionId.size()) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + + CdmResponseType res = mCDM->RemoveKeys(cdmSessionId); + + return toNdkScopedAStatus(mapAndNotifyOfCdmResponseType(in_sessionId, res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::restoreKeys( + const vector& in_sessionId, + const ::aidl::android::hardware::drm::KeySetId& in_keySetId) { + if (!in_sessionId.size() || !in_keySetId.keySetId.size()) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + CdmKeySetId cdmKeySetId(in_keySetId.keySetId.begin(), + in_keySetId.keySetId.end()); + + CdmResponseType res = mCDM->RestoreKey(cdmSessionId, cdmKeySetId); + + return toNdkScopedAStatus(mapAndNotifyOfCdmResponseType(in_sessionId, res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::queryKeyStatus( + const vector& in_sessionId, + vector<::aidl::android::hardware::drm::KeyValue>* _aidl_return) { + if (in_sessionId.size() == 0) { + *_aidl_return = vector(); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + CdmQueryMap cdmLicenseInfo; + + CdmResponseType res = mCDM->QueryKeyStatus(cdmSessionId, &cdmLicenseInfo); + + vector infoMapVec; + if (isCdmResponseTypeSuccess(res)) { + infoMapVec.clear(); + + KeyValue keyValuePair; + for (CdmQueryMap::const_iterator iter = cdmLicenseInfo.begin(); + iter != cdmLicenseInfo.end(); ++iter) { + const std::string& cdmKey = iter->first; + const std::string& cdmValue = iter->second; + keyValuePair.key = std::string(cdmKey.data(), cdmKey.size()); + keyValuePair.value = std::string(cdmValue.data(), cdmValue.size()); + infoMapVec.push_back(keyValuePair); + } + } + + *_aidl_return = infoMapVec; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::getProvisionRequest( + const std::string& in_certificateType, + const std::string& in_certificateAuthority, + ::aidl::android::hardware::drm::ProvisionRequest* _aidl_return) { + Status status = Status::OK; + std::string defaultUrl; + vector request; + + if (mPropertySet.use_atsc_mode()) { + _aidl_return->defaultUrl = defaultUrl; + _aidl_return->request = request; + return toNdkScopedAStatus( + mapCdmResponseType(wvcdm::PROVISIONING_NOT_ALLOWED_FOR_ATSC)); + } + + CdmIdentifier identifier; + status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + _aidl_return->defaultUrl = defaultUrl; + _aidl_return->request = request; + return toNdkScopedAStatus(status); + } + + CdmProvisioningRequest cdmProvisionRequest; + std::string cdmDefaultUrl; + + CdmCertificateType cdmCertType = wvcdm::kCertificateWidevine; + if (in_certificateType == "X.509") { + cdmCertType = wvcdm::kCertificateX509; + } + + std::string cdmCertAuthority = in_certificateAuthority; + + CdmResponseType res = mCDM->GetProvisioningRequest( + cdmCertType, cdmCertAuthority, identifier, + mProvisioningServiceCertificate, getRequestedSecurityLevel(), + &cdmProvisionRequest, &cdmDefaultUrl); + if (isCdmResponseTypeSuccess(res)) { + request = StrToVector(cdmProvisionRequest); + defaultUrl.clear(); + defaultUrl.assign(cdmDefaultUrl.data(), cdmDefaultUrl.size()); + } + + _aidl_return->defaultUrl = defaultUrl; + _aidl_return->request = request; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::provideProvisionResponse( + const vector& in_response, + ::aidl::android::hardware::drm::ProvideProvisionResponseResult* + _aidl_return) { + if (!in_response.size()) { + _aidl_return->certificate = vector(); + _aidl_return->wrappedKey = vector(); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + vector certificate; + vector wrappedKey; + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + _aidl_return->certificate = certificate; + _aidl_return->wrappedKey = wrappedKey; + return toNdkScopedAStatus(status); + } + + CdmProvisioningResponse cdmResponse(in_response.begin(), in_response.end()); + if (cdmResponse == kSpecialUnprovisionResponse) { + if (identifier.IsEquivalentToDefault()) { + ALOGW("Returns UNKNOWN error for legacy status kErrorNoOriginSpecified"); + _aidl_return->certificate = certificate; + _aidl_return->wrappedKey = wrappedKey; + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + _aidl_return->certificate = certificate; + _aidl_return->wrappedKey = wrappedKey; + return toNdkScopedAStatus(unprovision(identifier)); + } else { + std::string cdmCertificate; + std::string cdmWrappedKey; + CdmResponseType res = mCDM->HandleProvisioningResponse( + identifier, cdmResponse, getRequestedSecurityLevel(), &cdmCertificate, + &cdmWrappedKey); + if (isCdmResponseTypeSuccess(res)) { + certificate = StrToVector(cdmCertificate); + wrappedKey = StrToVector(cdmWrappedKey); + } + _aidl_return->certificate = certificate; + _aidl_return->wrappedKey = wrappedKey; + return toNdkScopedAStatus(mapCdmResponseType(res)); + } +} + +Status WVDrmPlugin::unprovisionDevice() { + return unprovision(kDefaultCdmIdentifier); +} + +::ndk::ScopedAStatus WVDrmPlugin::getSecureStop( + const ::aidl::android::hardware::drm::SecureStopId& in_secureStopId, + ::aidl::android::hardware::drm::SecureStop* _aidl_return) { + if (!in_secureStopId.secureStopId.size()) { + *_aidl_return = SecureStop(); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + vector cdmStopVec; + SecureStop secureStop; + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + *_aidl_return = SecureStop(); + return toNdkScopedAStatus(status); + } + + CdmUsageInfo cdmUsageInfo; + CdmSecureStopId cdmSsId(in_secureStopId.secureStopId.begin(), + in_secureStopId.secureStopId.end()); + CdmResponseType res = mCDM->GetUsageInfo(mPropertySet.app_id(), cdmSsId, + identifier, &cdmUsageInfo); + + if (isCdmResponseTypeSuccess(res)) { + for (CdmUsageInfo::const_iterator iter = cdmUsageInfo.begin(); + iter != cdmUsageInfo.end(); ++iter) { + const std::string& cdmStop = *iter; + cdmStopVec = StrToVector(cdmStop); + } + secureStop.opaqueData = cdmStopVec; + } + + *_aidl_return = secureStop; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::getSecureStops( + vector<::aidl::android::hardware::drm::SecureStop>* _aidl_return) { + std::list> secureStops; + vector secureStopsVec; + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + *_aidl_return = secureStopsVec; + return toNdkScopedAStatus(status); + } + + CdmUsageInfo cdmUsageInfo; + CdmResponseType res = + mCDM->GetUsageInfo(mPropertySet.app_id(), identifier, &cdmUsageInfo); + + if (isCdmResponseTypeSuccess(res)) { + secureStops.clear(); + for (CdmUsageInfo::const_iterator iter = cdmUsageInfo.begin(); + iter != cdmUsageInfo.end(); ++iter) { + const std::string& cdmStop = *iter; + secureStops.push_back(StrToVector(cdmStop)); + } + } + + std::list>::iterator iter = secureStops.begin(); + while (iter != secureStops.end()) { + SecureStop secureStop; + secureStop.opaqueData = *iter++; + secureStopsVec.push_back(secureStop); + } + + *_aidl_return = secureStopsVec; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::releaseAllSecureStops() { + const auto res = removeAllSecureStops(); + Status status = Status::OK; + if (!res.isOk() && res.getExceptionCode() == EX_SERVICE_SPECIFIC) { + status = static_cast(res.getServiceSpecificError()); + } + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::releaseSecureStop( + const ::aidl::android::hardware::drm::SecureStopId& in_secureStopId) { + if (!in_secureStopId.secureStopId.size()) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + return toNdkScopedAStatus(status); + } + + CdmUsageInfoReleaseMessage cdmMessage(in_secureStopId.secureStopId.begin(), + in_secureStopId.secureStopId.end()); + CdmResponseType res = mCDM->ReleaseUsageInfo(cdmMessage, identifier); + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::getMetrics( + vector<::aidl::android::hardware::drm::DrmMetricGroup>* _aidl_return) { + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + *_aidl_return = vector(); + return toNdkScopedAStatus(status); + } + + drm_metrics::WvCdmMetrics proto_metrics; + CdmResponseType result = mCDM->GetMetrics(identifier, &proto_metrics); + if (result != wvcdm::NO_ERROR) { + *_aidl_return = vector(); + return toNdkScopedAStatus(mapCdmResponseType(result)); + } + + vector wvMetrics; + ::wvcdm::WvMetricsAdapter adapter; + ::wvcdm::WvMetricsAdapter::ToWvMetrics(proto_metrics, &wvMetrics); + *_aidl_return = wvMetrics; + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::getSecureStopIds( + vector<::aidl::android::hardware::drm::SecureStopId>* _aidl_return) { + vector secureStopIds; + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + *_aidl_return = secureStopIds; + return toNdkScopedAStatus(status); + } + + vector ssids; + CdmResponseType res = + mCDM->GetSecureStopIds(mPropertySet.app_id(), identifier, &ssids); + + if (isCdmResponseTypeSuccess(res)) { + for (auto itr = ssids.begin(); itr != ssids.end(); ++itr) { + const CdmSecureStopId& cdmSsid = *itr; + SecureStopId ssid; + ssid.secureStopId = StrToVector(cdmSsid); + secureStopIds.push_back(ssid); + } + } + + *_aidl_return = secureStopIds; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::releaseSecureStops( + const ::aidl::android::hardware::drm::OpaqueData& in_ssRelease) { + if (in_ssRelease.opaqueData.size() == 0) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + return toNdkScopedAStatus(status); + } + + const vector data = in_ssRelease.opaqueData; + CdmUsageInfoReleaseMessage cdmMessage(data.begin(), data.end()); + CdmResponseType res = mCDM->ReleaseUsageInfo(cdmMessage, identifier); + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::removeSecureStop( + const ::aidl::android::hardware::drm::SecureStopId& in_secureStopId) { + if (!in_secureStopId.secureStopId.size()) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + return toNdkScopedAStatus(status); + } + + CdmSecureStopId id(in_secureStopId.secureStopId.begin(), + in_secureStopId.secureStopId.end()); + CdmResponseType res = + mCDM->RemoveUsageInfo(mPropertySet.app_id(), identifier, id); + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::removeAllSecureStops() { + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + return toNdkScopedAStatus(status); + } + + CdmResponseType res = + mCDM->RemoveAllUsageInfo(mPropertySet.app_id(), identifier); + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::getHdcpLevels( + ::aidl::android::hardware::drm::HdcpLevels* _aidl_return) { + HdcpLevel connectedLevel = HdcpLevel::HDCP_NONE; + HdcpLevel maxLevel = HdcpLevel::HDCP_NO_OUTPUT; + + std::string level; + Status status = queryProperty(wvcdm::QUERY_KEY_CURRENT_HDCP_LEVEL, level); + if (status == Status::OK) { + connectedLevel = mapHdcpLevel(level); + } else { + ALOGE("Failed to query current hdcp level."); + _aidl_return->connectedLevel = connectedLevel; + _aidl_return->maxLevel = maxLevel; + return toNdkScopedAStatus(Status::ERROR_DRM_INVALID_STATE); + } + + status = queryProperty(wvcdm::QUERY_KEY_MAX_HDCP_LEVEL, level); + if (status == Status::OK) { + maxLevel = mapHdcpLevel(level); + } else { + ALOGE("Failed to query maximum hdcp level."); + _aidl_return->connectedLevel = connectedLevel; + _aidl_return->maxLevel = maxLevel; + return toNdkScopedAStatus(Status::ERROR_DRM_INVALID_STATE); + } + + _aidl_return->connectedLevel = connectedLevel; + _aidl_return->maxLevel = maxLevel; + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::getNumberOfSessions( + ::aidl::android::hardware::drm::NumberOfSessions* _aidl_return) { + uint32_t currentSessions = 0; + uint32_t maxSessions = 1; + + std::string value; + Status status = + queryProperty(wvcdm::QUERY_KEY_NUMBER_OF_OPEN_SESSIONS, value); + if (status == Status::OK) { + currentSessions = std::strtoul(value.c_str(), nullptr, 10); + } else { + ALOGE("Failed to query currently opened sessions."); + _aidl_return->currentSessions = currentSessions; + _aidl_return->maxSessions = maxSessions; + return toNdkScopedAStatus(Status::ERROR_DRM_INVALID_STATE); + } + + status = queryProperty(wvcdm::QUERY_KEY_MAX_NUMBER_OF_SESSIONS, value); + if (status == Status::OK) { + maxSessions = std::strtoul(value.c_str(), nullptr, 10); + } else { + ALOGE( + "Failed to query maximum number of sessions that the device can " + "support."); + _aidl_return->currentSessions = currentSessions; + _aidl_return->maxSessions = maxSessions; + return toNdkScopedAStatus(Status::ERROR_DRM_INVALID_STATE); + } + + _aidl_return->currentSessions = currentSessions; + _aidl_return->maxSessions = maxSessions; + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::getSecurityLevel( + const vector& in_sessionId, + ::aidl::android::hardware::drm::SecurityLevel* _aidl_return) { + if (in_sessionId.size() == 0) { + *_aidl_return = SecurityLevel::UNKNOWN; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmQueryMap info; + SecurityLevel securityLevel = SecurityLevel::UNKNOWN; + + CdmResponseType status = mCDM->QuerySessionStatus( + std::string(in_sessionId.begin(), in_sessionId.end()), &info); + if (wvcdm::NO_ERROR == status) { + std::string level = info[wvcdm::QUERY_KEY_SECURITY_LEVEL]; + securityLevel = mapSecurityLevel(level); + } else { + ALOGE("Failed to query security level, status=%d", status); + } + + *_aidl_return = securityLevel; + return toNdkScopedAStatus(mapCdmResponseType(status)); +} + +::ndk::ScopedAStatus WVDrmPlugin::getOfflineLicenseKeySetIds( + vector<::aidl::android::hardware::drm::KeySetId>* _aidl_return) { + vector> keySetIds; + vector keySetIdsVec; + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + *_aidl_return = keySetIdsVec; + return toNdkScopedAStatus(status); + } + + vector levels = {wvcdm::kSecurityLevelL1, + wvcdm::kSecurityLevelL3}; + + CdmResponseType res = wvcdm::UNKNOWN_ERROR; + + for (auto level : levels) { + vector cdmKeySetIds; + res = mCDM->ListStoredLicenses(level, identifier, &cdmKeySetIds); + + if (isCdmResponseTypeSuccess(res)) { + keySetIds.clear(); + for (auto id : cdmKeySetIds) { + keySetIds.push_back(StrToVector(id)); + } + KeySetId kid; + for (auto id : keySetIds) { + kid.keySetId = id; + keySetIdsVec.push_back(kid); + } + } + } + *_aidl_return = keySetIdsVec; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::getOfflineLicenseState( + const ::aidl::android::hardware::drm::KeySetId& in_keySetId, + ::aidl::android::hardware::drm::OfflineLicenseState* _aidl_return) { + OfflineLicenseState licenseState = OfflineLicenseState::UNKNOWN; + + if (!in_keySetId.keySetId.size()) { + *_aidl_return = licenseState; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + *_aidl_return = licenseState; + return toNdkScopedAStatus(status); + } + + CdmResponseType res = wvcdm::UNKNOWN_ERROR; + CdmKeySetId keySetIdStr(in_keySetId.keySetId.begin(), + in_keySetId.keySetId.end()); + + wvcdm::CdmOfflineLicenseState state = wvcdm::kLicenseStateUnknown; + res = mCDM->GetOfflineLicenseState(keySetIdStr, wvcdm::kSecurityLevelL1, + identifier, &state); + if (!isCdmResponseTypeSuccess(res)) { + // try L3 + res = mCDM->GetOfflineLicenseState(keySetIdStr, wvcdm::kSecurityLevelL3, + identifier, &state); + if (!isCdmResponseTypeSuccess(res)) { + *_aidl_return = licenseState; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } + + switch (state) { + case wvcdm::kLicenseStateActive: + licenseState = OfflineLicenseState::USABLE; + break; + case wvcdm::kLicenseStateReleasing: + licenseState = OfflineLicenseState::INACTIVE; + break; + default: + licenseState = OfflineLicenseState::UNKNOWN; + ALOGE("Return unknown offline license state for %s", keySetIdStr.c_str()); + break; + } + + *_aidl_return = licenseState; + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +::ndk::ScopedAStatus WVDrmPlugin::removeOfflineLicense( + const ::aidl::android::hardware::drm::KeySetId& in_keySetId) { + if (!in_keySetId.keySetId.size()) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + CdmIdentifier identifier; + Status status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + return toNdkScopedAStatus(status); + } + + CdmResponseType res = wvcdm::UNKNOWN_ERROR; + + res = mCDM->RemoveOfflineLicense( + std::string(in_keySetId.keySetId.begin(), in_keySetId.keySetId.end()), + wvcdm::kSecurityLevelL1, identifier); + if (!isCdmResponseTypeSuccess(res)) { + CdmResponseType res = mCDM->RemoveOfflineLicense( + std::string(in_keySetId.keySetId.begin(), in_keySetId.keySetId.end()), + wvcdm::kSecurityLevelL3, identifier); + status = mapCdmResponseType(res); + } + + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::getPropertyString( + const std::string& in_propertyName, std::string* _aidl_return) { + Status status = Status::OK; + std::string name(in_propertyName.c_str()); + std::string value; + + if (name == "vendor") { + value = "Google"; + } else if (name == "version") { + status = queryProperty(wvcdm::QUERY_KEY_WVCDM_VERSION, value); + } else if (name == "description") { + value = "Widevine CDM"; + } else if (name == "algorithms") { + value = "AES/CBC/NoPadding,HmacSHA256"; + } else if (name == "securityLevel") { + std::string requestedLevel = mPropertySet.security_level(); + + if (requestedLevel.length() > 0) { + value = requestedLevel.c_str(); + } else { + status = queryProperty(wvcdm::QUERY_KEY_SECURITY_LEVEL, value); + } + } else if (name == "systemId") { + status = queryProperty(wvcdm::QUERY_KEY_SYSTEM_ID, value); + } else if (name == "privacyMode") { + if (mPropertySet.use_privacy_mode()) { + value = kEnable; + } else { + value = kDisable; + } + } else if (name == "sessionSharing") { + if (mPropertySet.is_session_sharing_enabled()) { + value = kEnable; + } else { + value = kDisable; + } + } else if (name == "hdcpLevel") { + status = queryProperty(wvcdm::QUERY_KEY_CURRENT_HDCP_LEVEL, value); + } else if (name == "maxHdcpLevel") { + status = queryProperty(wvcdm::QUERY_KEY_MAX_HDCP_LEVEL, value); + } else if (name == "usageReportingSupport") { + status = queryProperty(wvcdm::QUERY_KEY_USAGE_SUPPORT, value); + } else if (name == "numberOfOpenSessions") { + status = queryProperty(wvcdm::QUERY_KEY_NUMBER_OF_OPEN_SESSIONS, value); + } else if (name == "maxNumberOfSessions") { + status = queryProperty(wvcdm::QUERY_KEY_MAX_NUMBER_OF_SESSIONS, value); + } else if (name == "oemCryptoApiVersion") { + status = queryProperty(wvcdm::QUERY_KEY_OEMCRYPTO_API_VERSION, value); + } else if (name == "appId") { + value = mPropertySet.app_id().c_str(); + } else if (name == "origin") { + value = mCdmIdentifierBuilder.origin().c_str(); + } else if (name == "CurrentSRMVersion") { + status = queryProperty(wvcdm::QUERY_KEY_CURRENT_SRM_VERSION, value); + } else if (name == "SRMUpdateSupport") { + status = queryProperty(wvcdm::QUERY_KEY_SRM_UPDATE_SUPPORT, value); + } else if (name == "resourceRatingTier") { + status = queryProperty(wvcdm::QUERY_KEY_RESOURCE_RATING_TIER, value); + } else if (name == "oemCryptoBuildInformation") { + status = queryProperty(wvcdm::QUERY_KEY_OEMCRYPTO_BUILD_INFORMATION, value); + } else if (name == "decryptHashSupport") { + status = queryProperty(wvcdm::QUERY_KEY_DECRYPT_HASH_SUPPORT, value); + } else if (name == "decryptHashError") { + status = mapCdmResponseType( + mCDM->GetDecryptHashError(mDecryptHashSessionId, &value)); + } else if (name == "maxUsageEntriesSupported") { + status = queryProperty(wvcdm::QUERY_KEY_MAX_USAGE_TABLE_ENTRIES, value); + } else if (name == "oemCryptoApiMinorVersion") { + status = queryProperty(wvcdm::QUERY_KEY_OEMCRYPTO_API_MINOR_VERSION, value); + } else if (name == "analogOutputCapabilities") { + status = queryProperty(wvcdm::QUERY_KEY_ANALOG_OUTPUT_CAPABILITIES, value); + } else if (name == "canDisableAnalogOutput") { + status = queryProperty(wvcdm::QUERY_KEY_CAN_DISABLE_ANALOG_OUTPUT, value); + } else if (name == "atscMode") { + if (mPropertySet.use_atsc_mode()) { + value = kEnable; + } else { + value = kDisable; + } + } else { + ALOGE("App requested unknown string property %s", name.c_str()); + *_aidl_return = value; + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + *_aidl_return = value; + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::getPropertyByteArray( + const std::string& in_propertyName, vector* _aidl_return) { + Status status = Status::OK; + std::string name(in_propertyName.c_str()); + vector value; + + if (name == "deviceUniqueId") { + std::string id; + status = mCdmIdentifierBuilder.getDeviceUniqueId(&id); + if (status == Status::OK) { + value = StrToVector(id); + } + } else if (name == "provisioningUniqueId") { + std::string id; + status = mCdmIdentifierBuilder.getProvisioningUniqueId(&id); + if (status == Status::OK) { + value = StrToVector(id); + } + } else if (name == "serviceCertificate") { + value = StrToVector(mPropertySet.service_certificate()); + } else if (name == "provisioningServiceCertificate") { + value = StrToVector(mProvisioningServiceCertificate); + } else if (name == "metrics") { + drm_metrics::WvCdmMetrics metrics; + // If the cdm identifier is not yet sealed, then there are no metrics + // for that cdm engine. Avoid calling getCdmIdentifier and sealing + // the identifier builder. + if (mCdmIdentifierBuilder.is_sealed()) { + CdmIdentifier identifier; + status = mCdmIdentifierBuilder.getCdmIdentifier(&identifier); + if (status != Status::OK) { + ALOGE("Unexpected error retrieving cdm identifier: %d", status); + } else { + status = mapCdmResponseType(mCDM->GetMetrics(identifier, &metrics)); + } + } + if (status == Status::OK) { + std::string serialized_metrics; + if (!metrics.SerializeToString(&serialized_metrics)) { + status = Status::ERROR_DRM_UNKNOWN; + } else { + value = StrToVector(serialized_metrics); + } + } + } else { + ALOGE("App requested unknown byte array property %s", name.c_str()); + status = Status::ERROR_DRM_CANNOT_HANDLE; + } + + *_aidl_return = value; + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::setPropertyString( + const std::string& in_propertyName, const std::string& in_value) { + std::string name(in_propertyName.c_str()); + std::string _value(in_value.c_str()); + + if (name == "securityLevel") { + if (mCryptoSessions.size() == 0) { + if (_value == wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3.c_str()) { + mPropertySet.set_security_level(wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3); + } else if (_value == wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1.c_str()) { + // We must be sure we CAN set the security level to L1. + std::string current_security_level; + Status status = + queryProperty(wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, + current_security_level); + if (status != Status::OK) { + return toNdkScopedAStatus(status); + } + if (current_security_level != wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1) { + ALOGE("App requested L1 security on a non-L1 device."); + return toNdkScopedAStatus(Status::BAD_VALUE); + } else { + mPropertySet.set_security_level(kResetSecurityLevel); + } + } else if (_value == kResetSecurityLevel || + _value == wvcdm::QUERY_VALUE_SECURITY_LEVEL_DEFAULT) { + mPropertySet.set_security_level(kResetSecurityLevel); + } else { + ALOGE("App requested invalid security level %s", _value.c_str()); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } else { + ALOGE("App tried to change security level while sessions are open."); + ALOGW("Returns UNKNOWN error for legacy status kErrorSessionIsOpen"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + } else if (name == "privacyMode") { + if (_value == kEnable) { + mPropertySet.set_use_privacy_mode(true); + } else if (_value == kDisable) { + mPropertySet.set_use_privacy_mode(false); + } else { + ALOGE("App requested unknown privacy mode %s", _value.c_str()); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } else if (name == "sessionSharing") { + if (mCryptoSessions.size() == 0) { + if (_value == kEnable) { + mPropertySet.set_is_session_sharing_enabled(true); + } else if (_value == kDisable) { + mPropertySet.set_is_session_sharing_enabled(false); + } else { + ALOGE("App requested unknown sharing type %s", _value.c_str()); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } else { + ALOGE("App tried to change key sharing while sessions are open."); + ALOGW("Returns UNKNOWN error for legacy status kErrorSessionIsOpen"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + } else if (name == "appId") { + if (mCryptoSessions.size() == 0) { + mPropertySet.set_app_id(_value.c_str()); + } else { + ALOGE("App tried to set the application id while sessions are opened."); + ALOGW("Returns UNKNOWN error for legacy status kErrorSessionIsOpen"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + } else if (name == "origin") { + if (mCryptoSessions.size() != 0) { + ALOGE("App tried to set the origin while sessions are opened."); + ALOGW("Returns UNKNOWN error for legacy status kErrorSessionIsOpen"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } else { + if (!mCdmIdentifierBuilder.set_origin(_value.c_str())) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } + } else if (name == "debugIgnoreKeyboxCount") { + std::istringstream ss(_value); + uint32_t count = 0; + ss >> count; + if (ss.fail()) { + ALOGE("Could not parse an integer from '%s'", _value.c_str()); + count = 0; + return toNdkScopedAStatus(Status::BAD_VALUE); + } + CdmResponseType res = mCDM->SetDebugIgnoreKeyboxCount(count); + return toNdkScopedAStatus(mapCdmResponseType(res)); + } else if (name == "decryptHash") { + wvcdm::CdmSessionId sessionId; + CdmResponseType res = mCDM->SetDecryptHash(_value.c_str(), &sessionId); + + if (wvcdm::NO_ERROR == res) mDecryptHashSessionId = sessionId; + return toNdkScopedAStatus(mapCdmResponseType(res)); + } else if (name == "decryptHashSessionId") { + mDecryptHashSessionId = _value.c_str(); + } else if (name == "atscMode") { + if (_value == kEnable) { + if (!mCdmIdentifierBuilder.set_use_atsc_mode(true)) { + ALOGE("Cdm identifier builder is sealed. Setting ATSC mode prohibited"); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + mPropertySet.set_use_atsc_mode(true); + } else if (_value == kDisable) { + if (!mCdmIdentifierBuilder.set_use_atsc_mode(false)) { + ALOGE("Cdm identifier builder is sealed. Setting ATSC mode prohibited"); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + mPropertySet.set_use_atsc_mode(false); + } else { + ALOGE("App requested unknown ATSC mode %s", _value.c_str()); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } else if (name == "debugOtaKeyboxFallbackDuration") { + bool success = false; + if (_value == "default") { + success = mCDM->SetDefaultOtaKeyboxFallbackDurationRules(); + } else if (_value == "fast") { + success = mCDM->SetFastOtaKeyboxFallbackDurationRules(); + } else { + ALOGE("Unknown OTA fallback duration value %s", _value.c_str()); + return toNdkScopedAStatus(Status::BAD_VALUE); + } + if (!success) { + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + } else { + ALOGE("App set unknown string property %s", name.c_str()); + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::setPropertyByteArray( + const std::string& in_propertyName, const vector& in_value) { + std::string name(in_propertyName.c_str()); + vector _value = in_value; + + if (name == "serviceCertificate") { + std::string cert(_value.begin(), _value.end()); + if (_value.empty() || mCDM->IsValidServiceCertificate(cert)) { + mPropertySet.set_service_certificate(cert); + } else { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } else if (name == "provisioningServiceCertificate") { + std::string cert(_value.begin(), _value.end()); + if (_value.empty() || mCDM->IsValidServiceCertificate(cert)) { + mProvisioningServiceCertificate = cert; + } else { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + } else { + ALOGE("App set unknown byte array property %s", name.c_str()); + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::setCipherAlgorithm( + const vector& in_sessionId, const std::string& in_algorithm) { + if (in_sessionId.size() == 0 || in_algorithm.size() == 0) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + std::string algo(in_algorithm.c_str()); + + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCryptoSessions.count(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + + CryptoSession& cryptoSession = mCryptoSessions[cdmSessionId]; + + if (algo == "AES/CBC/NoPadding") { + cryptoSession.setCipherAlgorithm(OEMCrypto_AES_CBC_128_NO_PADDING); + } else { + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::setMacAlgorithm( + const vector& in_sessionId, const std::string& in_algorithm) { + if (in_sessionId.size() == 0 || in_algorithm.size() == 0) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + std::string algo(in_algorithm.c_str()); + + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCryptoSessions.count(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + + CryptoSession& cryptoSession = mCryptoSessions[cdmSessionId]; + + if (algo == "HmacSHA256") { + cryptoSession.setMacAlgorithm(OEMCrypto_HMAC_SHA256); + } else { + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::encrypt(const vector& in_sessionId, + const vector& in_keyId, + const vector& in_input, + const vector& in_iv, + vector* _aidl_return) { + vector output; + + *_aidl_return = output; + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCryptoSessions.count(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + + const CryptoSession& cryptoSession = mCryptoSessions[cdmSessionId]; + + if (cryptoSession.cipherAlgorithm() == kInvalidCryptoAlgorithm) { + ALOGW("Returns UNKNOWN error for legacy status NO_INIT"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + + OEMCryptoResult res = mCrypto->selectKey(cryptoSession.oecSessionId(), + in_keyId.data(), in_keyId.size()); + + if (res != OEMCrypto_SUCCESS) { + ALOGE("OEMCrypto_SelectKey failed with %u", res); + return toNdkScopedAStatus(mapAndNotifyOfOEMCryptoResult(in_sessionId, res)); + } + + output.resize(in_input.size()); + + Status status = Status::OK; + res = mCrypto->encrypt(cryptoSession.oecSessionId(), in_input.data(), + in_input.size(), in_iv.data(), + cryptoSession.cipherAlgorithm(), output.data()); + + *_aidl_return = output; + if (res == OEMCrypto_SUCCESS) { + status = Status::OK; + } else { + ALOGE("OEMCrypto_Generic_Encrypt failed with %u", res); + status = mapAndNotifyOfOEMCryptoResult(in_sessionId, res); + } + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::decrypt(const vector& in_sessionId, + const vector& in_keyId, + const vector& in_input, + const vector& in_iv, + vector* _aidl_return) { + vector output; + *_aidl_return = output; + + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCryptoSessions.count(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + + const CryptoSession& cryptoSession = mCryptoSessions[cdmSessionId]; + + if (cryptoSession.cipherAlgorithm() == kInvalidCryptoAlgorithm) { + ALOGW("Returns UNKNOWN error for legacy status NO_INIT"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + + OEMCryptoResult res = mCrypto->selectKey(cryptoSession.oecSessionId(), + in_keyId.data(), in_keyId.size()); + + if (res != OEMCrypto_SUCCESS) { + ALOGE("OEMCrypto_SelectKey failed with %u", res); + return toNdkScopedAStatus(mapAndNotifyOfOEMCryptoResult(in_sessionId, res)); + } + + output.resize(in_input.size()); + + Status status = Status::OK; + res = mCrypto->decrypt(cryptoSession.oecSessionId(), in_input.data(), + in_input.size(), in_iv.data(), + cryptoSession.cipherAlgorithm(), output.data()); + + *_aidl_return = output; + if (res == OEMCrypto_SUCCESS) { + status = Status::OK; + } else { + ALOGE("OEMCrypto_Generic_Decrypt failed with %u", res); + status = mapAndNotifyOfOEMCryptoResult(in_sessionId, res); + } + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::sign(const vector& in_sessionId, + const vector& in_keyId, + const vector& in_message, + vector* _aidl_return) { + vector signature; + *_aidl_return = signature; + + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCryptoSessions.count(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + + const CryptoSession& cryptoSession = mCryptoSessions[cdmSessionId]; + + if (cryptoSession.macAlgorithm() == kInvalidCryptoAlgorithm) { + ALOGW("Returns UNKNOWN error for legacy status NO_INIT"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + + OEMCryptoResult res = mCrypto->selectKey(cryptoSession.oecSessionId(), + in_keyId.data(), in_keyId.size()); + + if (res != OEMCrypto_SUCCESS) { + ALOGE("OEMCrypto_SelectKey failed with %u", res); + return toNdkScopedAStatus(mapAndNotifyOfOEMCryptoResult(in_sessionId, res)); + } + + size_t signatureSize = 0; + + res = mCrypto->sign(cryptoSession.oecSessionId(), in_message.data(), + in_message.size(), cryptoSession.macAlgorithm(), nullptr, + &signatureSize); + + Status status = Status::OK; + if (res != OEMCrypto_ERROR_SHORT_BUFFER) { + ALOGE( + "OEMCrypto_Generic_Sign failed with %u when requesting signature " + "size", + res); + if (res != OEMCrypto_SUCCESS) { + status = mapAndNotifyOfOEMCryptoResult(in_sessionId, res); + } else { + status = Status::ERROR_DRM_UNKNOWN; + } + return toNdkScopedAStatus(status); + } + + signature.resize(signatureSize); + + res = mCrypto->sign(cryptoSession.oecSessionId(), in_message.data(), + in_message.size(), cryptoSession.macAlgorithm(), + signature.data(), &signatureSize); + + *_aidl_return = signature; + if (res == OEMCrypto_SUCCESS) { + status = Status::OK; + } else { + ALOGE("OEMCrypto_Generic_Sign failed with %u", res); + status = mapAndNotifyOfOEMCryptoResult(in_sessionId, res); + } + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::verify(const vector& in_sessionId, + const vector& in_keyId, + const vector& in_message, + const vector& in_signature, + bool* _aidl_return) { + bool match = false; + *_aidl_return = match; + + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + if (!mCryptoSessions.count(cdmSessionId)) { + return toNdkScopedAStatus(Status::ERROR_DRM_SESSION_NOT_OPENED); + } + + const CryptoSession& cryptoSession = mCryptoSessions[cdmSessionId]; + + if (cryptoSession.macAlgorithm() == kInvalidCryptoAlgorithm) { + ALOGW("Returns UNKNOWN error for legacy status NO_INIT"); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + + OEMCryptoResult res = mCrypto->selectKey(cryptoSession.oecSessionId(), + in_keyId.data(), in_keyId.size()); + + if (res != OEMCrypto_SUCCESS) { + ALOGE("OEMCrypto_SelectKey failed with %u", res); + return toNdkScopedAStatus(mapAndNotifyOfOEMCryptoResult(in_sessionId, res)); + } + + res = mCrypto->verify(cryptoSession.oecSessionId(), in_message.data(), + in_message.size(), cryptoSession.macAlgorithm(), + in_signature.data(), in_signature.size()); + + Status status = Status::OK; + if (res == OEMCrypto_SUCCESS) { + match = true; + status = Status::OK; + } else if (res == OEMCrypto_ERROR_SIGNATURE_FAILURE) { + match = false; + status = Status::OK; + } else { + ALOGE("OEMCrypto_Generic_Verify failed with %u", res); + match = false; + status = mapAndNotifyOfOEMCryptoResult(in_sessionId, res); + } + *_aidl_return = match; + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::signRSA(const vector& in_sessionId, + const std::string& in_algorithm, + const vector& in_message, + const vector& in_wrappedkey, + vector* _aidl_return) { + *_aidl_return = vector(); + if (in_sessionId.size() == 0 || in_algorithm.size() == 0 || + in_message.size() == 0 || in_wrappedkey.size() == 0) { + return toNdkScopedAStatus(Status::BAD_VALUE); + } + + const auto& self = android::IPCThreadState::self(); + const char* sid = self->getCallingSid(); + if (!sid || + (!strstr(sid, ":mediashell_app:") && !strstr(sid, ":mediadrmserver:") && + !strstr(sid, ":setupwraith_app:"))) { + ALOGE( + "Only mediashell/mediadrmserver/setupwraith_app can call signRSA, " + "but actually: %s", + sid); + return toNdkScopedAStatus(Status::ERROR_DRM_UNKNOWN); + } + + const std::string algo(in_algorithm.c_str()); + vector signature; + *_aidl_return = signature; + + RSA_Padding_Scheme padding_scheme; + if (algo == "RSASSA-PSS-SHA1") { + padding_scheme = kSign_RSASSA_PSS; + } else if (algo == "PKCS1-BlockType1") { + padding_scheme = kSign_PKCS1_Block1; + } else { + ALOGE("Unknown RSA Algorithm %s", algo.c_str()); + return toNdkScopedAStatus(Status::ERROR_DRM_CANNOT_HANDLE); + } + + Status status = Status::OK; + OEMCryptoResult res = mCrypto->signRSA( + in_wrappedkey.data(), in_wrappedkey.size(), in_message.data(), + in_message.size(), signature, padding_scheme); + + *_aidl_return = signature; + if (res != OEMCrypto_SUCCESS) { + ALOGE("OEMCrypto_GenerateRSASignature failed with %u", res); + status = mapOEMCryptoResult(res); + } + return toNdkScopedAStatus(status); +} + +::ndk::ScopedAStatus WVDrmPlugin::setListener( + const std::shared_ptr<::aidl::android::hardware::drm::IDrmPluginListener>& + in_listener) { + mListener = in_listener; + ::ndk::ScopedAStatus _aidl_status; + _aidl_status.set(AStatus_fromStatus(STATUS_OK)); + return _aidl_status; +} + +void WVDrmPlugin::sendEvent( + ::aidl::android::hardware::drm::EventType in_eventType, + const vector& in_sessionId, const vector& in_data) { + ::ndk::ScopedAStatus err = ::ndk::ScopedAStatus::ok(); + if (mListener != nullptr) { + err = mListener->onEvent(in_eventType, in_sessionId, in_data); + } else { + ALOGE("Null event listener, event not sent"); + } + if (!err.isOk()) { + ALOGW("sendEvent failed %s", err.getDescription().c_str()); + } + return; +} + +void WVDrmPlugin::sendExpirationUpdate(const vector& in_sessionId, + int64_t in_expiryTimeInMS) { + ::ndk::ScopedAStatus err; + if (mListener != nullptr) { + err = mListener->onExpirationUpdate(in_sessionId, in_expiryTimeInMS); + } else { + ALOGE("Null event listener, event not sent"); + } + if (!err.isOk()) { + ALOGW("sendExpirationUpdate failed %s", err.getDescription().c_str()); + } + return; +} + +void WVDrmPlugin::sendKeysChange( + const vector& in_sessionId, + const vector<::aidl::android::hardware::drm::KeyStatus>& in_keyStatusList, + bool in_hasNewUsableKey) { + ::ndk::ScopedAStatus err; + if (mListener != nullptr) { + err = mListener->onKeysChange(in_sessionId, in_keyStatusList, + in_hasNewUsableKey); + } else { + ALOGE("Null event listener, event not sent"); + } + if (!err.isOk()) { + ALOGW("sendKeysChange failed %s", err.getDescription().c_str()); + } + return; +} + +void WVDrmPlugin::sendSessionLostState(const vector& in_sessionId) { + ::ndk::ScopedAStatus err; + if (mListener != nullptr) { + err = mListener->onSessionLostState(in_sessionId); + } else { + ALOGE("Null event listener, event not sent"); + } + if (!err.isOk()) { + ALOGW("sendSessionLostState failed %s", err.getDescription().c_str()); + } + return; +} + +::ndk::ScopedAStatus WVDrmPlugin::getLogMessages( + vector<::aidl::android::hardware::drm::LogMessage>* _aidl_return) { + const vector& logs(wvutil::g_logbuf.getLogs()); + vector<::aidl::android::hardware::drm::LogMessage> msgs; + for (auto log : logs) { + msgs.push_back( + {log.time_ms_, toAidlLogPriority(log.priority_), log.message_}); + } + *_aidl_return = msgs; + return toNdkScopedAStatus(Status::OK); +} + +::ndk::ScopedAStatus WVDrmPlugin::requiresSecureDecoder( + const std::string& in_mime, SecurityLevel in_level, bool* _aidl_return) { + if (!strncasecmp(in_mime.c_str(), "video/", 6)) { + // Type is video, so check level to see if we require a secure decoder. + *_aidl_return = in_level == SecurityLevel::HW_SECURE_ALL || + in_level == SecurityLevel::HW_SECURE_DECODE; + } else { + // Type is not video, so never require a secure decoder. + *_aidl_return = false; + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVDrmPlugin::requiresSecureDecoderDefault( + const std::string& in_mime, bool* _aidl_return) { + if (!strncasecmp(in_mime.c_str(), "video/", 6)) { + // Type is video, so check level to see if we require a secure decoder. + std::string level(mPropertySet.security_level()); + + if (level == kResetSecurityLevel) { + mCDM->QueryStatus(wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, + &level); + } + + *_aidl_return = level == wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1; + } else { + // Type is not video, so never require a secure decoder. + *_aidl_return = false; + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus WVDrmPlugin::setPlaybackId( + const vector& in_sessionId, const std::string& in_playbackId) { + CdmSessionId cdmSessionId(in_sessionId.begin(), in_sessionId.end()); + CdmResponseType res = mCDM->SetPlaybackId(cdmSessionId, in_playbackId); + return toNdkScopedAStatus(mapCdmResponseType(res)); +} + +void WVDrmPlugin::OnSessionRenewalNeeded(const CdmSessionId& cdmSessionId) { + const vector sessionId = StrToVector(cdmSessionId); + const vector data; // data is ignored + sendEvent(EventType::KEY_NEEDED, sessionId, data); +} + +void WVDrmPlugin::OnSessionKeysChange(const CdmSessionId& cdmSessionId, + const CdmKeyStatusMap& cdmKeysStatus, + bool hasNewUsableKey) { + bool expired = false; + vector keyStatusList; + for (CdmKeyStatusMap::const_iterator it = cdmKeysStatus.begin(); + it != cdmKeysStatus.end(); ++it) { + const KeyId& keyId = it->first; + const CdmKeyStatus cdmKeyStatus = it->second; + if (cdmKeyStatus == wvcdm::kKeyStatusExpired) expired = true; + + KeyStatus keyStatus; + keyStatus.keyId = StrToVector(keyId); + keyStatus.type = ConvertFromCdmKeyStatus(cdmKeyStatus); + keyStatusList.push_back(keyStatus); + } + + const vector sessionId = StrToVector(cdmSessionId); + const vector data; // data is ignored + sendKeysChange(sessionId, keyStatusList, hasNewUsableKey); + // For backward compatibility. + if (expired) { + sendEvent(EventType::KEY_EXPIRED, sessionId, data); + } +} + +void WVDrmPlugin::OnExpirationUpdate(const CdmSessionId& cdmSessionId, + int64_t newExpiryTimeSeconds) { + const vector sessionId = StrToVector(cdmSessionId); + int64_t newExpiryTimeMilliseconds = + newExpiryTimeSeconds == wvcdm::NEVER_EXPIRES + ? newExpiryTimeSeconds + : newExpiryTimeSeconds * 1000; + + sendExpirationUpdate(sessionId, newExpiryTimeMilliseconds); +} + +void WVDrmPlugin::OnSessionLostState(const CdmSessionId& cdmSessionId) { + const vector sessionId = StrToVector(cdmSessionId); + sendSessionLostState(sessionId); +} + +Status WVDrmPlugin::queryProperty(const std::string& property, + std::string& stringValue) const { + return queryProperty(getRequestedSecurityLevel(), property, stringValue); +} + +Status WVDrmPlugin::queryProperty(RequestedSecurityLevel securityLevel, + const std::string& property, + std::string& stringValue) const { + CdmResponseType res = + mCDM->QueryStatus(securityLevel, property, &stringValue); + + if (res != wvcdm::NO_ERROR) { + ALOGE("Error querying CDM status: %u", res); + } + return mapCdmResponseType(res); +} + +Status WVDrmPlugin::queryProperty(const std::string& property, + vector& vector_value) const { + std::string string_value; + Status status = queryProperty(property, string_value); + if (status != Status::OK) return status; + vector_value = StrToVector(string_value); + return Status::OK; +} + +bool WVDrmPlugin::isProvisioned(wvcdm::CdmSecurityLevel securityLevel, + const std::string& origin, + const std::string& spoid, + bool atsc_mode_enabled) const { + return mCDM->IsProvisioned(securityLevel, origin, spoid, atsc_mode_enabled); +} + +Status WVDrmPlugin::mapAndNotifyOfCdmResponseType( + const vector& sessionId, CdmResponseType res) { + notifyOfCdmResponseType(sessionId, res); + return mapCdmResponseType(res); +} + +void WVDrmPlugin::notifyOfCdmResponseType(const vector& sessionId, + CdmResponseType res) { + const vector data; // data is ignored + if (res == wvcdm::NEED_PROVISIONING) { + sendEvent(EventType::PROVISION_REQUIRED, sessionId, data); + } else if (res == wvcdm::NEED_KEY) { + sendEvent(EventType::KEY_NEEDED, sessionId, data); + } +} + +Status WVDrmPlugin::mapAndNotifyOfOEMCryptoResult( + const vector& sessionId, OEMCryptoResult res) { + const vector data; // data is ignored + if (res == OEMCrypto_ERROR_NO_DEVICE_KEY) { + sendEvent(EventType::PROVISION_REQUIRED, sessionId, data); + } + return mapOEMCryptoResult(res); +} + +Status WVDrmPlugin::mapOEMCryptoResult(OEMCryptoResult res) { + switch (res) { + case OEMCrypto_SUCCESS: + return Status::OK; + + case OEMCrypto_ERROR_SIGNATURE_FAILURE: + return Status::ERROR_DRM_INVALID_STATE; + + case OEMCrypto_ERROR_NO_DEVICE_KEY: + return Status::ERROR_DRM_NOT_PROVISIONED; + + case OEMCrypto_ERROR_INVALID_SESSION: + return Status::ERROR_DRM_SESSION_NOT_OPENED; + + case OEMCrypto_ERROR_TOO_MANY_SESSIONS: + case OEMCrypto_ERROR_INSUFFICIENT_RESOURCES: + return Status::ERROR_DRM_RESOURCE_BUSY; + + case OEMCrypto_ERROR_NOT_IMPLEMENTED: + return Status::ERROR_DRM_CANNOT_HANDLE; + + case OEMCrypto_ERROR_INVALID_RSA_KEY: + case OEMCrypto_ERROR_SHORT_BUFFER: + case OEMCrypto_ERROR_UNKNOWN_FAILURE: + case OEMCrypto_ERROR_OPEN_SESSION_FAILED: + FALLTHROUGH_INTENDED; /* FALLTHROUGH */ + default: + ALOGW("Returns UNKNOWN error for legacy status: %d", res); + return static_cast(Status::GENERAL_OEM_ERROR); + } +} + +RequestedSecurityLevel WVDrmPlugin::getRequestedSecurityLevel() const { + return mPropertySet.security_level().compare( + wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3) == 0 + ? wvcdm::kLevel3 + : wvcdm::kLevelDefault; +} + +bool WVDrmPlugin::initDataResemblesPSSH(const vector& initData) { + const uint8_t* const initDataArray = initData.data(); + + if (sizeof(uint32_t) + kPsshTag.size() > initData.size()) { + // The init data is so small that it couldn't contain a size and PSSH tag. + return false; + } + + // Extract the size field + const uint8_t* const sizeField = &initDataArray[0]; + uint32_t nboSize; + memcpy(&nboSize, sizeField, sizeof(nboSize)); + uint32_t size = ntohl(nboSize); + + if (size > initData.size()) { + return false; + } + + // Extract the ID field + const char* const idField = + reinterpret_cast(&initDataArray[sizeof(nboSize)]); + std::string id(idField, kPsshTag.size()); + return id == kPsshTag; +} + +Status WVDrmPlugin::unprovision(const CdmIdentifier& identifier) { + if (mPropertySet.use_atsc_mode()) + return mapCdmResponseType(wvcdm::PROVISIONING_NOT_ALLOWED_FOR_ATSC); + + CdmResponseType res1 = mCDM->Unprovision(wvcdm::kSecurityLevelL1, identifier); + CdmResponseType res3 = mCDM->Unprovision(wvcdm::kSecurityLevelL3, identifier); + if (!isCdmResponseTypeSuccess(res1)) { + return mapCdmResponseType(res1); + } else { + return mapCdmResponseType(res3); + } +} + +// Implementation for the CdmIdentifierBuilder inner class +WVDrmPlugin::CdmIdentifierBuilder::CdmIdentifierBuilder( + bool useSpoid, const WVDrmPlugin& parent, const std::string& appPackageName) + : mCdmIdentifier(), + mIsIdentifierSealed(false), + mUseSpoid(useSpoid), + mAppPackageName(appPackageName), + mParent(parent) { + mCdmIdentifier.app_package_name = mAppPackageName; + mCdmIdentifier.unique_id = getNextUniqueId(); + mCdmIdentifier.user_id = wvutil::GetIpcCallingUid(); +} + +Status WVDrmPlugin::CdmIdentifierBuilder::getCdmIdentifier( + CdmIdentifier* identifier) { + if (!mIsIdentifierSealed) { + Status res = calculateSpoid(); + if (res != Status::OK) return res; + mIsIdentifierSealed = true; + } + *identifier = mCdmIdentifier; + return Status::OK; +} + +Status WVDrmPlugin::CdmIdentifierBuilder::getDeviceUniqueId(std::string* id) { + if (mUseSpoid) { + CdmIdentifier identifier; + Status res = getCdmIdentifier(&identifier); + if (res != Status::OK) return res; + + *id = identifier.spoid; + return Status::OK; + } else { + return getOemcryptoDeviceId(id); + } +} + +Status WVDrmPlugin::CdmIdentifierBuilder::getProvisioningUniqueId( + std::string* id) { + if (mUseSpoid) { + // To fake a provisioning-unique ID on SPOID devices where we can't expose + // the real provisioning-unique ID, we just use the SPOID and invert all + // the bits. + Status res = getDeviceUniqueId(id); + if (res != Status::OK) return res; + + for (char& c : *id) { + c = ~c; + } + + return Status::OK; + } else { + return mParent.queryProperty(wvcdm::QUERY_KEY_PROVISIONING_ID, *id); + } +} + +bool WVDrmPlugin::CdmIdentifierBuilder::set_origin(const std::string& id) { + if (mIsIdentifierSealed) return false; + mCdmIdentifier.origin = id; + return true; +} + +bool WVDrmPlugin::CdmIdentifierBuilder::set_use_atsc_mode(bool enable) { + if (is_sealed()) return false; + mCdmIdentifier.app_package_name = + enable ? wvcdm::ATSC_APP_PACKAGE_NAME : mAppPackageName; + return true; +} + +Status WVDrmPlugin::CdmIdentifierBuilder::calculateSpoid() { + if (!mUseSpoid) return Status::OK; + + // Calculate SPOID for default security level if appropriate + std::string deviceId; + if (mParent.getRequestedSecurityLevel() == wvcdm::kLevelDefault) { + Status res = getOemcryptoDeviceId(&deviceId); + if (res != Status::OK) return res; + + return calculateSpoid(deviceId, &mCdmIdentifier.spoid); + } + + // If requested security level is L3, possibilities are + // (a) L3 has not been provisioned + // (b) L3 was provisioned with L3 device ID in the CdmIdentifier + // (c) L3 was provisioned (incorrectly) with L1 device ID in the + // CdmIdentifier Check (b) first. Get L3 device ID, calculate SPOID and if + // provisioned with this SPOID, return this SPOID. Check (c) next. Get L1 + // device ID, calculate SPOID and if provisioned with this SPOID, return + // this SPOID. On any errors in (c) or not provisioned return L3 SPOID. + Status res = getOemcryptoDeviceId(wvcdm::kLevel3, &deviceId); + if (res != Status::OK) return res; + + std::string spoidL3; + res = calculateSpoid(deviceId, &spoidL3); + if (res != Status::OK) return res; + + bool atsc_mode_enabled = + mCdmIdentifier.app_package_name == wvcdm::ATSC_APP_PACKAGE_NAME; + + if (mParent.isProvisioned(wvcdm::kSecurityLevelL3, origin(), spoidL3, + atsc_mode_enabled)) { + mCdmIdentifier.spoid = spoidL3; + return Status::OK; + } + + // Not provisioned with CdmIdentifier containing SPOID with L3 device ID. + // Try SPOID with L1 device ID. + std::string deviceIdLevelDefault; + res = getOemcryptoDeviceId(wvcdm::kLevelDefault, &deviceIdLevelDefault); + if (res != Status::OK) { + mCdmIdentifier.spoid = spoidL3; + return Status::OK; + } + + // If the L3 and default security level IDs are identical then the + // device does not support L1. + if (deviceId == deviceIdLevelDefault) { + mCdmIdentifier.spoid = spoidL3; + return Status::OK; + } + + std::string spoidLevelDefault; + res = calculateSpoid(deviceIdLevelDefault, &spoidLevelDefault); + if (res != Status::OK) { + mCdmIdentifier.spoid = spoidL3; + return Status::OK; + } + + if (mParent.isProvisioned(wvcdm::kSecurityLevelL1, origin(), + spoidLevelDefault, atsc_mode_enabled)) { + mCdmIdentifier.spoid = spoidLevelDefault; + return Status::OK; + } + + // Not provisioned with CdmIdentifier containing SPOID with L1 or L3 + // device ID. Return L3 SPOID. + mCdmIdentifier.spoid = spoidL3; + return Status::OK; +} + +Status WVDrmPlugin::CdmIdentifierBuilder::calculateSpoid( + const std::string& deviceId, std::string* spoid) { + if (spoid == nullptr) return Status::ERROR_DRM_CANNOT_HANDLE; + + if (!mUseSpoid) { + spoid->clear(); + return Status::OK; + } + + uint8_t hash[SHA256_DIGEST_LENGTH]; + SHA256_CTX ctx; + SHA256_Init(&ctx); + SHA256_Update(&ctx, deviceId.data(), deviceId.length()); + SHA256_Update(&ctx, mAppPackageName.data(), mAppPackageName.length()); + SHA256_Update(&ctx, origin().data(), origin().length()); + SHA256_Final(hash, &ctx); + + *spoid = std::string(reinterpret_cast(hash), SHA256_DIGEST_LENGTH); + return Status::OK; +} + +Status WVDrmPlugin::CdmIdentifierBuilder::getOemcryptoDeviceId( + std::string* id) { + return mParent.queryProperty(wvcdm::QUERY_KEY_DEVICE_ID, *id); +} + +Status WVDrmPlugin::CdmIdentifierBuilder::getOemcryptoDeviceId( + wvcdm::RequestedSecurityLevel securityLevel, std::string* id) { + return mParent.queryProperty(securityLevel, wvcdm::QUERY_KEY_DEVICE_ID, *id); +} + +uint32_t WVDrmPlugin::CdmIdentifierBuilder::getNextUniqueId() { + // Start with 1. 0 is reserved for the default cdm identifier. + static uint32_t unique_id = 1; + return ++unique_id; +} + +} // namespace widevine +} // namespace drm +} // namespace hardware +} // namespace wvdrm diff --git a/libwvdrmengine/mediadrm/aidl_src/WVGenericCryptoInterface.cpp b/libwvdrmengine/mediadrm/aidl_src/WVGenericCryptoInterface.cpp new file mode 100644 index 00000000..19c6f6b9 --- /dev/null +++ b/libwvdrmengine/mediadrm/aidl_src/WVGenericCryptoInterface.cpp @@ -0,0 +1,50 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +//#define LOG_NDEBUG 0 +#define LOG_TAG "WVCdm" +#include + +#include "WVGenericCryptoInterface.h" + +#include "wv_cdm_constants.h" + +namespace wvdrm { + +using namespace std; +using namespace wvcdm; + +OEMCryptoResult WVGenericCryptoInterface::signRSA(const uint8_t* wrapped_rsa_key, + size_t wrapped_rsa_key_length, + const uint8_t* message, + size_t message_length, + std::vector& signature, + RSA_Padding_Scheme padding_scheme) { + OEMCrypto_SESSION session; + OEMCryptoResult sts = OEMCrypto_OpenSession(&session); + if (sts != OEMCrypto_SUCCESS) return sts; + sts = OEMCrypto_LoadDRMPrivateKey(session, OEMCrypto_RSA_Private_Key, + wrapped_rsa_key, wrapped_rsa_key_length); + if (sts == OEMCrypto_SUCCESS) { + size_t signatureSize = 0; + sts = OEMCrypto_GenerateRSASignature(session, message, message_length, + NULL, &signatureSize, + padding_scheme); + if (sts == OEMCrypto_SUCCESS) { + // Should be short buffer. + sts = OEMCrypto_ERROR_UNKNOWN_FAILURE; + } else if (sts == OEMCrypto_ERROR_SHORT_BUFFER) { + signature.resize(signatureSize); + sts = OEMCrypto_GenerateRSASignature(session, message, message_length, + signature.data(), &signatureSize, + padding_scheme); + } + } + OEMCrypto_CloseSession(session); + return sts; +} + +} // namespace wvdrm diff --git a/libwvdrmengine/mediadrm/aidl_src/wv_metrics_adapter.cpp b/libwvdrmengine/mediadrm/aidl_src/wv_metrics_adapter.cpp new file mode 100644 index 00000000..95582f19 --- /dev/null +++ b/libwvdrmengine/mediadrm/aidl_src/wv_metrics_adapter.cpp @@ -0,0 +1,595 @@ +// +// Copyright 2021 Google LLC. All Rights Reserved. This file and proprietary +// source code may only be used and distributed under the Widevine License +// Agreement. +// + +#include "wv_metrics_adapter.h" + +#include "wv_metrics.pb.h" + +namespace wvcdm { + +using ::aidl::android::hardware::drm::DrmMetric; +using ::aidl::android::hardware::drm::DrmMetricGroup; +using ::aidl::android::hardware::drm::DrmMetricNamedValue; +using ::aidl::android::hardware::drm::DrmMetricValue; + +using drm_metrics::CounterMetric; +using drm_metrics::DistributionMetric; +using google::protobuf::RepeatedPtrField; + +namespace { + +const char kAttributeErrorCode[] = "error_code"; +const char kAttributeErrorCodeBool[] = "error_code_bool"; +const char kAttributeCdmSecurityLevel[] = "cdm_security_level"; +const char kAttributeSecurityLevel[] = "security_level"; +const char kAttributeLength[] = "length"; +const char kAttributeEncryptionAlgorithm[] = "encryption_algorithm"; +const char kAttributeSigningAlgorithm[] = "signing_algorithm"; +const char kAttributeOemCryptoResult[] = "oem_crypto_result"; +const char kAttributeKeyStatusType[] = "key_status_type"; +const char kAttributeEventType[] = "event_type"; +const char kAttributeKeyRequestType[] = "key_request_type"; +const char kAttributeLicenseType[] = "license_type"; + +template +void SetValue(const T& value, DrmMetricNamedValue* attribute); + +template <> +void SetValue(const int& value, DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +void SetValue(const bool& value, DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +void SetValue(const float& value, DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +void SetValue(const double& value, DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +__attribute__((unused)) void SetValue(const long& value, + DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +__attribute__((unused)) void SetValue(const long long& value, + DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +void SetValue(const std::string& value, DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +void SetValue(const unsigned int& value, DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +__attribute__((unused)) void SetValue(const unsigned long& value, + DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} +template <> +__attribute__((unused)) void SetValue(const unsigned long long& value, + DrmMetricNamedValue* attribute) { + attribute->value = DrmMetricValue::make(value); +} + +template +void AddAttribute(const std::string& name, T value, + std::vector* attribute_vector) { + // Set the default values. + DrmMetricNamedValue attribute; + attribute.name = name; + SetValue(value, &attribute); + attribute_vector->push_back(attribute); +} + +} // anonymous namespace + +void WvMetricsGroupBuilder::AddDistributions( + const std::string& name, + const RepeatedPtrField& distributions) { + for (const auto& metric : distributions) { + AddDistribution(name, metric); + } +} + +void WvMetricsGroupBuilder::AddCounters( + const std::string& name, + const RepeatedPtrField& counters) { + for (const auto& counter : counters) { + AddCounter(name, counter); + } +} + +void WvMetricsGroupBuilder::AddDistribution( + const std::string& name, + const drm_metrics::DistributionMetric& distribution) { + DrmMetric metric; + metric.name = name; + AddAttributes(distribution.attributes(), &(metric.attributes)); + + DrmMetricNamedValue mean, count; + mean.name = "mean"; + SetValue(distribution.mean(), &mean); + count.name = "count"; + SetValue(distribution.operation_count(), &count); + + if (distribution.operation_count() == 1) { + metric.values.resize(2); + metric.values[0] = mean; + metric.values[1] = count; + } else { + DrmMetricNamedValue min, max, variance; + min.name = "min"; + SetValue(distribution.min(), &min); + max.name = "max"; + SetValue(distribution.max(), &max); + variance.name = "variance"; + SetValue(distribution.variance(), &variance); + metric.values.resize(5); + metric.values[0] = mean; + metric.values[1] = count; + metric.values[2] = min; + metric.values[3] = max; + metric.values[4] = variance; + } + metrics_.push_back(metric); +} + +void WvMetricsGroupBuilder::AddCounter( + const std::string& name, const drm_metrics::CounterMetric& counter) { + DrmMetric metric; + metric.name = name; + AddAttributes(counter.attributes(), &(metric.attributes)); + + DrmMetricNamedValue count; + count.name = "count"; + SetValue(counter.count(), &count); + + metric.values.resize(1); + metric.values[0] = count; + metrics_.push_back(metric); +} + +void WvMetricsGroupBuilder::AddValue( + const std::string& name, const drm_metrics::ValueMetric& value_or_error) { + DrmMetric metric; + DrmMetricNamedValue value; + + metric.name = name; + if (value_or_error.has_error_code()) { + value.name = "error_code"; + SetValue(value_or_error.error_code(), &value); + } else if (value_or_error.has_int_value()) { + value.name = "value"; + SetValue(value_or_error.int_value(), &value); + } else if (value_or_error.has_double_value()) { + value.name = "value"; + SetValue(value_or_error.double_value(), &value); + } else if (value_or_error.has_string_value()) { + value.name = "value"; + SetValue(value_or_error.string_value(), &value); + } else { + value.name = "error"; + SetValue(std::string("Unexpected value type"), &value); + } + metric.values.resize(1); + metric.values[0] = value; + metrics_.push_back(metric); +} + +void WvMetricsGroupBuilder::AddAttributes( + const drm_metrics::Attributes& attributes_proto, + std::vector* attributes) { + std::vector attribute_vector; + if (attributes_proto.has_error_code()) { + AddAttribute(kAttributeErrorCode, attributes_proto.error_code(), + &attribute_vector); + } + if (attributes_proto.has_error_code_bool()) { + AddAttribute(kAttributeErrorCodeBool, attributes_proto.error_code_bool(), + &attribute_vector); + } + if (attributes_proto.has_cdm_security_level()) { + AddAttribute(kAttributeCdmSecurityLevel, + attributes_proto.cdm_security_level(), &attribute_vector); + } + if (attributes_proto.has_security_level()) { + AddAttribute(kAttributeSecurityLevel, attributes_proto.security_level(), + &attribute_vector); + } + if (attributes_proto.has_length()) { + AddAttribute(kAttributeLength, attributes_proto.length(), + &attribute_vector); + } + if (attributes_proto.has_encryption_algorithm()) { + AddAttribute(kAttributeEncryptionAlgorithm, + attributes_proto.encryption_algorithm(), &attribute_vector); + } + if (attributes_proto.has_signing_algorithm()) { + AddAttribute(kAttributeSigningAlgorithm, + attributes_proto.signing_algorithm(), &attribute_vector); + } + if (attributes_proto.has_oem_crypto_result()) { + AddAttribute(kAttributeOemCryptoResult, + attributes_proto.oem_crypto_result(), &attribute_vector); + } + if (attributes_proto.has_key_status_type()) { + AddAttribute(kAttributeKeyStatusType, attributes_proto.key_status_type(), + &attribute_vector); + } + if (attributes_proto.has_event_type()) { + AddAttribute(kAttributeEventType, attributes_proto.event_type(), + &attribute_vector); + } + if (attributes_proto.has_key_request_type()) { + AddAttribute(kAttributeKeyRequestType, attributes_proto.key_request_type(), + &attribute_vector); + } + if (attributes_proto.has_license_type()) { + AddAttribute(kAttributeLicenseType, attributes_proto.license_type(), + &attribute_vector); + } + + *attributes = attribute_vector; +} + +DrmMetricGroup WvMetricsGroupBuilder::Build() { + DrmMetricGroup metric_group; + metric_group.metrics = metrics_; + return metric_group; +} + +WvMetricsGroupBuilder::WvMetricsGroupBuilder() {} + +WvMetricsAdapter::WvMetricsAdapter() {} +WvMetricsAdapter::~WvMetricsAdapter() {} + +void WvMetricsAdapter::AddEngineMetrics( + const drm_metrics::WvCdmMetrics::EngineMetrics& proto_metrics) { + WvMetricsGroupBuilder group_builder; + AddCryptoMetrics(proto_metrics.crypto_metrics(), &group_builder); + + if (proto_metrics.has_oemcrypto_initialization_mode()) { + group_builder.AddValue("oemcrypto_initialization_mode", + proto_metrics.oemcrypto_initialization_mode()); + } + if (proto_metrics.has_oemcrypto_l1_api_version()) { + group_builder.AddValue("oemcrypto_l1_api_version", + proto_metrics.oemcrypto_l1_api_version()); + } + if (proto_metrics.has_oemcrypto_l1_min_api_version()) { + group_builder.AddValue("oemcrypto_l1_min_api_version", + proto_metrics.oemcrypto_l1_min_api_version()); + } + if (proto_metrics.has_app_package_name()) { + group_builder.AddValue("app_package_name", + proto_metrics.app_package_name()); + } + group_builder.AddDistributions("cdm_engine_add_key_time_us", + proto_metrics.cdm_engine_add_key_time_us()); + if (proto_metrics.has_cdm_engine_cdm_version()) { + group_builder.AddValue("cdm_engine_cdm_version", + proto_metrics.cdm_engine_cdm_version()); + } + group_builder.AddCounters("cdm_engine_close_session", + proto_metrics.cdm_engine_close_session()); + if (proto_metrics.has_cdm_engine_creation_time_millis()) { + group_builder.AddValue("cdm_engine_creation_time_millis", + proto_metrics.cdm_engine_creation_time_millis()); + } + group_builder.AddDistributions("cdm_engine_decrypt_time_us", + proto_metrics.cdm_engine_decrypt_time_us()); + group_builder.AddCounters("cdm_engine_find_session_for_key", + proto_metrics.cdm_engine_find_session_for_key()); + group_builder.AddDistributions( + "cdm_engine_generate_key_request_time_us", + proto_metrics.cdm_engine_generate_key_request_time_us()); + group_builder.AddDistributions( + "cdm_engine_get_provisioning_request_time_us", + proto_metrics.cdm_engine_get_provisioning_request_time_us()); + group_builder.AddCounters("cdm_engine_get_secure_stop_ids", + proto_metrics.cdm_engine_get_secure_stop_ids()); + group_builder.AddDistributions( + "cdm_engine_get_usage_info_time_us", + proto_metrics.cdm_engine_get_usage_info_time_us()); + group_builder.AddDistributions( + "cdm_engine_handle_provisioning_response_time_us", + proto_metrics.cdm_engine_handle_provisioning_response_time_us()); + if (proto_metrics.has_cdm_engine_life_span_ms()) { + group_builder.AddValue("cdm_engine_life_span_ms", + proto_metrics.cdm_engine_life_span_ms()); + } + group_builder.AddCounters("cdm_engine_open_key_set_session", + proto_metrics.cdm_engine_open_key_set_session()); + group_builder.AddCounters("cdm_engine_open_session", + proto_metrics.cdm_engine_open_session()); + group_builder.AddDistributions( + "cdm_engine_query_key_status_time_us", + proto_metrics.cdm_engine_query_key_status_time_us()); + group_builder.AddCounters("cdm_engine_release_all_usage_info", + proto_metrics.cdm_engine_release_all_usage_info()); + group_builder.AddCounters("cdm_engine_release_usage_info", + proto_metrics.cdm_engine_release_usage_info()); + group_builder.AddCounters("cdm_engine_remove_all_usage_info", + proto_metrics.cdm_engine_remove_all_usage_info()); + group_builder.AddCounters("cdm_engine_remove_keys", + proto_metrics.cdm_engine_remove_keys()); + group_builder.AddCounters("cdm_engine_remove_usage_info", + proto_metrics.cdm_engine_remove_usage_info()); + group_builder.AddDistributions( + "cdm_engine_restore_key_time_us", + proto_metrics.cdm_engine_restore_key_time_us()); + group_builder.AddCounters("cdm_engine_unprovision", + proto_metrics.cdm_engine_unprovision()); + if (proto_metrics.has_level3_oemcrypto_initialization_error()) { + group_builder.AddValue( + "level3_oemcrypto_initialization_error", + proto_metrics.level3_oemcrypto_initialization_error()); + } + if (proto_metrics.has_previous_oemcrypto_initialization_failure()) { + group_builder.AddValue( + "previous_oemcrypto_initialization_failure", + proto_metrics.previous_oemcrypto_initialization_failure()); + } + + group_vector_.emplace_back(group_builder.Build()); +} + +void WvMetricsAdapter::AddSessionMetrics( + const drm_metrics::WvCdmMetrics::SessionMetrics& proto_metrics) { + WvMetricsGroupBuilder group_builder; + AddCryptoMetrics(proto_metrics.crypto_metrics(), &group_builder); + + if (proto_metrics.has_session_id()) { + group_builder.AddValue("session_id", proto_metrics.session_id()); + } + if (proto_metrics.has_cdm_session_life_span_ms()) { + group_builder.AddValue("cdm_session_life_span_ms", + proto_metrics.cdm_session_life_span_ms()); + } + group_builder.AddDistributions("cdm_session_renew_key_time_us", + proto_metrics.cdm_session_renew_key_time_us()); + group_builder.AddCounters( + "cdm_session_restore_offline_session", + proto_metrics.cdm_session_restore_offline_session()); + group_builder.AddCounters("cdm_session_restore_usage_session", + proto_metrics.cdm_session_restore_usage_session()); + group_builder.AddDistributions( + "cdm_session_license_request_latency_ms", + proto_metrics.cdm_session_license_request_latency_ms()); + if (proto_metrics.has_oemcrypto_build_info()) { + group_builder.AddValue("oemcrypto_build_info", + proto_metrics.oemcrypto_build_info()); + } + if (proto_metrics.has_license_sdk_version()) { + group_builder.AddValue("license_sdk_version", + proto_metrics.license_sdk_version()); + } + if (proto_metrics.has_license_service_version()) { + group_builder.AddValue("license_service_version", + proto_metrics.license_service_version()); + } + if (proto_metrics.has_playback_id()) { + group_builder.AddValue("playback_id", proto_metrics.playback_id()); + } + group_vector_.emplace_back(group_builder.Build()); +} + +void WvMetricsAdapter::AddCryptoMetrics( + const drm_metrics::WvCdmMetrics::CryptoMetrics& proto_metrics, + WvMetricsGroupBuilder* group_builder) { + if (proto_metrics.has_crypto_session_security_level()) { + group_builder->AddValue("crypto_session_security_level", + proto_metrics.crypto_session_security_level()); + } + group_builder->AddCounters( + "crypto_session_delete_all_usage_reports", + proto_metrics.crypto_session_delete_all_usage_reports()); + group_builder->AddCounters( + "crypto_session_delete_multiple_usage_information", + proto_metrics.crypto_session_delete_multiple_usage_information()); + group_builder->AddDistributions( + "crypto_session_generic_decrypt_time_us", + proto_metrics.crypto_session_generic_decrypt_time_us()); + group_builder->AddDistributions( + "crypto_session_generic_encrypt_time_us", + proto_metrics.crypto_session_generic_encrypt_time_us()); + group_builder->AddDistributions( + "crypto_session_generic_sign_time_us", + proto_metrics.crypto_session_generic_sign_time_us()); + group_builder->AddDistributions( + "crypto_session_generic_verify_time_us", + proto_metrics.crypto_session_generic_verify_time_us()); + group_builder->AddCounters( + "crypto_session_get_device_unique_id", + proto_metrics.crypto_session_get_device_unique_id()); + group_builder->AddCounters("crypto_session_get_token", + proto_metrics.crypto_session_get_token()); + if (proto_metrics.has_crypto_session_life_span()) { + group_builder->AddValue("crypto_session_life_span", + proto_metrics.crypto_session_life_span()); + } + group_builder->AddDistributions( + "crypto_session_load_certificate_private_key_time_us", + proto_metrics.crypto_session_load_certificate_private_key_time_us()); + group_builder->AddDistributions("crypto_session_open_time_us", + proto_metrics.crypto_session_open_time_us()); + if (proto_metrics.has_crypto_session_system_id()) { + group_builder->AddValue("crypto_session_system_id", + proto_metrics.crypto_session_system_id()); + } + group_builder->AddDistributions( + "crypto_session_update_usage_information_time_us", + proto_metrics.crypto_session_update_usage_information_time_us()); + if (proto_metrics.has_crypto_session_usage_information_support()) { + group_builder->AddValue( + "crypto_session_usage_information_support", + proto_metrics.crypto_session_usage_information_support()); + } + if (proto_metrics.has_usage_table_header_initial_size()) { + group_builder->AddValue("usage_table_header_initial_size", + proto_metrics.usage_table_header_initial_size()); + } + group_builder->AddCounters("usage_table_header_add_entry", + proto_metrics.usage_table_header_add_entry()); + group_builder->AddCounters("usage_table_header_delete_entry", + proto_metrics.usage_table_header_delete_entry()); + group_builder->AddDistributions( + "usage_table_header_update_entry_time_us", + proto_metrics.usage_table_header_update_entry_time_us()); + group_builder->AddCounters("usage_table_header_load_entry", + proto_metrics.usage_table_header_load_entry()); + if (proto_metrics.has_oemcrypto_api_version()) { + group_builder->AddValue("oemcrypto_api_version", + proto_metrics.oemcrypto_api_version()); + } + group_builder->AddCounters("oemcrypto_close_session", + proto_metrics.oemcrypto_close_session()); + group_builder->AddDistributions( + "oemcrypto_copy_buffer_time_us", + proto_metrics.oemcrypto_copy_buffer_time_us()); + if (proto_metrics.has_oemcrypto_current_hdcp_capability()) { + group_builder->AddValue("oemcrypto_current_hdcp_capability", + proto_metrics.oemcrypto_current_hdcp_capability()); + } + group_builder->AddCounters("oemcrypto_deactivate_usage_entry", + proto_metrics.oemcrypto_deactivate_usage_entry()); + group_builder->AddDistributions( + "oemcrypto_decrypt_cenc_time_us", + proto_metrics.oemcrypto_decrypt_cenc_time_us()); + group_builder->AddCounters("oemcrypto_delete_usage_entry", + proto_metrics.oemcrypto_delete_usage_entry()); + group_builder->AddCounters("oemcrypto_delete_usage_table", + proto_metrics.oemcrypto_delete_usage_table()); + group_builder->AddDistributions( + "oemcrypto_derive_keys_from_session_key_time_us", + proto_metrics.oemcrypto_derive_keys_from_session_key_time_us()); + group_builder->AddCounters( + "oemcrypto_force_delete_usage_entry", + proto_metrics.oemcrypto_force_delete_usage_entry()); + group_builder->AddDistributions( + "oemcrypto_generate_derived_keys_time_us", + proto_metrics.oemcrypto_generate_derived_keys_time_us()); + group_builder->AddCounters("oemcrypto_generate_nonce", + proto_metrics.oemcrypto_generate_nonce()); + group_builder->AddDistributions( + "oemcrypto_generate_rsa_signature_time_us", + proto_metrics.oemcrypto_generate_rsa_signature_time_us()); + group_builder->AddDistributions( + "oemcrypto_generate_signature_time_us", + proto_metrics.oemcrypto_generate_signature_time_us()); + group_builder->AddDistributions( + "oemcrypto_generic_decrypt_time_us", + proto_metrics.oemcrypto_generic_decrypt_time_us()); + group_builder->AddDistributions( + "oemcrypto_generic_encrypt_time_us", + proto_metrics.oemcrypto_generic_encrypt_time_us()); + group_builder->AddDistributions( + "oemcrypto_generic_sign_time_us", + proto_metrics.oemcrypto_generic_sign_time_us()); + group_builder->AddDistributions( + "oemcrypto_generic_verify_time_us", + proto_metrics.oemcrypto_generic_verify_time_us()); + group_builder->AddCounters("oemcrypto_get_device_id", + proto_metrics.oemcrypto_get_device_id()); + group_builder->AddDistributions( + "oemcrypto_get_key_data_time_us", + proto_metrics.oemcrypto_get_key_data_time_us()); + group_builder->AddCounters( + "oemcrypto_get_oem_public_certificate", + proto_metrics.oemcrypto_get_oem_public_certificate()); + group_builder->AddCounters("oemcrypto_get_random", + proto_metrics.oemcrypto_get_random()); + group_builder->AddDistributions("oemcrypto_initialize_time_us", + proto_metrics.oemcrypto_initialize_time_us()); + if (proto_metrics.has_oemcrypto_is_anti_rollback_hw_present()) { + group_builder->AddValue( + "oemcrypto_is_anti_rollback_hw_present", + proto_metrics.oemcrypto_is_anti_rollback_hw_present()); + } + if (proto_metrics.has_oemcrypto_is_keybox_valid()) { + group_builder->AddValue("oemcrypto_is_keybox_valid", + proto_metrics.oemcrypto_is_keybox_valid()); + } + group_builder->AddDistributions( + "oemcrypto_load_device_drm_key_time_us", + proto_metrics.oemcrypto_load_device_drm_key_time_us()); + group_builder->AddDistributions( + "oemcrypto_load_entitled_keys_time_us", + proto_metrics.oemcrypto_load_entitled_keys_time_us()); + group_builder->AddDistributions("oemcrypto_load_keys_time_us", + proto_metrics.oemcrypto_load_keys_time_us()); + if (proto_metrics.has_oemcrypto_max_hdcp_capability()) { + group_builder->AddValue("oemcrypto_max_hdcp_capability", + proto_metrics.oemcrypto_max_hdcp_capability()); + } + if (proto_metrics.has_oemcrypto_max_number_of_sessions()) { + group_builder->AddValue("oemcrypto_max_number_of_sessions", + proto_metrics.oemcrypto_max_number_of_sessions()); + } + if (proto_metrics.has_oemcrypto_number_of_open_sessions()) { + group_builder->AddValue("oemcrypto_number_of_open_sessions", + proto_metrics.oemcrypto_number_of_open_sessions()); + } + if (proto_metrics.has_oemcrypto_provisioning_method()) { + group_builder->AddValue("oemcrypto_provisioning_method", + proto_metrics.oemcrypto_provisioning_method()); + } + group_builder->AddDistributions( + "oemcrypto_refresh_keys_time_us", + proto_metrics.oemcrypto_refresh_keys_time_us()); + group_builder->AddCounters("oemcrypto_report_usage", + proto_metrics.oemcrypto_report_usage()); + group_builder->AddDistributions( + "oemcrypto_rewrap_device_rsa_key_time_us", + proto_metrics.oemcrypto_rewrap_device_rsa_key_time_us()); + group_builder->AddDistributions( + "oemcrypto_rewrap_device_rsa_key_30_time_us", + proto_metrics.oemcrypto_rewrap_device_rsa_key_30_time_us()); + if (proto_metrics.has_oemcrypto_security_patch_level()) { + group_builder->AddValue("oemcrypto_security_patch_level", + proto_metrics.oemcrypto_security_patch_level()); + } + group_builder->AddDistributions("oemcrypto_select_key_time_us", + proto_metrics.oemcrypto_select_key_time_us()); + if (proto_metrics.has_oemcrypto_usage_table_support()) { + group_builder->AddValue("oemcrypto_usage_table_support", + proto_metrics.oemcrypto_usage_table_support()); + } + group_builder->AddCounters("oemcrypto_update_usage_table", + proto_metrics.oemcrypto_update_usage_table()); + group_builder->AddCounters("oemcrypto_update_usage_entry", + proto_metrics.oemcrypto_update_usage_entry()); +} + +const std::vector WvMetricsAdapter::GetWvGroupVector() { + return group_vector_; +} + +void WvMetricsAdapter::ToWvMetrics( + const drm_metrics::WvCdmMetrics& proto_metrics, + std::vector* wv_metrics) { + // Convert the engine level metrics + wvcdm::WvMetricsAdapter adapter; + + if (proto_metrics.has_engine_metrics()) { + adapter.AddEngineMetrics(proto_metrics.engine_metrics()); + } + for (const auto& session_metrics : proto_metrics.session_metrics()) { + adapter.AddSessionMetrics(session_metrics); + } + + *wv_metrics = adapter.GetWvGroupVector(); +} + +} // namespace wvcdm diff --git a/libwvdrmengine/mediadrm/include_hidl/WVDrmPlugin.h b/libwvdrmengine/mediadrm/include_hidl/WVDrmPlugin.h index a6feade9..7e98a813 100644 --- a/libwvdrmengine/mediadrm/include_hidl/WVDrmPlugin.h +++ b/libwvdrmengine/mediadrm/include_hidl/WVDrmPlugin.h @@ -7,19 +7,20 @@ #ifndef WV_DRM_PLUGIN_H_ #define WV_DRM_PLUGIN_H_ -#include -#include +#include +#include +#include + +#include "HidlTypes.h" +#include "OEMCryptoCENC.h" +#include "WVGenericCryptoInterface.h" +#include "WVTypes.h" #include "cdm_client_property_set.h" #include "cdm_identifier.h" #include "log.h" #include "wv_cdm_event_listener.h" #include "wv_content_decryption_module.h" -#include "OEMCryptoCENC.h" -#include "HidlTypes.h" -#include "WVGenericCryptoInterface.h" -#include "WVTypes.h" -#include namespace wvdrm { namespace hardware { @@ -27,24 +28,23 @@ namespace drm { namespace V1_4 { namespace widevine { -using std::map; using android::Mutex; +using std::map; using wvcdm::CdmIdentifier; using wvcdm::CdmKeyStatusMap; -using wvcdm::CdmSessionId; using wvcdm::CdmResponseType; +using wvcdm::CdmSessionId; using wvcdm::WvContentDecryptionModule; const OEMCrypto_Algorithm kInvalidCryptoAlgorithm = static_cast(-1); -struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, - wvcdm::WvCdmEventListener { - +struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, + IDrmPluginListener, + wvcdm::WvCdmEventListener { WVDrmPlugin(const sp& cdm, const std::string& appPackageName, - WVGenericCryptoInterface* crypto, - bool useSpoid); + WVGenericCryptoInterface* crypto, bool useSpoid); virtual ~WVDrmPlugin(); @@ -52,53 +52,44 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, Return openSession(openSession_cb _hidl_cb) override; - Return openSession_1_1(SecurityLevel securityLevel, openSession_1_1_cb _hidl_cb) override; + Return openSession_1_1(SecurityLevel securityLevel, + openSession_1_1_cb _hidl_cb) override; Return closeSession(const hidl_vec& sessionId) override; - Return getKeyRequest( - const hidl_vec& scope, - const hidl_vec& initData, - const hidl_string& mimeType, - KeyType keyType, - const hidl_vec& optionalParameters, - getKeyRequest_cb _hidl_cb) override; + Return getKeyRequest(const hidl_vec& scope, + const hidl_vec& initData, + const hidl_string& mimeType, KeyType keyType, + const hidl_vec& optionalParameters, + getKeyRequest_cb _hidl_cb) override; - Return getKeyRequest_1_1( - const hidl_vec& scope, - const hidl_vec& initData, - const hidl_string& mimeType, - KeyType keyType, - const hidl_vec& optionalParameters, - getKeyRequest_1_1_cb _hidl_cb) override; + Return getKeyRequest_1_1(const hidl_vec& scope, + const hidl_vec& initData, + const hidl_string& mimeType, KeyType keyType, + const hidl_vec& optionalParameters, + getKeyRequest_1_1_cb _hidl_cb) override; - Return getKeyRequest_1_2( - const hidl_vec& scope, - const hidl_vec& initData, - const hidl_string& mimeType, - KeyType keyType, - const hidl_vec& optionalParameters, - getKeyRequest_1_2_cb _hidl_cb) override; + Return getKeyRequest_1_2(const hidl_vec& scope, + const hidl_vec& initData, + const hidl_string& mimeType, KeyType keyType, + const hidl_vec& optionalParameters, + getKeyRequest_1_2_cb _hidl_cb) override; - Return provideKeyResponse( - const hidl_vec& scope, - const hidl_vec& response, - provideKeyResponse_cb _hidl_cb) override; + Return provideKeyResponse(const hidl_vec& scope, + const hidl_vec& response, + provideKeyResponse_cb _hidl_cb) override; Return removeKeys(const hidl_vec& sessionId) override; - Return restoreKeys( - const hidl_vec& sessionId, - const hidl_vec& keySetId) override; + Return restoreKeys(const hidl_vec& sessionId, + const hidl_vec& keySetId) override; - Return queryKeyStatus( - const hidl_vec& sessionId, - queryKeyStatus_cb _hidl_cb) override; + Return queryKeyStatus(const hidl_vec& sessionId, + queryKeyStatus_cb _hidl_cb) override; - Return getProvisionRequest( - const hidl_string& certificateType, - const hidl_string& certificateAuthority, - getProvisionRequest_cb _hidl_cb) override; + Return getProvisionRequest(const hidl_string& certificateType, + const hidl_string& certificateAuthority, + getProvisionRequest_cb _hidl_cb) override; Return getProvisionRequest_1_2( const hidl_string& certificateType, @@ -111,9 +102,8 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, Return getSecureStops(getSecureStops_cb _hidl_cb) override; - Return getSecureStop( - const hidl_vec& secureStopId, - getSecureStop_cb _hidl_cb) override; + Return getSecureStop(const hidl_vec& secureStopId, + getSecureStop_cb _hidl_cb) override; Return releaseAllSecureStops() override; @@ -124,9 +114,11 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, Return getSecureStopIds(getSecureStopIds_cb _hidl_cb) override; - Return releaseSecureStops(const SecureStopRelease& ssRelease) override; + Return releaseSecureStops( + const SecureStopRelease& ssRelease) override; - Return removeSecureStop(const hidl_vec& secureStopId) override; + Return removeSecureStop( + const hidl_vec& secureStopId) override; Return removeAllSecureStops() override; @@ -136,101 +128,87 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, Return getNumberOfSessions(getNumberOfSessions_cb _hidl_cb) override; Return getSecurityLevel(const hidl_vec& sessionId, - getSecurityLevel_cb _hidl_cb) override; + getSecurityLevel_cb _hidl_cb) override; Return getOfflineLicenseKeySetIds( getOfflineLicenseKeySetIds_cb _hidl_cb) override; - Return removeOfflineLicense(const KeySetId &keySetId) override; + Return removeOfflineLicense(const KeySetId& keySetId) override; - Return getOfflineLicenseState(const KeySetId &keySetId, - getOfflineLicenseState_cb _hidl_cb) override; + Return getOfflineLicenseState( + const KeySetId& keySetId, getOfflineLicenseState_cb _hidl_cb) override; - Return getPropertyString( - const hidl_string& propertyName, - getPropertyString_cb _hidl_cb) override; + Return getPropertyString(const hidl_string& propertyName, + getPropertyString_cb _hidl_cb) override; - Return getPropertyByteArray( - const hidl_string& propertyName, - getPropertyByteArray_cb _hidl_cb) override; + Return getPropertyByteArray(const hidl_string& propertyName, + getPropertyByteArray_cb _hidl_cb) override; - Return setPropertyString( - const hidl_string& propertyName, - const hidl_string& value) override; + Return setPropertyString(const hidl_string& propertyName, + const hidl_string& value) override; - Return setPropertyByteArray( - const hidl_string& propertyName, - const hidl_vec& value) override; + Return setPropertyByteArray(const hidl_string& propertyName, + const hidl_vec& value) override; - Return setCipherAlgorithm( - const hidl_vec& sessionId, - const hidl_string& algorithm) override; + Return setCipherAlgorithm(const hidl_vec& sessionId, + const hidl_string& algorithm) override; - Return setMacAlgorithm( - const hidl_vec& sessionId, - const hidl_string& algorithm) override; + Return setMacAlgorithm(const hidl_vec& sessionId, + const hidl_string& algorithm) override; - Return encrypt( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& input, - const hidl_vec& iv, - encrypt_cb _hidl_cb) override; + Return encrypt(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& input, + const hidl_vec& iv, + encrypt_cb _hidl_cb) override; - Return decrypt( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& input, - const hidl_vec& iv, - decrypt_cb _hidl_cb) override; + Return decrypt(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& input, + const hidl_vec& iv, + decrypt_cb _hidl_cb) override; Return sign(const hidl_vec& sessionId, - const hidl_vec& keyId, const hidl_vec& message, - sign_cb _hidl_cb) override; + const hidl_vec& keyId, + const hidl_vec& message, + sign_cb _hidl_cb) override; - Return verify( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& message, - const hidl_vec& signature, - verify_cb _hidl_cb) override; + Return verify(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& message, + const hidl_vec& signature, + verify_cb _hidl_cb) override; - Return signRSA( - const hidl_vec& sessionId, - const hidl_string& algorithm, - const hidl_vec& message, - const hidl_vec& wrappedkey, - signRSA_cb _hidl_cb) override; + Return signRSA(const hidl_vec& sessionId, + const hidl_string& algorithm, + const hidl_vec& message, + const hidl_vec& wrappedkey, + signRSA_cb _hidl_cb) override; Return setListener(const sp& listener) override; - Return sendEvent( - EventType eventType, - const hidl_vec& sessionId, - const hidl_vec& data) override; + Return sendEvent(EventType eventType, + const hidl_vec& sessionId, + const hidl_vec& data) override; - Return sendExpirationUpdate( - const hidl_vec& sessionId, - int64_t expiryTimeInMS) override; + Return sendExpirationUpdate(const hidl_vec& sessionId, + int64_t expiryTimeInMS) override; - Return sendKeysChange( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, - bool hasNewUsableKey) override; + Return sendKeysChange(const hidl_vec& sessionId, + const hidl_vec& keyStatusList, + bool hasNewUsableKey) override; - Return sendKeysChange_1_2( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, - bool hasNewUsableKey) override; + Return sendKeysChange_1_2(const hidl_vec& sessionId, + const hidl_vec& keyStatusList, + bool hasNewUsableKey) override; Return sendSessionLostState( const hidl_vec& sessionId) override; - Return getLogMessages( - getLogMessages_cb _hidl_cb) override; + Return getLogMessages(getLogMessages_cb _hidl_cb) override; - Return requiresSecureDecoder(const hidl_string& mime, SecurityLevel level) - override; + Return requiresSecureDecoder(const hidl_string& mime, + SecurityLevel level) override; Return requiresSecureDecoderDefault(const hidl_string& mime) override; @@ -243,29 +221,22 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, virtual void OnSessionRenewalNeeded(const CdmSessionId& cdmSessionId); - template - void _sendKeysChange( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, - bool hasNewUsableKey); + template + void _sendKeysChange(const hidl_vec& sessionId, + const hidl_vec& keyStatusList, bool hasNewUsableKey); - template - void _OnSessionKeysChange( - const CdmSessionId&, - const CdmKeyStatusMap&, - bool hasNewUsableKey); + template + void _OnSessionKeysChange(const CdmSessionId&, const CdmKeyStatusMap&, + bool hasNewUsableKey); - virtual void OnSessionKeysChange( - const CdmSessionId& cdmSessionId, - const CdmKeyStatusMap& cdmKeysStatus, - bool hasNewUsableKey); + virtual void OnSessionKeysChange(const CdmSessionId& cdmSessionId, + const CdmKeyStatusMap& cdmKeysStatus, + bool hasNewUsableKey); - virtual void OnExpirationUpdate( - const CdmSessionId& cdmSessionId, - int64_t newExpiryTimeSeconds); + virtual void OnExpirationUpdate(const CdmSessionId& cdmSessionId, + int64_t newExpiryTimeSeconds); - virtual void OnSessionLostState( - const CdmSessionId& cdmSessionId); + virtual void OnSessionLostState(const CdmSessionId& cdmSessionId); private: WVDRM_DISALLOW_COPY_AND_ASSIGN_AND_NEW(WVDrmPlugin); @@ -277,14 +248,14 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, struct CryptoSession { public: CryptoSession() - : mOecSessionId(-1), - mCipherAlgorithm(kInvalidCryptoAlgorithm), - mMacAlgorithm(kInvalidCryptoAlgorithm) {} + : mOecSessionId(-1), + mCipherAlgorithm(kInvalidCryptoAlgorithm), + mMacAlgorithm(kInvalidCryptoAlgorithm) {} CryptoSession(OEMCrypto_SESSION sessionId) - : mOecSessionId(sessionId), - mCipherAlgorithm(kInvalidCryptoAlgorithm), - mMacAlgorithm(kInvalidCryptoAlgorithm) {} + : mOecSessionId(sessionId), + mCipherAlgorithm(kInvalidCryptoAlgorithm), + mMacAlgorithm(kInvalidCryptoAlgorithm) {} OEMCrypto_SESSION oecSessionId() const { return mOecSessionId; } @@ -309,22 +280,20 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, class WVClientPropertySet : public wvcdm::CdmClientPropertySet { public: WVClientPropertySet() - : mUsePrivacyMode(false), mShareKeys(false), mSessionSharingId(0), - mUseAtscMode(false) {} + : mUsePrivacyMode(false), + mShareKeys(false), + mSessionSharingId(0), + mUseAtscMode(false) {} virtual ~WVClientPropertySet() {} - virtual const std::string& security_level() const { - return mSecurityLevel; - } + virtual const std::string& security_level() const { return mSecurityLevel; } void set_security_level(const std::string& securityLevel) { mSecurityLevel = securityLevel; } - virtual bool use_privacy_mode() const { - return mUsePrivacyMode; - } + virtual bool use_privacy_mode() const { return mUsePrivacyMode; } void set_use_privacy_mode(bool usePrivacyMode) { mUsePrivacyMode = usePrivacyMode; @@ -345,42 +314,28 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, } virtual void set_device_provisioning_service_certificate( - const std::string& ) { + const std::string&) { // Ignore. Android does not support service certificates for provisioning // TODO(b/69562876): Android SHOULD support service cert for provisioning } - virtual bool is_session_sharing_enabled() const { - return mShareKeys; - } + virtual bool is_session_sharing_enabled() const { return mShareKeys; } void set_is_session_sharing_enabled(bool shareKeys) { mShareKeys = shareKeys; } - virtual uint32_t session_sharing_id() const { - return mSessionSharingId; - } + virtual uint32_t session_sharing_id() const { return mSessionSharingId; } - virtual void set_session_sharing_id(uint32_t id) { - mSessionSharingId = id; - } + virtual void set_session_sharing_id(uint32_t id) { mSessionSharingId = id; } - virtual const std::string& app_id() const { - return mAppId; - } + virtual const std::string& app_id() const { return mAppId; } - void set_app_id(const std::string& appId) { - mAppId = appId; - } + void set_app_id(const std::string& appId) { mAppId = appId; } - virtual bool use_atsc_mode() const { - return mUseAtscMode; - } + virtual bool use_atsc_mode() const { return mUseAtscMode; } - void set_use_atsc_mode(bool useAtscMode) { - mUseAtscMode = useAtscMode; - } + void set_use_atsc_mode(bool useAtscMode) { mUseAtscMode = useAtscMode; } private: DISALLOW_EVIL_CONSTRUCTORS(WVClientPropertySet); @@ -444,7 +399,7 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, // outside this class should use getDeviceUniqueId() to get the // application-safe device-unique ID. Status getOemcryptoDeviceId(std::string* id); - Status getOemcryptoDeviceId(wvcdm::SecurityLevel securityLevel, + Status getOemcryptoDeviceId(wvcdm::RequestedSecurityLevel securityLevel, std::string* id); // The unique identifier is meant to ensure that two clients with the @@ -465,9 +420,7 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, private: WVDRM_DISALLOW_COPY_AND_ASSIGN(Terminator); - Terminator() { - signal(SIGTERM, Terminate); - } + Terminator() { signal(SIGTERM, Terminate); } static Terminator& instance() { static Terminator instance; @@ -510,37 +463,36 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, std::string mAppPackageName; Status queryProperty(const std::string& property, - std::string& stringValue) const; + std::string& stringValue) const; - Status queryProperty(wvcdm::SecurityLevel securityLevel, - const std::string& property, - std::string& stringValue) const; + Status queryProperty(wvcdm::RequestedSecurityLevel securityLevel, + const std::string& property, + std::string& stringValue) const; Status queryProperty(const std::string& property, - std::vector& vector_value) const; + std::vector& vector_value) const; bool isProvisioned(wvcdm::CdmSecurityLevel securityLevel, - const std::string& origin, - const std::string& spoid, + const std::string& origin, const std::string& spoid, bool atsc_mode_enabled) const; Status mapAndNotifyOfCdmResponseType(const std::vector& sessionId, - CdmResponseType res); + CdmResponseType res); - Status_V1_2 mapAndNotifyOfCdmResponseType_1_2(const std::vector& sessionId, - CdmResponseType res); + Status_V1_2 mapAndNotifyOfCdmResponseType_1_2( + const std::vector& sessionId, CdmResponseType res); void notifyOfCdmResponseType(const std::vector& sessionId, - CdmResponseType res); + CdmResponseType res); Status mapAndNotifyOfOEMCryptoResult(const std::vector& sessionId, - OEMCryptoResult res); + OEMCryptoResult res); Status mapOEMCryptoResult(OEMCryptoResult res); SecurityLevel mapSecurityLevel(const std::string& level); - wvcdm::SecurityLevel getRequestedSecurityLevel() const; + wvcdm::RequestedSecurityLevel getRequestedSecurityLevel() const; Status openSessionCommon(std::vector& sessionId); @@ -555,4 +507,4 @@ struct WVDrmPlugin : public ::drm::V1_4::IDrmPlugin, IDrmPluginListener, } // namespace hardware } // namespace wvdrm -#endif // WV_DRM_PLUGIN_H_ +#endif // WV_DRM_PLUGIN_H_ diff --git a/libwvdrmengine/mediadrm/src_hidl/WVDrmPlugin.cpp b/libwvdrmengine/mediadrm/src_hidl/WVDrmPlugin.cpp index c42efd1a..5596d59e 100644 --- a/libwvdrmengine/mediadrm/src_hidl/WVDrmPlugin.cpp +++ b/libwvdrmengine/mediadrm/src_hidl/WVDrmPlugin.cpp @@ -6,17 +6,17 @@ //#define LOG_NDEBUG 0 #define LOG_TAG "WVCdm" +#include "WVDrmPlugin.h" + #include +#include #include #include #include -#include #include #include -#include "WVDrmPlugin.h" - #include "HidlTypes.h" #include "TypeConvert.h" #include "android-base/macros.h" @@ -38,7 +38,7 @@ static const char* const kSpecialUnprovisionResponse = "unprovision"; static const std::string kKeyAppPackageName = "application_name"; static const std::string kKeyOrigin = "origin"; -} // namespace +} // namespace namespace wvdrm { namespace hardware { @@ -48,15 +48,14 @@ namespace widevine { using android::hardware::drm::V1_2::widevine::toHidlVec; using android::hardware::drm::V1_2::widevine::toVector; -using wvcdm::kDefaultCdmIdentifier; using wvcdm::CdmAppParameterMap; using wvcdm::CdmCertificateType; using wvcdm::CdmInitData; -using wvcdm::CdmKeyStatus; using wvcdm::CdmKeyRequest; using wvcdm::CdmKeyRequestType; using wvcdm::CdmKeyResponse; using wvcdm::CdmKeySetId; +using wvcdm::CdmKeyStatus; using wvcdm::CdmLicenseType; using wvcdm::CdmProvisioningRequest; using wvcdm::CdmProvisioningResponse; @@ -65,6 +64,7 @@ using wvcdm::CdmSecureStopId; using wvcdm::CdmSecurityLevel; using wvcdm::CdmUsageInfo; using wvcdm::CdmUsageInfoReleaseMessage; +using wvcdm::kDefaultCdmIdentifier; using wvcdm::KeyId; namespace { @@ -74,8 +74,7 @@ std::vector StrToVector(const std::string& str) { return vec; } -KeyRequestType ConvertFromCdmKeyRequestType( - CdmKeyRequestType keyRequestType) { +KeyRequestType ConvertFromCdmKeyRequestType(CdmKeyRequestType keyRequestType) { switch (keyRequestType) { case wvcdm::kKeyRequestTypeInitial: return KeyRequestType::INITIAL; @@ -123,10 +122,10 @@ Status toStatus_1_0(Status_V1_2 status) { } } -template +template KST ConvertFromCdmKeyStatus(CdmKeyStatus keyStatus); -template<> +template <> KeyStatusType ConvertFromCdmKeyStatus(CdmKeyStatus keyStatus) { switch (keyStatus) { case wvcdm::kKeyStatusUsable: @@ -144,13 +143,15 @@ KeyStatusType ConvertFromCdmKeyStatus(CdmKeyStatus keyStatus) { } } -template<> -KeyStatusType_V1_2 ConvertFromCdmKeyStatus(CdmKeyStatus keyStatus) { +template <> +KeyStatusType_V1_2 ConvertFromCdmKeyStatus( + CdmKeyStatus keyStatus) { switch (keyStatus) { case wvcdm::kKeyStatusUsableInFuture: return KeyStatusType_V1_2::USABLEINFUTURE; default: - return static_cast(ConvertFromCdmKeyStatus(keyStatus)); + return static_cast( + ConvertFromCdmKeyStatus(keyStatus)); } } @@ -174,30 +175,29 @@ HdcpLevel mapHdcpLevel(const std::string& level) { } HdcpLevel_V1_2 mapHdcpLevel_1_2(const std::string level) { - if (level == wvcdm::QUERY_VALUE_HDCP_V2_3) { - return HdcpLevel_V1_2::HDCP_V2_3; - } - return static_cast(mapHdcpLevel(level)); + if (level == wvcdm::QUERY_VALUE_HDCP_V2_3) { + return HdcpLevel_V1_2::HDCP_V2_3; + } + return static_cast(mapHdcpLevel(level)); } HdcpLevel toHdcpLevel_1_1(HdcpLevel_V1_2 level) { - if (level == HdcpLevel_V1_2::HDCP_V2_3) { - return HdcpLevel::HDCP_NONE; - } - return static_cast(level); + if (level == HdcpLevel_V1_2::HDCP_V2_3) { + return HdcpLevel::HDCP_NONE; + } + return static_cast(level); } } // namespace WVDrmPlugin::WVDrmPlugin(const sp& cdm, const std::string& appPackageName, - WVGenericCryptoInterface* crypto, - bool useSpoid) - : mCdmIdentifierBuilder(useSpoid, *this, appPackageName), - mCDM(cdm), - mCrypto(crypto), - mCryptoSessions(), - mAppPackageName(appPackageName) { + WVGenericCryptoInterface* crypto, bool useSpoid) + : mCdmIdentifierBuilder(useSpoid, *this, appPackageName), + mCDM(cdm), + mCrypto(crypto), + mCryptoSessions(), + mAppPackageName(appPackageName) { Terminator::Register(this); } @@ -210,8 +210,7 @@ WVDrmPlugin::~WVDrmPlugin() { void WVDrmPlugin::Close() { typedef map::iterator mapIterator; for (mapIterator iter = mCryptoSessions.begin(); - iter != mCryptoSessions.end(); - ++iter) { + iter != mCryptoSessions.end(); ++iter) { CdmResponseType res = mCDM->CloseSession(iter->first); if (!isCdmResponseTypeSuccess(res)) { ALOGE("Failed to close session while destroying WVDrmPlugin"); @@ -242,9 +241,8 @@ Status WVDrmPlugin::openSessionCommon(std::vector& sessionId) { } CdmSessionId cdmSessionId; - CdmResponseType res = - mCDM->OpenSession("com.widevine", &mPropertySet, identifier, this, - &cdmSessionId); + CdmResponseType res = mCDM->OpenSession("com.widevine", &mPropertySet, + identifier, this, &cdmSessionId); if (!isCdmResponseTypeSuccess(res)) { status = mapAndNotifyOfCdmResponseType(sessionId, res); @@ -305,14 +303,13 @@ SecurityLevel WVDrmPlugin::mapSecurityLevel(const std::string& level) { hSecurityLevel = SecurityLevel::HW_SECURE_CRYPTO; } else if (wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3 == level) { hSecurityLevel = SecurityLevel::SW_SECURE_CRYPTO; - } // else QUERY_VALUE_SECURITY_LEVEL_UNKNOWN returns Security::UNKNOWN + } // else QUERY_VALUE_SECURITY_LEVEL_UNKNOWN returns Security::UNKNOWN return hSecurityLevel; } -Return WVDrmPlugin::openSession_1_1( - SecurityLevel requestedLevel, - openSession_1_1_cb _hidl_cb) { +Return WVDrmPlugin::openSession_1_1(SecurityLevel requestedLevel, + openSession_1_1_cb _hidl_cb) { std::vector sessionId; sessionId.clear(); @@ -322,8 +319,9 @@ Return WVDrmPlugin::openSession_1_1( } std::string native_security_level; - Status status = queryProperty(wvcdm::kLevelDefault, - wvcdm::QUERY_KEY_SECURITY_LEVEL, native_security_level); + Status status = + queryProperty(wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, + native_security_level); if (Status::OK != status) { _hidl_cb(status, toHidlVec(sessionId)); return Void(); @@ -336,8 +334,9 @@ Return WVDrmPlugin::openSession_1_1( } std::string wvcdm_security_level = - (SecurityLevel::SW_SECURE_CRYPTO == requestedLevel) ? - wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3 : wvcdm::QUERY_VALUE_SECURITY_LEVEL_DEFAULT; + (SecurityLevel::SW_SECURE_CRYPTO == requestedLevel) + ? wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3 + : wvcdm::QUERY_VALUE_SECURITY_LEVEL_DEFAULT; setPropertyString("securityLevel", hidl_string(wvcdm_security_level)); @@ -346,14 +345,15 @@ Return WVDrmPlugin::openSession_1_1( if (Status::OK == status) { SecurityLevel currentSecurityLevel = SecurityLevel::UNKNOWN; Return hResult = getSecurityLevel( - hSessionId, [&](Status gslStatus, SecurityLevel hSecurityLevel) { - currentSecurityLevel = hSecurityLevel; - if (Status::OK != gslStatus || requestedLevel != hSecurityLevel) { - ALOGE("Failed to open session with the requested security level=%d", requestedLevel); - closeSession(hSessionId); - sessionId.clear(); - } - }); + hSessionId, [&](Status gslStatus, SecurityLevel hSecurityLevel) { + currentSecurityLevel = hSecurityLevel; + if (Status::OK != gslStatus || requestedLevel != hSecurityLevel) { + ALOGE("Failed to open session with the requested security level=%d", + requestedLevel); + closeSession(hSessionId); + sessionId.clear(); + } + }); if (!hResult.isOk() || (requestedLevel != currentSecurityLevel)) { status = Status::ERROR_DRM_INVALID_STATE; } @@ -377,12 +377,9 @@ Return WVDrmPlugin::closeSession(const hidl_vec& sessionId) { } Return WVDrmPlugin::getKeyRequest( - const hidl_vec& scope, - const hidl_vec& initData, - const hidl_string& mimeType, - KeyType keyType, - const hidl_vec& optionalParameters, - getKeyRequest_cb _hidl_cb) { + const hidl_vec& scope, const hidl_vec& initData, + const hidl_string& mimeType, KeyType keyType, + const hidl_vec& optionalParameters, getKeyRequest_cb _hidl_cb) { hidl_string defaultUrl; hidl_vec request; KeyRequestType requestType = KeyRequestType::UNKNOWN; @@ -390,14 +387,14 @@ Return WVDrmPlugin::getKeyRequest( defaultUrl.clear(); Return hResult = getKeyRequest_1_1( - scope, initData, mimeType, keyType, optionalParameters, - [&](Status statusCode, const hidl_vec& hRequest, - KeyRequestType_V1_1 hKeyRequestType, const hidl_string& hDefaultUrl) { - defaultUrl = hDefaultUrl; - request = hRequest; - requestType = toKeyRequestType_V1_0(hKeyRequestType); - status = statusCode; - }); + scope, initData, mimeType, keyType, optionalParameters, + [&](Status statusCode, const hidl_vec& hRequest, + KeyRequestType_V1_1 hKeyRequestType, const hidl_string& hDefaultUrl) { + defaultUrl = hDefaultUrl; + request = hRequest; + requestType = toKeyRequestType_V1_0(hKeyRequestType); + status = statusCode; + }); if (!hResult.isOk()) { status = Status::ERROR_DRM_INVALID_STATE; } @@ -406,10 +403,8 @@ Return WVDrmPlugin::getKeyRequest( } Return WVDrmPlugin::getKeyRequest_1_1( - const hidl_vec& scope, - const hidl_vec& initData, - const hidl_string& mimeType, - KeyType keyType, + const hidl_vec& scope, const hidl_vec& initData, + const hidl_string& mimeType, KeyType keyType, const hidl_vec& optionalParameters, getKeyRequest_1_1_cb _hidl_cb) { hidl_string defaultUrl; @@ -420,13 +415,13 @@ Return WVDrmPlugin::getKeyRequest_1_1( defaultUrl.clear(); Return hResult = getKeyRequest_1_2( scope, initData, mimeType, keyType, optionalParameters, - [&](Status_V1_2 statusCode, const hidl_vec& hRequest, - KeyRequestType_V1_1 hKeyRequestType, const hidl_string& hDefaultUrl) { - defaultUrl = hDefaultUrl; - request = hRequest; - requestType = hKeyRequestType; - status = toStatus_1_0(statusCode); - }); + [&](Status_V1_2 statusCode, const hidl_vec& hRequest, + KeyRequestType_V1_1 hKeyRequestType, const hidl_string& hDefaultUrl) { + defaultUrl = hDefaultUrl; + request = hRequest; + requestType = hKeyRequestType; + status = toStatus_1_0(statusCode); + }); if (!hResult.isOk()) { status = Status::ERROR_DRM_INVALID_STATE; } @@ -435,16 +430,13 @@ Return WVDrmPlugin::getKeyRequest_1_1( } Return WVDrmPlugin::getKeyRequest_1_2( - const hidl_vec& scope, - const hidl_vec& initData, - const hidl_string& mimeType, - KeyType keyType, + const hidl_vec& scope, const hidl_vec& initData, + const hidl_string& mimeType, KeyType keyType, const hidl_vec& optionalParameters, getKeyRequest_1_2_cb _hidl_cb) { - if (!scope.size()) { _hidl_cb(Status_V1_2::BAD_VALUE, hidl_vec(), - KeyRequestType_V1_1::UNKNOWN, ""); + KeyRequestType_V1_1::UNKNOWN, ""); return Void(); } KeyRequestType_V1_1 requestType = KeyRequestType_V1_1::UNKNOWN; @@ -457,8 +449,7 @@ Return WVDrmPlugin::getKeyRequest_1_2( status = static_cast( mCdmIdentifierBuilder.getCdmIdentifier(&identifier)); if (status != Status_V1_2::OK) { - _hidl_cb(status, toHidlVec(request), requestType, - defaultUrl.c_str()); + _hidl_cb(status, toHidlVec(request), requestType, defaultUrl.c_str()); return Void(); } @@ -475,8 +466,8 @@ Return WVDrmPlugin::getKeyRequest_1_2( cdmLicenseType = wvcdm::kLicenseTypeRelease; cdmKeySetId.assign(scopeId.begin(), scopeId.end()); } else { - _hidl_cb(Status_V1_2::BAD_VALUE, toHidlVec(request), KeyRequestType_V1_1::UNKNOWN, - defaultUrl.c_str()); + _hidl_cb(Status_V1_2::BAD_VALUE, toHidlVec(request), + KeyRequestType_V1_1::UNKNOWN, defaultUrl.c_str()); return Void(); } @@ -494,20 +485,19 @@ Return WVDrmPlugin::getKeyRequest_1_2( // This data was passed in the old format, pre-unwrapped. We need to wrap // the init data in a new PSSH header. static const uint8_t psshPrefix[] = { - 0, 0, 0, 0, // Total size - 'p', 's', 's', 'h', // "PSSH" - 0, 0, 0, 0, // Flags - must be zero - 0xED, 0xEF, 0x8B, 0xA9, 0x79, 0xD6, 0x4A, 0xCE, // Widevine UUID - 0xA3, 0xC8, 0x27, 0xDC, 0xD5, 0x1D, 0x21, 0xED, - 0, 0, 0, 0 // Size of initData + 0, 0, 0, 0, // Total size + 'p', 's', 's', 'h', // "PSSH" + 0, 0, 0, 0, // Flags - must be zero + 0xED, 0xEF, 0x8B, 0xA9, 0x79, 0xD6, 0x4A, 0xCE, // Widevine UUID + 0xA3, 0xC8, 0x27, 0xDC, 0xD5, 0x1D, 0x21, 0xED, + 0, 0, 0, 0 // Size of initData }; processedInitData.assign(reinterpret_cast(psshPrefix), sizeof(psshPrefix) / sizeof(uint8_t)); processedInitData.append(reinterpret_cast(initData.data()), initData.size()); const size_t kPsshBoxSizeLocation = 0; - const size_t kInitDataSizeLocation = - sizeof(psshPrefix) - sizeof(uint32_t); + const size_t kInitDataSizeLocation = sizeof(psshPrefix) - sizeof(uint32_t); uint32_t psshBoxSize = htonl(processedInitData.size()); uint32_t initDataSize = htonl(initData.size()); memcpy(&processedInitData[kPsshBoxSizeLocation], &psshBoxSize, @@ -558,16 +548,13 @@ Return WVDrmPlugin::getKeyRequest_1_2( // For all other requests, we have a session ID. status = mapAndNotifyOfCdmResponseType_1_2(scopeId, res); } - _hidl_cb(status, toHidlVec(request), requestType, - defaultUrl.c_str()); + _hidl_cb(status, toHidlVec(request), requestType, defaultUrl.c_str()); return Void(); } -Return WVDrmPlugin::provideKeyResponse( - const hidl_vec& scope, - const hidl_vec& response, - provideKeyResponse_cb _hidl_cb) { - +Return WVDrmPlugin::provideKeyResponse(const hidl_vec& scope, + const hidl_vec& response, + provideKeyResponse_cb _hidl_cb) { if (scope.size() == 0 || response.size() == 0) { _hidl_cb(Status::BAD_VALUE, hidl_vec()); return Void(); @@ -620,7 +607,6 @@ Return WVDrmPlugin::provideKeyResponse( } Return WVDrmPlugin::removeKeys(const hidl_vec& sessionId) { - if (!sessionId.size()) { return Status::BAD_VALUE; } @@ -634,7 +620,6 @@ Return WVDrmPlugin::removeKeys(const hidl_vec& sessionId) { Return WVDrmPlugin::restoreKeys(const hidl_vec& sessionId, const hidl_vec& keySetId) { - if (!sessionId.size() || !keySetId.size()) { return Status::BAD_VALUE; } @@ -648,9 +633,8 @@ Return WVDrmPlugin::restoreKeys(const hidl_vec& sessionId, return mapAndNotifyOfCdmResponseType(sId, res); } - Return WVDrmPlugin::queryKeyStatus(const hidl_vec& sessionId, - queryKeyStatus_cb _hidl_cb) { - +Return WVDrmPlugin::queryKeyStatus(const hidl_vec& sessionId, + queryKeyStatus_cb _hidl_cb) { if (sessionId.size() == 0) { _hidl_cb(Status::BAD_VALUE, hidl_vec()); return Void(); @@ -667,8 +651,7 @@ Return WVDrmPlugin::restoreKeys(const hidl_vec& sessionId, KeyValue keyValuePair; for (CdmQueryMap::const_iterator iter = cdmLicenseInfo.begin(); - iter != cdmLicenseInfo.end(); - ++iter) { + iter != cdmLicenseInfo.end(); ++iter) { const std::string& cdmKey = iter->first; const std::string& cdmValue = iter->second; keyValuePair.key = std::string(cdmKey.data(), cdmKey.size()); @@ -682,21 +665,20 @@ Return WVDrmPlugin::restoreKeys(const hidl_vec& sessionId, } Return WVDrmPlugin::getProvisionRequest( - const hidl_string& certificateType, - const hidl_string& certificateAuthority, - getProvisionRequest_cb _hidl_cb) { + const hidl_string& certificateType, const hidl_string& certificateAuthority, + getProvisionRequest_cb _hidl_cb) { Status status = Status::OK; std::string defaultUrl; std::vector request; Return hResult = getProvisionRequest_1_2( certificateType, certificateAuthority, - [&](Status_V1_2 statusCode, const hidl_vec& hRequest, - const hidl_string& hDefaultUrl) { - request = hRequest; - status = toStatus_1_0(statusCode); - defaultUrl = hDefaultUrl; - }); + [&](Status_V1_2 statusCode, const hidl_vec& hRequest, + const hidl_string& hDefaultUrl) { + request = hRequest; + status = toStatus_1_0(statusCode); + defaultUrl = hDefaultUrl; + }); if (!hResult.isOk()) { status = Status::ERROR_DRM_INVALID_STATE; } @@ -706,21 +688,22 @@ Return WVDrmPlugin::getProvisionRequest( } Return WVDrmPlugin::getProvisionRequest_1_2( - const hidl_string& certificateType, - const hidl_string& certificateAuthority, - getProvisionRequest_1_2_cb _hidl_cb) { + const hidl_string& certificateType, const hidl_string& certificateAuthority, + getProvisionRequest_1_2_cb _hidl_cb) { Status_V1_2 status = Status_V1_2::OK; std::string defaultUrl; std::vector request; if (mPropertySet.use_atsc_mode()) { - _hidl_cb(mapCdmResponseType(wvcdm::PROVISIONING_NOT_ALLOWED_FOR_ATSC), + _hidl_cb(mapCdmResponseType( + wvcdm::PROVISIONING_NOT_ALLOWED_FOR_ATSC), toHidlVec(request), hidl_string(defaultUrl)); return Void(); } CdmIdentifier identifier; - status = static_cast(mCdmIdentifierBuilder.getCdmIdentifier(&identifier)); + status = static_cast( + mCdmIdentifierBuilder.getCdmIdentifier(&identifier)); if (status != Status_V1_2::OK) { _hidl_cb(status, toHidlVec(request), hidl_string(defaultUrl)); return Void(); @@ -752,9 +735,7 @@ Return WVDrmPlugin::getProvisionRequest_1_2( } Return WVDrmPlugin::provideProvisionResponse( - const hidl_vec& response, - provideProvisionResponse_cb _hidl_cb) { - + const hidl_vec& response, provideProvisionResponse_cb _hidl_cb) { if (!response.size()) { _hidl_cb(Status::BAD_VALUE, hidl_vec(), hidl_vec()); return Void(); @@ -772,13 +753,12 @@ Return WVDrmPlugin::provideProvisionResponse( CdmProvisioningResponse cdmResponse(resp.begin(), resp.end()); if (cdmResponse == kSpecialUnprovisionResponse) { if (identifier.IsEquivalentToDefault()) { - ALOGW("Returns UNKNOWN error for legacy status kErrorNoOriginSpecified"); + ALOGW("Returns UNKNOWN error for legacy status kErrorNoOriginSpecified"); _hidl_cb(Status::ERROR_DRM_UNKNOWN, toHidlVec(certificate), toHidlVec(wrappedKey)); return Void(); } - _hidl_cb(unprovision(identifier), - toHidlVec(certificate), + _hidl_cb(unprovision(identifier), toHidlVec(certificate), toHidlVec(wrappedKey)); return Void(); } else { @@ -802,10 +782,8 @@ Status WVDrmPlugin::unprovisionDevice() { return unprovision(kDefaultCdmIdentifier); } -Return WVDrmPlugin::getSecureStop( - const hidl_vec& secureStopId, - getSecureStop_cb _hidl_cb) { - +Return WVDrmPlugin::getSecureStop(const hidl_vec& secureStopId, + getSecureStop_cb _hidl_cb) { if (!secureStopId.size()) { _hidl_cb(Status::BAD_VALUE, SecureStop()); return Void(); @@ -824,13 +802,12 @@ Return WVDrmPlugin::getSecureStop( CdmUsageInfo cdmUsageInfo; CdmSecureStopId cdmSsId(id.begin(), id.end()); - CdmResponseType res = mCDM->GetUsageInfo( - mPropertySet.app_id(), cdmSsId, identifier, &cdmUsageInfo); + CdmResponseType res = mCDM->GetUsageInfo(mPropertySet.app_id(), cdmSsId, + identifier, &cdmUsageInfo); if (isCdmResponseTypeSuccess(res)) { for (CdmUsageInfo::const_iterator iter = cdmUsageInfo.begin(); - iter != cdmUsageInfo.end(); - ++iter) { + iter != cdmUsageInfo.end(); ++iter) { const std::string& cdmStop = *iter; cdmStopVec = StrToVector(cdmStop); } @@ -842,8 +819,7 @@ Return WVDrmPlugin::getSecureStop( } Return WVDrmPlugin::getSecureStops(getSecureStops_cb _hidl_cb) { - - std::list > secureStops; + std::list> secureStops; std::vector secureStopsVec; CdmIdentifier identifier; @@ -860,14 +836,13 @@ Return WVDrmPlugin::getSecureStops(getSecureStops_cb _hidl_cb) { if (isCdmResponseTypeSuccess(res)) { secureStops.clear(); for (CdmUsageInfo::const_iterator iter = cdmUsageInfo.begin(); - iter != cdmUsageInfo.end(); - ++iter) { + iter != cdmUsageInfo.end(); ++iter) { const std::string& cdmStop = *iter; secureStops.push_back(StrToVector(cdmStop)); } } - std::list >::iterator iter = secureStops.begin(); + std::list>::iterator iter = secureStops.begin(); while (iter != secureStops.end()) { SecureStop secureStop; secureStop.opaqueData = toHidlVec(*iter++); @@ -884,7 +859,6 @@ Return WVDrmPlugin::releaseAllSecureStops() { Return WVDrmPlugin::releaseSecureStop( const hidl_vec& secureStopId) { - if (!secureStopId.size()) { return Status::BAD_VALUE; } @@ -925,7 +899,6 @@ Return WVDrmPlugin::getMetrics(getMetrics_cb _hidl_cb) { } Return WVDrmPlugin::getSecureStopIds(getSecureStopIds_cb _hidl_cb) { - std::vector secureStopIds; CdmIdentifier identifier; @@ -950,8 +923,8 @@ Return WVDrmPlugin::getSecureStopIds(getSecureStopIds_cb _hidl_cb) { return Void(); } -Return WVDrmPlugin::releaseSecureStops(const SecureStopRelease& ssRelease) { - +Return WVDrmPlugin::releaseSecureStops( + const SecureStopRelease& ssRelease) { if (ssRelease.opaqueData.size() == 0) { return Status::BAD_VALUE; } @@ -968,7 +941,8 @@ Return WVDrmPlugin::releaseSecureStops(const SecureStopRelease& ssReleas return mapCdmResponseType(res); } -Return WVDrmPlugin::removeSecureStop(const hidl_vec& secureStopId) { +Return WVDrmPlugin::removeSecureStop( + const hidl_vec& secureStopId) { if (!secureStopId.size()) { return Status::BAD_VALUE; } @@ -981,7 +955,8 @@ Return WVDrmPlugin::removeSecureStop(const hidl_vec& secureStop const std::vector idVec = toVector(secureStopId); CdmSecureStopId id(idVec.begin(), idVec.end()); - CdmResponseType res = mCDM->RemoveUsageInfo(mPropertySet.app_id(), identifier, id); + CdmResponseType res = + mCDM->RemoveUsageInfo(mPropertySet.app_id(), identifier, id); return mapCdmResponseType(res); } @@ -992,23 +967,23 @@ Return WVDrmPlugin::removeAllSecureStops() { return status; } - CdmResponseType res = mCDM->RemoveAllUsageInfo(mPropertySet.app_id(), - identifier); + CdmResponseType res = + mCDM->RemoveAllUsageInfo(mPropertySet.app_id(), identifier); return mapCdmResponseType(res); } Return WVDrmPlugin::getHdcpLevels(getHdcpLevels_cb _hidl_cb) { - HdcpLevel connectedLevel = HdcpLevel::HDCP_NONE; - HdcpLevel maxLevel = HdcpLevel::HDCP_NO_OUTPUT; + HdcpLevel connectedLevel = HdcpLevel::HDCP_NONE; + HdcpLevel maxLevel = HdcpLevel::HDCP_NO_OUTPUT; - Return hResult = getHdcpLevels_1_2( - [&](Status_V1_2 status, const HdcpLevel_V1_2& hConnected, - const HdcpLevel_V1_2& hMax) { - if (status == Status_V1_2::OK) { - connectedLevel = toHdcpLevel_1_1(hConnected); - maxLevel = toHdcpLevel_1_1(hMax); - } - }); + Return hResult = getHdcpLevels_1_2([&](Status_V1_2 status, + const HdcpLevel_V1_2& hConnected, + const HdcpLevel_V1_2& hMax) { + if (status == Status_V1_2::OK) { + connectedLevel = toHdcpLevel_1_1(hConnected); + maxLevel = toHdcpLevel_1_1(hMax); + } + }); _hidl_cb(Status::OK, connectedLevel, maxLevel); return Void(); @@ -1046,7 +1021,8 @@ Return WVDrmPlugin::getNumberOfSessions(getNumberOfSessions_cb _hidl_cb) { uint32_t maxSessions = 1; std::string value; - Status status = queryProperty(wvcdm::QUERY_KEY_NUMBER_OF_OPEN_SESSIONS, value); + Status status = + queryProperty(wvcdm::QUERY_KEY_NUMBER_OF_OPEN_SESSIONS, value); if (status == Status::OK) { currentSessions = std::strtoul(value.c_str(), nullptr, 10); } else { @@ -1059,7 +1035,9 @@ Return WVDrmPlugin::getNumberOfSessions(getNumberOfSessions_cb _hidl_cb) { if (status == Status::OK) { maxSessions = std::strtoul(value.c_str(), nullptr, 10); } else { - ALOGE("Failed to query maximum number of sessions that the device can support."); + ALOGE( + "Failed to query maximum number of sessions that the device can " + "support."); _hidl_cb(Status::ERROR_DRM_INVALID_STATE, currentSessions, maxSessions); return Void(); } @@ -1068,9 +1046,8 @@ Return WVDrmPlugin::getNumberOfSessions(getNumberOfSessions_cb _hidl_cb) { return Void(); } -Return WVDrmPlugin::getSecurityLevel( - const hidl_vec& sessionId, - getSecurityLevel_cb _hidl_cb) { +Return WVDrmPlugin::getSecurityLevel(const hidl_vec& sessionId, + getSecurityLevel_cb _hidl_cb) { if (sessionId.size() == 0) { _hidl_cb(Status::BAD_VALUE, SecurityLevel::UNKNOWN); return Void(); @@ -1080,8 +1057,8 @@ Return WVDrmPlugin::getSecurityLevel( CdmQueryMap info; SecurityLevel hSecurityLevel = SecurityLevel::UNKNOWN; - CdmResponseType status = mCDM->QuerySessionStatus( - std::string(sid.begin(), sid.end()), &info); + CdmResponseType status = + mCDM->QuerySessionStatus(std::string(sid.begin(), sid.end()), &info); if (wvcdm::NO_ERROR == status) { std::string level = info[wvcdm::QUERY_KEY_SECURITY_LEVEL]; hSecurityLevel = mapSecurityLevel(level); @@ -1095,7 +1072,7 @@ Return WVDrmPlugin::getSecurityLevel( Return WVDrmPlugin::getOfflineLicenseKeySetIds( getOfflineLicenseKeySetIds_cb _hidl_cb) { - std::vector > keySetIds; + std::vector> keySetIds; std::vector keySetIdsVec; CdmIdentifier identifier; @@ -1105,8 +1082,8 @@ Return WVDrmPlugin::getOfflineLicenseKeySetIds( return Void(); } - std::vector levels = { - wvcdm::kSecurityLevelL1, wvcdm::kSecurityLevelL3 }; + std::vector levels = {wvcdm::kSecurityLevelL1, + wvcdm::kSecurityLevelL3}; CdmResponseType res = wvcdm::UNKNOWN_ERROR; @@ -1128,9 +1105,9 @@ Return WVDrmPlugin::getOfflineLicenseKeySetIds( return Void(); } -Return WVDrmPlugin::getOfflineLicenseState(const KeySetId &keySetId, - getOfflineLicenseState_cb _hidl_cb) { - OfflineLicenseState licenseState = OfflineLicenseState::UNKNOWN; +Return WVDrmPlugin::getOfflineLicenseState( + const KeySetId& keySetId, getOfflineLicenseState_cb _hidl_cb) { + OfflineLicenseState licenseState = OfflineLicenseState::UNKNOWN; if (!keySetId.size()) { _hidl_cb(Status::BAD_VALUE, licenseState); @@ -1148,25 +1125,19 @@ Return WVDrmPlugin::getOfflineLicenseState(const KeySetId &keySetId, CdmKeySetId keySetIdStr(keySetId.begin(), keySetId.end()); wvcdm::CdmOfflineLicenseState state = wvcdm::kLicenseStateUnknown; - res = mCDM->GetOfflineLicenseState( - keySetIdStr, - wvcdm::kSecurityLevelL1, - identifier, - &state); + res = mCDM->GetOfflineLicenseState(keySetIdStr, wvcdm::kSecurityLevelL1, + identifier, &state); if (!isCdmResponseTypeSuccess(res)) { // try L3 - res = mCDM->GetOfflineLicenseState( - keySetIdStr, - wvcdm::kSecurityLevelL3, - identifier, - &state); + res = mCDM->GetOfflineLicenseState(keySetIdStr, wvcdm::kSecurityLevelL3, + identifier, &state); if (!isCdmResponseTypeSuccess(res)) { _hidl_cb(Status::BAD_VALUE, licenseState); return Void(); } } - switch(state) { + switch (state) { case wvcdm::kLicenseStateActive: licenseState = OfflineLicenseState::USABLE; break; @@ -1183,7 +1154,7 @@ Return WVDrmPlugin::getOfflineLicenseState(const KeySetId &keySetId, return Void(); } -Return WVDrmPlugin::removeOfflineLicense(const KeySetId &keySetId) { +Return WVDrmPlugin::removeOfflineLicense(const KeySetId& keySetId) { if (!keySetId.size()) { return Status::BAD_VALUE; } @@ -1196,14 +1167,12 @@ Return WVDrmPlugin::removeOfflineLicense(const KeySetId &keySetId) { CdmResponseType res = wvcdm::UNKNOWN_ERROR; - res = mCDM->RemoveOfflineLicense( - std::string(keySetId.begin(), keySetId.end()), - wvcdm::kSecurityLevelL1, - identifier); + res = + mCDM->RemoveOfflineLicense(std::string(keySetId.begin(), keySetId.end()), + wvcdm::kSecurityLevelL1, identifier); if (!isCdmResponseTypeSuccess(res)) { CdmResponseType res = mCDM->RemoveOfflineLicense( - std::string(keySetId.begin(), keySetId.end()), - wvcdm::kSecurityLevelL3, + std::string(keySetId.begin(), keySetId.end()), wvcdm::kSecurityLevelL3, identifier); status = mapCdmResponseType(res); } @@ -1300,9 +1269,7 @@ Return WVDrmPlugin::getPropertyString(const hidl_string& propertyName, } Return WVDrmPlugin::getPropertyByteArray( - const hidl_string& propertyName, - getPropertyByteArray_cb _hidl_cb) { - + const hidl_string& propertyName, getPropertyByteArray_cb _hidl_cb) { Status status = Status::OK; std::string name(propertyName.c_str()); std::vector value; @@ -1366,11 +1333,11 @@ Return WVDrmPlugin::setPropertyString(const hidl_string& propertyName, } else if (_value == wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1.c_str()) { // We must be sure we CAN set the security level to L1. std::string current_security_level; - Status status = queryProperty( - wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, - current_security_level); + Status status = + queryProperty(wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, + current_security_level); if (status != Status::OK) { - return status; + return status; } if (current_security_level != wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1) { ALOGE("App requested L1 security on a non-L1 device."); @@ -1457,8 +1424,7 @@ Return WVDrmPlugin::setPropertyString(const hidl_string& propertyName, return mapCdmResponseType(res); } else if (name == "decryptHash") { wvcdm::CdmSessionId sessionId; - CdmResponseType res = - mCDM->SetDecryptHash(_value.c_str(), &sessionId); + CdmResponseType res = mCDM->SetDecryptHash(_value.c_str(), &sessionId); if (wvcdm::NO_ERROR == res) mDecryptHashSessionId = sessionId; @@ -1505,7 +1471,6 @@ Return WVDrmPlugin::setPropertyString(const hidl_string& propertyName, Return WVDrmPlugin::setPropertyByteArray( const hidl_string& propertyName, const hidl_vec& value) { - std::string name(propertyName.c_str()); std::vector _value = toVector(value); @@ -1533,7 +1498,6 @@ Return WVDrmPlugin::setPropertyByteArray( Return WVDrmPlugin::setCipherAlgorithm( const hidl_vec& sessionId, const hidl_string& algorithm) { - if (sessionId.size() == 0 || algorithm.size() == 0) { return Status::BAD_VALUE; } @@ -1556,9 +1520,8 @@ Return WVDrmPlugin::setCipherAlgorithm( return Status::OK; } -Return WVDrmPlugin::setMacAlgorithm( - const hidl_vec& sessionId, const hidl_string& algorithm) { - +Return WVDrmPlugin::setMacAlgorithm(const hidl_vec& sessionId, + const hidl_string& algorithm) { if (sessionId.size() == 0 || algorithm.size() == 0) { return Status::BAD_VALUE; } @@ -1581,13 +1544,11 @@ Return WVDrmPlugin::setMacAlgorithm( return Status::OK; } -Return WVDrmPlugin::encrypt( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& input, - const hidl_vec& iv, - encrypt_cb _hidl_cb) { - +Return WVDrmPlugin::encrypt(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& input, + const hidl_vec& iv, + encrypt_cb _hidl_cb) { const std::vector sId = toVector(sessionId); std::vector output; @@ -1611,8 +1572,7 @@ Return WVDrmPlugin::encrypt( if (res != OEMCrypto_SUCCESS) { ALOGE("OEMCrypto_SelectKey failed with %u", res); - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(output)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(output)); return Void(); } @@ -1628,19 +1588,16 @@ Return WVDrmPlugin::encrypt( _hidl_cb(Status::OK, toHidlVec(output)); } else { ALOGE("OEMCrypto_Generic_Encrypt failed with %u", res); - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(output)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(output)); } return Void(); } -Return WVDrmPlugin::decrypt( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& input, - const hidl_vec& iv, - decrypt_cb _hidl_cb) { - +Return WVDrmPlugin::decrypt(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& input, + const hidl_vec& iv, + decrypt_cb _hidl_cb) { const std::vector sId = toVector(sessionId); std::vector output; @@ -1664,8 +1621,7 @@ Return WVDrmPlugin::decrypt( if (res != OEMCrypto_SUCCESS) { ALOGE("OEMCrypto_SelectKey failed with %u", res); - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(output)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(output)); return Void(); } @@ -1681,18 +1637,15 @@ Return WVDrmPlugin::decrypt( _hidl_cb(Status::OK, toHidlVec(output)); } else { ALOGE("OEMCrypto_Generic_Decrypt failed with %u", res); - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(output)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(output)); } return Void(); } -Return WVDrmPlugin::sign( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& message, - sign_cb _hidl_cb) { - +Return WVDrmPlugin::sign(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& message, + sign_cb _hidl_cb) { const std::vector sId = toVector(sessionId); std::vector signature; @@ -1716,24 +1669,23 @@ Return WVDrmPlugin::sign( if (res != OEMCrypto_SUCCESS) { ALOGE("OEMCrypto_SelectKey failed with %u", res); - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(signature)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(signature)); return Void(); } size_t signatureSize = 0; const std::vector msg = toVector(message); - res = mCrypto->sign(cryptoSession.oecSessionId(), msg.data(), - msg.size(), cryptoSession.macAlgorithm(), - NULL, &signatureSize); + res = mCrypto->sign(cryptoSession.oecSessionId(), msg.data(), msg.size(), + cryptoSession.macAlgorithm(), NULL, &signatureSize); if (res != OEMCrypto_ERROR_SHORT_BUFFER) { - ALOGE("OEMCrypto_Generic_Sign failed with %u when requesting signature " - "size", res); + ALOGE( + "OEMCrypto_Generic_Sign failed with %u when requesting signature " + "size", + res); if (res != OEMCrypto_SUCCESS) { - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(signature)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(signature)); } else { _hidl_cb(Status::ERROR_DRM_UNKNOWN, toHidlVec(signature)); } @@ -1742,27 +1694,24 @@ Return WVDrmPlugin::sign( signature.resize(signatureSize); - res = mCrypto->sign(cryptoSession.oecSessionId(), msg.data(), - msg.size(), cryptoSession.macAlgorithm(), - signature.data(), &signatureSize); + res = mCrypto->sign(cryptoSession.oecSessionId(), msg.data(), msg.size(), + cryptoSession.macAlgorithm(), signature.data(), + &signatureSize); if (res == OEMCrypto_SUCCESS) { _hidl_cb(Status::OK, toHidlVec(signature)); } else { ALOGE("OEMCrypto_Generic_Sign failed with %u", res); - _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), - toHidlVec(signature)); + _hidl_cb(mapAndNotifyOfOEMCryptoResult(sId, res), toHidlVec(signature)); } return Void(); } -Return WVDrmPlugin::verify( - const hidl_vec& sessionId, - const hidl_vec& keyId, - const hidl_vec& message, - const hidl_vec& signature, - verify_cb _hidl_cb) { - +Return WVDrmPlugin::verify(const hidl_vec& sessionId, + const hidl_vec& keyId, + const hidl_vec& message, + const hidl_vec& signature, + verify_cb _hidl_cb) { bool match = false; const std::vector sId = toVector(sessionId); @@ -1809,26 +1758,26 @@ Return WVDrmPlugin::verify( return Void(); } -Return WVDrmPlugin::signRSA( - const hidl_vec& sessionId, - const hidl_string& algorithm, - const hidl_vec& message, - const hidl_vec& wrappedKey, - signRSA_cb _hidl_cb) { - - if (sessionId.size() == 0 || algorithm.size() == 0 || - message.size() == 0 || wrappedKey.size() == 0) { +Return WVDrmPlugin::signRSA(const hidl_vec& sessionId, + const hidl_string& algorithm, + const hidl_vec& message, + const hidl_vec& wrappedKey, + signRSA_cb _hidl_cb) { + if (sessionId.size() == 0 || algorithm.size() == 0 || message.size() == 0 || + wrappedKey.size() == 0) { _hidl_cb(Status::BAD_VALUE, hidl_vec()); return Void(); } const auto& self = android::hardware::IPCThreadState::self(); const char* sid = self->getCallingSid(); - if (!sid || (!strstr(sid, ":mediashell_app:") - && !strstr(sid, ":mediadrmserver:") - && !strstr(sid, ":setupwraith_app:"))) { - ALOGE("Only mediashell/mediadrmserver/setupwraith_app can call signRSA, " - "but actually: %s", sid); + if (!sid || + (!strstr(sid, ":mediashell_app:") && !strstr(sid, ":mediadrmserver:") && + !strstr(sid, ":setupwraith_app:"))) { + ALOGE( + "Only mediashell/mediadrmserver/setupwraith_app can call signRSA, " + "but actually: %s", + sid); _hidl_cb(Status::ERROR_DRM_UNKNOWN, hidl_vec()); return Void(); } @@ -1847,13 +1796,11 @@ Return WVDrmPlugin::signRSA( return Void(); } - const std::vector msg = toVector(message); - const std::vector _wrappedKey = toVector(wrappedKey); - OEMCryptoResult res = mCrypto->signRSA(_wrappedKey.data(), - _wrappedKey.size(), - msg.data(), msg.size(), - signature, - padding_scheme); + const std::vector msg = toVector(message); + const std::vector _wrappedKey = toVector(wrappedKey); + OEMCryptoResult res = + mCrypto->signRSA(_wrappedKey.data(), _wrappedKey.size(), msg.data(), + msg.size(), signature, padding_scheme); if (res != OEMCrypto_SUCCESS) { ALOGE("OEMCrypto_GenerateRSASignature failed with %u", res); @@ -1871,10 +1818,9 @@ Return WVDrmPlugin::setListener(const sp& listener) { return Void(); } -Return WVDrmPlugin::sendEvent( - EventType eventType, - const hidl_vec& sessionId, - const hidl_vec& data) { +Return WVDrmPlugin::sendEvent(EventType eventType, + const hidl_vec& sessionId, + const hidl_vec& data) { Return err{}; if (mListenerV1_2 != NULL) { err = mListenerV1_2->sendEvent(eventType, sessionId, data); @@ -1890,8 +1836,7 @@ Return WVDrmPlugin::sendEvent( } Return WVDrmPlugin::sendExpirationUpdate( - const hidl_vec& sessionId, - int64_t expiryTimeInMS) { + const hidl_vec& sessionId, int64_t expiryTimeInMS) { Return err{}; if (mListenerV1_2 != NULL) { err = mListenerV1_2->sendExpirationUpdate(sessionId, expiryTimeInMS); @@ -1906,34 +1851,35 @@ Return WVDrmPlugin::sendExpirationUpdate( return err; } -template<> -void WVDrmPlugin::_sendKeysChange( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, - bool hasNewUsableKey) { - auto err = mListener->sendKeysChange(sessionId, keyStatusList, hasNewUsableKey); +template <> +void WVDrmPlugin::_sendKeysChange(const hidl_vec& sessionId, + const hidl_vec& keyStatusList, + bool hasNewUsableKey) { + auto err = + mListener->sendKeysChange(sessionId, keyStatusList, hasNewUsableKey); if (!err.isOk()) { ALOGW("sendKeysChange failed %s", err.description().c_str()); } } -template<> -void WVDrmPlugin::_sendKeysChange( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, - bool hasNewUsableKey) { - auto err = mListenerV1_2->sendKeysChange_1_2(sessionId, keyStatusList, hasNewUsableKey); +template <> +void WVDrmPlugin::_sendKeysChange(const hidl_vec& sessionId, + const hidl_vec& keyStatusList, + bool hasNewUsableKey) { + auto err = mListenerV1_2->sendKeysChange_1_2(sessionId, keyStatusList, + hasNewUsableKey); if (!err.isOk()) { ALOGW("sendKeysChange_1_2 failed %s", err.description().c_str()); } } Return WVDrmPlugin::sendKeysChange( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, bool hasNewUsableKey) { + const hidl_vec& sessionId, + const hidl_vec& keyStatusList, bool hasNewUsableKey) { Return err{}; if (mListenerV1_2 != NULL) { - err = mListenerV1_2->sendKeysChange(sessionId, keyStatusList, hasNewUsableKey); + err = mListenerV1_2->sendKeysChange(sessionId, keyStatusList, + hasNewUsableKey); } else if (mListener != NULL) { err = mListener->sendKeysChange(sessionId, keyStatusList, hasNewUsableKey); } else { @@ -1946,11 +1892,12 @@ Return WVDrmPlugin::sendKeysChange( } Return WVDrmPlugin::sendKeysChange_1_2( - const hidl_vec& sessionId, - const hidl_vec& keyStatusList, bool hasNewUsableKey) { + const hidl_vec& sessionId, + const hidl_vec& keyStatusList, bool hasNewUsableKey) { Return err{}; if (mListenerV1_2 != NULL) { - err = mListenerV1_2->sendKeysChange_1_2(sessionId, keyStatusList, hasNewUsableKey); + err = mListenerV1_2->sendKeysChange_1_2(sessionId, keyStatusList, + hasNewUsableKey); } else { ALOGE("Null event listener, event not sent"); } @@ -1980,26 +1927,27 @@ Return WVDrmPlugin::getLogMessages(getLogMessages_cb _hidl_cb) { return Void(); } -Return WVDrmPlugin::requiresSecureDecoder( - const hidl_string& mime, SecurityLevel level) { +Return WVDrmPlugin::requiresSecureDecoder(const hidl_string& mime, + SecurityLevel level) { if (!strncasecmp(mime.c_str(), "video/", 6)) { // Type is video, so check level to see if we require a secure decoder. - return level == SecurityLevel::HW_SECURE_ALL - || level == SecurityLevel::HW_SECURE_DECODE; + return level == SecurityLevel::HW_SECURE_ALL || + level == SecurityLevel::HW_SECURE_DECODE; } else { // Type is not video, so never require a secure decoder. return false; } } -Return WVDrmPlugin::requiresSecureDecoderDefault(const hidl_string& mime) { +Return WVDrmPlugin::requiresSecureDecoderDefault( + const hidl_string& mime) { if (!strncasecmp(mime.c_str(), "video/", 6)) { // Type is video, so check level to see if we require a secure decoder. std::string level(mPropertySet.security_level()); if (level == kResetSecurityLevel) { - mCDM->QueryStatus(wvcdm::kLevelDefault, - wvcdm::QUERY_KEY_SECURITY_LEVEL, &level); + mCDM->QueryStatus(wvcdm::kLevelDefault, wvcdm::QUERY_KEY_SECURITY_LEVEL, + &level); } return level == wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1; @@ -2010,8 +1958,7 @@ Return WVDrmPlugin::requiresSecureDecoderDefault(const hidl_string& mime) } Return<::drm::V1_0::Status> WVDrmPlugin::setPlaybackId( - const hidl_vec& sessionId, - const hidl_string& playbackId) { + const hidl_vec& sessionId, const hidl_string& playbackId) { const std::vector sId = toVector(sessionId); CdmSessionId cdmSessionId(sId.begin(), sId.end()); std::string cdmPlaybackId = playbackId; @@ -2030,15 +1977,17 @@ void WVDrmPlugin::OnSessionKeysChange(const CdmSessionId& cdmSessionId, const CdmKeyStatusMap& cdmKeysStatus, bool hasNewUsableKey) { if (mListenerV1_2 != NULL) { - _OnSessionKeysChange(cdmSessionId, cdmKeysStatus, hasNewUsableKey); + _OnSessionKeysChange(cdmSessionId, cdmKeysStatus, + hasNewUsableKey); } else if (mListener != NULL) { - _OnSessionKeysChange(cdmSessionId, cdmKeysStatus, hasNewUsableKey); + _OnSessionKeysChange(cdmSessionId, cdmKeysStatus, + hasNewUsableKey); } else { ALOGE("Null event listener, event not sent"); } } -template +template void WVDrmPlugin::_OnSessionKeysChange(const CdmSessionId& cdmSessionId, const CdmKeyStatusMap& cdmKeysStatus, bool hasNewUsableKey) { @@ -2052,7 +2001,8 @@ void WVDrmPlugin::_OnSessionKeysChange(const CdmSessionId& cdmSessionId, KS keyStatus; keyStatus.keyId = toHidlVec(StrToVector(keyId)); - keyStatus.type = ConvertFromCdmKeyStatus(cdmKeyStatus); + keyStatus.type = + ConvertFromCdmKeyStatus(cdmKeyStatus); keyStatusList.push_back(keyStatus); } @@ -2071,7 +2021,8 @@ void WVDrmPlugin::OnExpirationUpdate(const CdmSessionId& cdmSessionId, const std::vector sessionId = StrToVector(cdmSessionId); int64_t newExpiryTimeMilliseconds = newExpiryTimeSeconds == wvcdm::NEVER_EXPIRES - ? newExpiryTimeSeconds : newExpiryTimeSeconds * 1000; + ? newExpiryTimeSeconds + : newExpiryTimeSeconds * 1000; sendExpirationUpdate(toHidlVec(sessionId), newExpiryTimeMilliseconds); } @@ -2082,13 +2033,13 @@ void WVDrmPlugin::OnSessionLostState(const CdmSessionId& cdmSessionId) { } Status WVDrmPlugin::queryProperty(const std::string& property, - std::string& stringValue) const { + std::string& stringValue) const { return queryProperty(getRequestedSecurityLevel(), property, stringValue); } -Status WVDrmPlugin::queryProperty(wvcdm::SecurityLevel securityLevel, - const std::string& property, - std::string& stringValue) const { +Status WVDrmPlugin::queryProperty(wvcdm::RequestedSecurityLevel securityLevel, + const std::string& property, + std::string& stringValue) const { CdmResponseType res = mCDM->QueryStatus(securityLevel, property, &stringValue); @@ -2099,7 +2050,7 @@ Status WVDrmPlugin::queryProperty(wvcdm::SecurityLevel securityLevel, } Status WVDrmPlugin::queryProperty(const std::string& property, - std::vector& vector_value) const { + std::vector& vector_value) const { std::string string_value; Status status = queryProperty(property, string_value); if (status != Status::OK) return status; @@ -2126,10 +2077,8 @@ Status_V1_2 WVDrmPlugin::mapAndNotifyOfCdmResponseType_1_2( return mapCdmResponseType(res); } -void WVDrmPlugin::notifyOfCdmResponseType( - const std::vector& sessionId, - CdmResponseType res) { - +void WVDrmPlugin::notifyOfCdmResponseType(const std::vector& sessionId, + CdmResponseType res) { const hidl_vec data; // data is ignored if (res == wvcdm::NEED_PROVISIONING) { sendEvent(EventType::PROVISION_REQUIRED, toHidlVec(sessionId), data); @@ -2139,9 +2088,7 @@ void WVDrmPlugin::notifyOfCdmResponseType( } Status WVDrmPlugin::mapAndNotifyOfOEMCryptoResult( - const std::vector& sessionId, - OEMCryptoResult res) { - + const std::vector& sessionId, OEMCryptoResult res) { const hidl_vec data; // data is ignored if (res == OEMCrypto_ERROR_NO_DEVICE_KEY) { sendEvent(EventType::PROVISION_REQUIRED, toHidlVec(sessionId), data); @@ -2181,11 +2128,11 @@ Status WVDrmPlugin::mapOEMCryptoResult(OEMCryptoResult res) { } } -wvcdm::SecurityLevel WVDrmPlugin::getRequestedSecurityLevel() const { +wvcdm::RequestedSecurityLevel WVDrmPlugin::getRequestedSecurityLevel() const { return mPropertySet.security_level().compare( - wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3) == 0 - ? wvcdm::kLevel3 - : wvcdm::kLevelDefault; + wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3) == 0 + ? wvcdm::kLevel3 + : wvcdm::kLevelDefault; } bool WVDrmPlugin::initDataResemblesPSSH(const std::vector& initData) { @@ -2229,11 +2176,11 @@ Status WVDrmPlugin::unprovision(const CdmIdentifier& identifier) { // Implementation for the CdmIdentifierBuilder inner class WVDrmPlugin::CdmIdentifierBuilder::CdmIdentifierBuilder( bool useSpoid, const WVDrmPlugin& parent, const std::string& appPackageName) - : mCdmIdentifier(), - mIsIdentifierSealed(false), - mUseSpoid(useSpoid), - mAppPackageName(appPackageName), - mParent(parent) { + : mCdmIdentifier(), + mIsIdentifierSealed(false), + mUseSpoid(useSpoid), + mAppPackageName(appPackageName), + mParent(parent) { mCdmIdentifier.app_package_name = mAppPackageName; mCdmIdentifier.unique_id = getNextUniqueId(); mCdmIdentifier.user_id = wvutil::GetIpcCallingUid(); @@ -2263,7 +2210,8 @@ Status WVDrmPlugin::CdmIdentifierBuilder::getDeviceUniqueId(std::string* id) { } } -Status WVDrmPlugin::CdmIdentifierBuilder::getProvisioningUniqueId(std::string* id) { +Status WVDrmPlugin::CdmIdentifierBuilder::getProvisioningUniqueId( + std::string* id) { if (mUseSpoid) { // To fake a provisioning-unique ID on SPOID devices where we can't expose // the real provisioning-unique ID, we just use the SPOID and invert all the @@ -2295,8 +2243,7 @@ bool WVDrmPlugin::CdmIdentifierBuilder::set_use_atsc_mode(bool enable) { } Status WVDrmPlugin::CdmIdentifierBuilder::calculateSpoid() { - if (!mUseSpoid) - return Status::OK; + if (!mUseSpoid) return Status::OK; // Calculate SPOID for default security level if appropriate std::string deviceId; @@ -2369,8 +2316,7 @@ Status WVDrmPlugin::CdmIdentifierBuilder::calculateSpoid() { Status WVDrmPlugin::CdmIdentifierBuilder::calculateSpoid( const std::string& deviceId, std::string* spoid) { - if (spoid == nullptr) - return Status::ERROR_DRM_CANNOT_HANDLE; + if (spoid == nullptr) return Status::ERROR_DRM_CANNOT_HANDLE; if (!mUseSpoid) { spoid->clear(); @@ -2395,8 +2341,7 @@ Status WVDrmPlugin::CdmIdentifierBuilder::getOemcryptoDeviceId( } Status WVDrmPlugin::CdmIdentifierBuilder::getOemcryptoDeviceId( - wvcdm::SecurityLevel securityLevel, - std::string* id) { + wvcdm::RequestedSecurityLevel securityLevel, std::string* id) { return mParent.queryProperty(securityLevel, wvcdm::QUERY_KEY_DEVICE_ID, *id); } diff --git a/libwvdrmengine/mediadrm/test/Android.mk b/libwvdrmengine/mediadrm/test/Android.mk index 146fa7fe..bc449b2a 100644 --- a/libwvdrmengine/mediadrm/test/Android.mk +++ b/libwvdrmengine/mediadrm/test/Android.mk @@ -23,7 +23,7 @@ LOCAL_C_INCLUDES := \ LOCAL_STATIC_LIBRARIES := \ libcdm \ libcdm_protos \ - libcdm_utils \ + libcdm_utils_hidl \ libjsmn \ libgmock \ libgmock_main \ diff --git a/libwvdrmengine/mediadrm/test/WVDrmPlugin_test.cpp b/libwvdrmengine/mediadrm/test/WVDrmPlugin_test.cpp index 3d576fd4..8e567b32 100644 --- a/libwvdrmengine/mediadrm/test/WVDrmPlugin_test.cpp +++ b/libwvdrmengine/mediadrm/test/WVDrmPlugin_test.cpp @@ -5,22 +5,22 @@ // //#define LOG_NDEBUG 0 #define LOG_TAG "WVDrmPluginTest" +#include "WVDrmPlugin.h" + +#include #include #include #include -#include #include #include -#include "gmock/gmock.h" -#include "gtest/gtest.h" - #include "HidlTypes.h" #include "TypeConvert.h" -#include "WVDrmPlugin.h" #include "WVErrors.h" #include "cdm_client_property_set.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" #include "media/stagefright/MediaErrors.h" #include "media/stagefright/foundation/ABase.h" #include "string_conversions.h" @@ -52,8 +52,8 @@ using ::testing::Pointee; using ::testing::SaveArg; using ::testing::SetArgPointee; using ::testing::SetArrayArgument; -using ::testing::StrictMock; using ::testing::StrEq; +using ::testing::StrictMock; using ::testing::Test; using ::testing::Values; using ::testing::WithParamInterface; @@ -75,8 +75,8 @@ using wvcdm::CdmClientPropertySet; using wvcdm::CdmIdentifier; using wvcdm::CdmInitData; using wvcdm::CdmKeyMessage; -using wvcdm::CdmKeyResponse; using wvcdm::CdmKeyRequest; +using wvcdm::CdmKeyResponse; using wvcdm::CdmKeySetId; using wvcdm::CdmKeySystem; using wvcdm::CdmLicenseType; @@ -89,24 +89,33 @@ using wvcdm::CdmSecurityLevel; using wvcdm::CdmUsageInfo; using wvcdm::CdmUsageInfoReleaseMessage; using wvcdm::EMPTY_ORIGIN; +using wvcdm::kCertificateWidevine; using wvcdm::KEY_ID_SIZE; using wvcdm::KEY_IV_SIZE; using wvcdm::KEY_SET_ID_PREFIX; +using wvcdm::kKeyRequestTypeInitial; +using wvcdm::kKeyRequestTypeRelease; +using wvcdm::kKeyRequestTypeRenewal; +using wvcdm::kLicenseTypeOffline; +using wvcdm::kLicenseTypeRelease; +using wvcdm::kLicenseTypeStreaming; +using wvcdm::kSecurityLevelL1; +using wvcdm::kSecurityLevelL3; using wvcdm::NEVER_EXPIRES; using wvcdm::QUERY_KEY_CURRENT_SRM_VERSION; -using wvcdm::QUERY_KEY_DEVICE_ID; using wvcdm::QUERY_KEY_DECRYPT_HASH_SUPPORT; +using wvcdm::QUERY_KEY_DEVICE_ID; using wvcdm::QUERY_KEY_MAX_NUMBER_OF_SESSIONS; using wvcdm::QUERY_KEY_NUMBER_OF_OPEN_SESSIONS; using wvcdm::QUERY_KEY_OEMCRYPTO_API_VERSION; +using wvcdm::QUERY_KEY_OEMCRYPTO_BUILD_INFORMATION; using wvcdm::QUERY_KEY_OEMCRYPTO_SESSION_ID; using wvcdm::QUERY_KEY_PROVISIONING_ID; +using wvcdm::QUERY_KEY_RESOURCE_RATING_TIER; using wvcdm::QUERY_KEY_SECURITY_LEVEL; using wvcdm::QUERY_KEY_SRM_UPDATE_SUPPORT; using wvcdm::QUERY_KEY_SYSTEM_ID; using wvcdm::QUERY_KEY_WVCDM_VERSION; -using wvcdm::QUERY_KEY_RESOURCE_RATING_TIER; -using wvcdm::QUERY_KEY_OEMCRYPTO_BUILD_INFORMATION; using wvcdm::QUERY_VALUE_SECURITY_LEVEL_L1; using wvcdm::QUERY_VALUE_SECURITY_LEVEL_L3; using wvcdm::SESSION_ID_PREFIX; @@ -131,9 +140,10 @@ const char kSerializedMetricsHex[] = "0310b739820102100d8a01060801120248009a010310ff01da0106080112024800e2010e1d" "005243472801320528800248009a020d1d00b016452801320428404800a202060801120248" "19aa0206080212024800b2020b1d8098f047280132024800ba02021001ca020b1d00101945" - "280132024800e202021004fa02021002a203021000b2030210021a09196891ed7c3f355040"; + "280132024800e202021004fa02021002a203021000b2030210021a09196891ed7c3f35504" + "0"; -#define N_ELEM(a) (sizeof(a)/sizeof(a[0])) +#define N_ELEM(a) (sizeof(a) / sizeof(a[0])) } // anonymous namespace class MockCDM : public WvContentDecryptionModule { @@ -162,7 +172,7 @@ class MockCDM : public WvContentDecryptionModule { MOCK_METHOD(CdmResponseType, RestoreKey, (const CdmSessionId&, const CdmKeySetId&), (override)); - MOCK_METHOD(CdmResponseType, QueryStatus, (wvcdm::SecurityLevel, + MOCK_METHOD(CdmResponseType, QueryStatus, (wvcdm::RequestedSecurityLevel, const std::string&, std::string*), (override)); @@ -179,13 +189,13 @@ class MockCDM : public WvContentDecryptionModule { const std::string&, const CdmIdentifier&, const std::string&, - wvcdm::SecurityLevel, + wvcdm::RequestedSecurityLevel, CdmProvisioningRequest*, std::string*), (override)); MOCK_METHOD(CdmResponseType, HandleProvisioningResponse, (const CdmIdentifier&, CdmProvisioningResponse&, - wvcdm::SecurityLevel, std::string*, std::string*), (override)); + wvcdm::RequestedSecurityLevel, std::string*, std::string*), (override)); MOCK_METHOD(CdmResponseType, Unprovision, (CdmSecurityLevel, const CdmIdentifier&), (override)); @@ -278,7 +288,6 @@ class MockDrmPluginListener : public IDrmPluginListener_V1_2 { MOCK_METHOD(Return, sendKeysChange_1_2, (const hidl_vec&, const hidl_vec&, bool), (override)); - }; template @@ -288,9 +297,7 @@ CdmResponseType setSessionIdOnMap(testing::Unused, CdmQueryMap* map) { return wvcdm::NO_ERROR; } -MATCHER_P(HasOrigin, origin, "") { - return arg.origin == origin; -} +MATCHER_P(HasOrigin, origin, "") { return arg.origin == origin; } class WVDrmPluginTest : public Test { protected: @@ -331,8 +338,9 @@ struct OriginTestVariant { OriginTestVariant(const std::string& nameValue, const std::string& originValue, const std::string& expectedOriginValue) - : name(nameValue), origin(originValue), - expectedOrigin(expectedOriginValue) {} + : name(nameValue), + origin(originValue), + expectedOrigin(expectedOriginValue) {} const std::string name; const std::string origin; @@ -341,7 +349,6 @@ struct OriginTestVariant { void PrintTo(const OriginTestVariant& param, ::std::ostream* os) { *os << param.name << " Variant"; - } class WVDrmPluginOriginTest : public WVDrmPluginTest, @@ -352,18 +359,17 @@ TEST_F(WVDrmPluginTest, OpensSessions) { StrictMock crypto; std::string appPackageName; - EXPECT_CALL(*cdm, - OpenSession(StrEq("com.widevine"), _, HasOrigin(EMPTY_ORIGIN), _, _)) - .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), - testing::Return(wvcdm::NO_ERROR))); + EXPECT_CALL(*cdm, OpenSession(StrEq("com.widevine"), _, + HasOrigin(EMPTY_ORIGIN), _, _)) + .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), + testing::Return(wvcdm::NO_ERROR))); // Provide expected mock behavior EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -401,27 +407,29 @@ TEST_F(WVDrmPluginTest, OpensSessions_1_1) { testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, OpenSession(_, _, _, _, _)) - .WillRepeatedly(DoAll(SetArgPointee<4>(cdmSessionId), - SaveArg<1>(&propertySet), - testing::Return(wvcdm::NO_ERROR))); + .WillRepeatedly(DoAll(SetArgPointee<4>(cdmSessionId), + SaveArg<1>(&propertySet), + testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); + Status status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); ASSERT_EQ(Status::OK, status); - plugin.openSession_1_1(android::hardware::drm::V1_1::SecurityLevel::SW_SECURE_CRYPTO, + plugin.openSession_1_1( + android::hardware::drm::V1_1::SecurityLevel::SW_SECURE_CRYPTO, [&](Status status, hidl_vec hSessionId) { - ASSERT_EQ(Status::OK, status); - sessionId.clear(); - sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); - }); + ASSERT_EQ(Status::OK, status); + sessionId.clear(); + sessionId.assign(hSessionId.data(), + hSessionId.data() + hSessionId.size()); + }); ASSERT_THAT(propertySet, NotNull()); EXPECT_THAT(sessionId, ElementsAreArray(sessionIdRaw, kSessionIdSize)); @@ -434,8 +442,7 @@ TEST_F(WVDrmPluginTest, ClosesSessions) { StrictMock crypto; std::string appPackageName; - EXPECT_CALL(*cdm, CloseSession(cdmSessionId)) - .Times(1); + EXPECT_CALL(*cdm, CloseSession(cdmSessionId)).Times(1); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); Status status = plugin.closeSession(toHidlVec(sessionId)); @@ -482,6 +489,7 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesKeyRequests) { std::vector initData; initData.assign(initDataRaw, initDataRaw + kInitDataSize); + // clang-format off static const uint8_t psshPrefix[] = { 0, 0, 0, 32 + kInitDataSize, // Total size 'p', 's', 's', 'h', // "PSSH" @@ -490,6 +498,7 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesKeyRequests) { 0xA3, 0xC8, 0x27, 0xDC, 0xD5, 0x1D, 0x21, 0xED, 0, 0, 0, kInitDataSize // Size of initData }; + // clang-format on static const size_t kPsshPrefixSize = sizeof(psshPrefix); static const size_t kPsshBoxSize = kPsshPrefixSize + kInitDataSize; uint8_t psshBoxRaw[kPsshBoxSize]; @@ -509,14 +518,13 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesKeyRequests) { parameters.insert( std::pair("favorite-particle", "tetraquark")); cdmParameters["favorite-particle"] = "tetraquark"; - parameters.insert( - std::pair("answer", "6 * 9")); + parameters.insert(std::pair("answer", "6 * 9")); cdmParameters["answer"] = "6 * 9"; std::vector optionalParameters; KeyValue keyValue; for (std::map::iterator itr = parameters.begin(); - itr != parameters.end(); ++itr) { + itr != parameters.end(); ++itr) { keyValue.key = itr->first; keyValue.value = itr->second; optionalParameters.push_back(keyValue); @@ -535,9 +543,9 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesKeyRequests) { // We run the same set of operations on several sets of data, simulating // different valid calling patterns. TestSet testSets[] = { - {kIsoBmffMimeType, psshBox, cdmPsshBox}, // ISO-BMFF, EME passing style - {kIsoBmffMimeType, initData, cdmPsshBox}, // ISO-BMFF, old passing style - {kWebmMimeType, initData, cdmInitData} // WebM + {kIsoBmffMimeType, psshBox, cdmPsshBox}, // ISO-BMFF, EME passing style + {kIsoBmffMimeType, initData, cdmPsshBox}, // ISO-BMFF, old passing style + {kWebmMimeType, initData, cdmInitData} // WebM }; size_t testSetCount = N_ELEM(testSets); @@ -546,47 +554,37 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesKeyRequests) { { InSequence calls; - for (size_t i = 0; i < testSetCount; ++i) - { + for (size_t i = 0; i < testSetCount; ++i) { const char* mimeType = testSets[i].mimeType; const CdmInitData& initData = testSets[i].initDataOut; - CdmKeyRequest initialRequest = { - cdmRequest, - kKeyRequestTypeInitial, - kDefaultUrl - }; + CdmKeyRequest initialRequest = {cdmRequest, kKeyRequestTypeInitial, + kDefaultUrl}; - CdmKeyRequest renewalRequest = { - cdmRequest, - kKeyRequestTypeRenewal, - kDefaultUrl - }; + CdmKeyRequest renewalRequest = {cdmRequest, kKeyRequestTypeRenewal, + kDefaultUrl}; - CdmKeyRequest releaseRequest = { - cdmRequest, - kKeyRequestTypeRelease, - kDefaultUrl - }; + CdmKeyRequest releaseRequest = {cdmRequest, kKeyRequestTypeRelease, + kDefaultUrl}; - EXPECT_CALL(*cdm, GenerateKeyRequest(cdmSessionId, "", mimeType, initData, - kLicenseTypeOffline, cdmParameters, - NotNull(), HasOrigin(EMPTY_ORIGIN), - _)) + EXPECT_CALL(*cdm, + GenerateKeyRequest(cdmSessionId, "", mimeType, initData, + kLicenseTypeOffline, cdmParameters, + NotNull(), HasOrigin(EMPTY_ORIGIN), _)) .WillOnce(DoAll(SetArgPointee<8>(initialRequest), testing::Return(wvcdm::KEY_MESSAGE))); - EXPECT_CALL(*cdm, GenerateKeyRequest(cdmSessionId, "", mimeType, initData, - kLicenseTypeStreaming, cdmParameters, - NotNull(), HasOrigin(EMPTY_ORIGIN), - _)) + EXPECT_CALL(*cdm, + GenerateKeyRequest(cdmSessionId, "", mimeType, initData, + kLicenseTypeStreaming, cdmParameters, + NotNull(), HasOrigin(EMPTY_ORIGIN), _)) .WillOnce(DoAll(SetArgPointee<8>(renewalRequest), testing::Return(wvcdm::KEY_MESSAGE))); - EXPECT_CALL(*cdm, GenerateKeyRequest("", cdmKeySetId, mimeType, initData, - kLicenseTypeRelease, cdmParameters, - NotNull(), HasOrigin(EMPTY_ORIGIN), - _)) + EXPECT_CALL(*cdm, + GenerateKeyRequest("", cdmKeySetId, mimeType, initData, + kLicenseTypeRelease, cdmParameters, + NotNull(), HasOrigin(EMPTY_ORIGIN), _)) .WillOnce(DoAll(SetArgPointee<8>(releaseRequest), testing::Return(wvcdm::KEY_MESSAGE))); @@ -595,49 +593,48 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesKeyRequests) { // Performs the actual tests WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - for (size_t i = 0; i < testSetCount; ++i) - { + for (size_t i = 0; i < testSetCount; ++i) { const std::string mimeType(testSets[i].mimeType); const std::vector& initData = testSets[i].initDataIn; plugin.getKeyRequest( - toHidlVec(sessionId), toHidlVec(initData), - hidl_string(mimeType), KeyType::OFFLINE, toHidlVec(optionalParameters), + toHidlVec(sessionId), toHidlVec(initData), hidl_string(mimeType), + KeyType::OFFLINE, toHidlVec(optionalParameters), [&](Status status, hidl_vec hRequest, KeyRequestType keyRequestType, hidl_string defaultUrl) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector request(hRequest); - EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); - EXPECT_EQ(KeyRequestType::INITIAL, keyRequestType); - EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); - }); + std::vector request(hRequest); + EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); + EXPECT_EQ(KeyRequestType::INITIAL, keyRequestType); + EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); + }); plugin.getKeyRequest( - toHidlVec(sessionId), toHidlVec(initData), - hidl_string(mimeType), KeyType::STREAMING, toHidlVec(optionalParameters), + toHidlVec(sessionId), toHidlVec(initData), hidl_string(mimeType), + KeyType::STREAMING, toHidlVec(optionalParameters), [&](Status status, hidl_vec hRequest, KeyRequestType keyRequestType, hidl_string defaultUrl) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector request(hRequest); - EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); - EXPECT_EQ(KeyRequestType::RENEWAL, keyRequestType); - EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); - }); + std::vector request(hRequest); + EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); + EXPECT_EQ(KeyRequestType::RENEWAL, keyRequestType); + EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); + }); plugin.getKeyRequest( - toHidlVec(sessionId), toHidlVec(initData), - hidl_string(mimeType), KeyType::RELEASE, toHidlVec(optionalParameters), + toHidlVec(sessionId), toHidlVec(initData), hidl_string(mimeType), + KeyType::RELEASE, toHidlVec(optionalParameters), [&](Status status, hidl_vec hRequest, KeyRequestType keyRequestType, hidl_string defaultUrl) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector request(hRequest); - EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); - EXPECT_EQ(KeyRequestType::RELEASE, keyRequestType); - EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); - }); + std::vector request(hRequest); + EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); + EXPECT_EQ(KeyRequestType::RELEASE, keyRequestType); + EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); + }); } } @@ -659,18 +656,18 @@ TEST_F(WVDrmPluginTest, AddsKeys) { response.assign(responseRaw, responseRaw + kResponseSize); memcpy(keySetIdRaw, KEY_SET_ID_PREFIX, sizeof(KEY_SET_ID_PREFIX) - 1); - CdmKeySetId cdmKeySetId(reinterpret_cast(keySetIdRaw), kKeySetIdSize); + CdmKeySetId cdmKeySetId(reinterpret_cast(keySetIdRaw), kKeySetIdSize); std::vector keySetId; std::vector emptyKeySetId; EXPECT_CALL(*cdm, AddKey(cdmSessionId, - ElementsAreArray(responseRaw, kResponseSize), _)) + ElementsAreArray(responseRaw, kResponseSize), _)) .WillOnce(DoAll(SetArgPointee<2>(cdmKeySetId), testing::Return(wvcdm::KEY_ADDED))); EXPECT_CALL(*cdm, AddKey("", ElementsAreArray(responseRaw, kResponseSize), - Pointee(cdmKeySetId))) + Pointee(cdmKeySetId))) .Times(1); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -678,20 +675,19 @@ TEST_F(WVDrmPluginTest, AddsKeys) { plugin.provideKeyResponse( toHidlVec(sessionId), toHidlVec(response), [&](Status status, hidl_vec hKeySetId) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector id(hKeySetId); - keySetId.assign(id.data(), id.data() + id.size()); - ASSERT_THAT(keySetId, ElementsAreArray(keySetIdRaw, kKeySetIdSize)); - }); + std::vector id(hKeySetId); + keySetId.assign(id.data(), id.data() + id.size()); + ASSERT_THAT(keySetId, ElementsAreArray(keySetIdRaw, kKeySetIdSize)); + }); - plugin.provideKeyResponse( - toHidlVec(keySetId), toHidlVec(response), - [&](Status status, hidl_vec hKeySetId) { - ASSERT_EQ(Status::OK, status); + plugin.provideKeyResponse(toHidlVec(keySetId), toHidlVec(response), + [&](Status status, hidl_vec hKeySetId) { + ASSERT_EQ(Status::OK, status); - EXPECT_EQ(0u, hKeySetId.size()); - }); + EXPECT_EQ(0u, hKeySetId.size()); + }); } TEST_F(WVDrmPluginTest, HandlesPrivacyCertCaseOfAddKey) { @@ -699,7 +695,7 @@ TEST_F(WVDrmPluginTest, HandlesPrivacyCertCaseOfAddKey) { StrictMock crypto; std::string appPackageName; - sp > listener = + sp> listener = new StrictMock(); const CdmClientPropertySet* propertySet = nullptr; @@ -715,8 +711,7 @@ TEST_F(WVDrmPluginTest, HandlesPrivacyCertCaseOfAddKey) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); static const uint32_t kResponseSize = 256; uint8_t responseRaw[kResponseSize]; @@ -758,8 +753,8 @@ TEST_F(WVDrmPluginTest, HandlesPrivacyCertCaseOfAddKey) { plugin.provideKeyResponse( toHidlVec(sessionId), toHidlVec(response), [&](Status status, hidl_vec /* keySetId */) { - ASSERT_EQ(Status::OK, status); - }); + ASSERT_EQ(Status::OK, status); + }); } TEST_F(WVDrmPluginTest, RemovesKeys) { @@ -767,8 +762,7 @@ TEST_F(WVDrmPluginTest, RemovesKeys) { StrictMock crypto; std::string appPackageName; - EXPECT_CALL(*cdm, RemoveKeys(cdmSessionId)) - .Times(1); + EXPECT_CALL(*cdm, RemoveKeys(cdmSessionId)).Times(1); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); Status status = plugin.removeKeys(toHidlVec(sessionId)); @@ -812,20 +806,22 @@ TEST_F(WVDrmPluginTest, QueriesKeyStatus) { testing::Return(wvcdm::NO_ERROR))); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - plugin.queryKeyStatus(toHidlVec(sessionId), - [&](Status status, hidl_vec(hLicenseStatus)) { - ASSERT_EQ(Status::OK, status); - ASSERT_EQ(expectedLicenseStatus.size(), hLicenseStatus.size()); + plugin.queryKeyStatus( + toHidlVec(sessionId), + [&](Status status, hidl_vec(hLicenseStatus)) { + ASSERT_EQ(Status::OK, status); + ASSERT_EQ(expectedLicenseStatus.size(), hLicenseStatus.size()); - KeyValue keyValuePair; - size_t i = 0; - for (std::map::iterator itr = - expectedLicenseStatus.begin(); - itr != expectedLicenseStatus.end(); ++itr) { - keyValuePair.value = hLicenseStatus[i++].value; - EXPECT_EQ(itr->second.c_str(), std::string(keyValuePair.value.c_str())); - } - }); + KeyValue keyValuePair; + size_t i = 0; + for (std::map::iterator itr = + expectedLicenseStatus.begin(); + itr != expectedLicenseStatus.end(); ++itr) { + keyValuePair.value = hLicenseStatus[i++].value; + EXPECT_EQ(itr->second.c_str(), + std::string(keyValuePair.value.c_str())); + } + }); } TEST_F(WVDrmPluginTest, GetsProvisioningRequests) { @@ -854,8 +850,8 @@ TEST_F(WVDrmPluginTest, GetsProvisioningRequests) { wvcdm::kLevelDefault, _, _)) .Times(2) .WillRepeatedly(DoAll(SetArgPointee<5>(cdmRequest), - SetArgPointee<6>(kDefaultUrl), - testing::Return(wvcdm::NO_ERROR))); + SetArgPointee<6>(kDefaultUrl), + testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, GetProvisioningRequest(kCertificateWidevine, IsEmpty(), HasOrigin(EMPTY_ORIGIN), IsEmpty(), wvcdm::kLevel3, _, _)) @@ -868,40 +864,40 @@ TEST_F(WVDrmPluginTest, GetsProvisioningRequests) { plugin.getProvisionRequest( hidl_string(""), hidl_string(""), [&](Status status, hidl_vec hRequest, hidl_string defaultUrl) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector request(hRequest); - EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); - EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); - }); + std::vector request(hRequest); + EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); + EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); + }); // Set L3 security level - Status status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L3")); + Status status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L3")); ASSERT_EQ(Status::OK, status); plugin.getProvisionRequest( hidl_string(""), hidl_string(""), [&](Status status, hidl_vec hRequest, hidl_string defaultUrl) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector request(hRequest); - EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); - EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); - }); + std::vector request(hRequest); + EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); + EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); + }); // Reset security level to L1 - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L1")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); ASSERT_EQ(Status::OK, status); plugin.getProvisionRequest( hidl_string(""), hidl_string(""), [&](Status status, hidl_vec hRequest, hidl_string defaultUrl) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector request(hRequest); - EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); - EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); - }); + std::vector request(hRequest); + EXPECT_THAT(request, ElementsAreArray(requestRaw, kRequestSize)); + EXPECT_STREQ(kDefaultUrl, defaultUrl.c_str()); + }); } TEST_F(WVDrmPluginTest, RejectsAtscProvisioningRequests) { @@ -911,15 +907,15 @@ TEST_F(WVDrmPluginTest, RejectsAtscProvisioningRequests) { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("atscMode"), - hidl_string("enable")); + Status status = + plugin.setPropertyString(hidl_string("atscMode"), hidl_string("enable")); ASSERT_EQ(Status::OK, status); plugin.getProvisionRequest( hidl_string(""), hidl_string(""), - [&](Status status, hidl_vec , hidl_string ) { - ASSERT_EQ(Status::ERROR_DRM_CANNOT_HANDLE, status); - }); + [&](Status status, hidl_vec, hidl_string) { + ASSERT_EQ(Status::ERROR_DRM_CANNOT_HANDLE, status); + }); } TEST_F(WVDrmPluginTest, HandlesProvisioningResponses) { @@ -942,15 +938,15 @@ TEST_F(WVDrmPluginTest, HandlesProvisioningResponses) { // The first and the third invocation should be at default security level, // while the second one should be L3 - EXPECT_CALL(*cdm, HandleProvisioningResponse(HasOrigin(EMPTY_ORIGIN), - ElementsAreArray(responseRaw, - kResponseSize), - wvcdm::kLevelDefault, _, _)) + EXPECT_CALL(*cdm, HandleProvisioningResponse( + HasOrigin(EMPTY_ORIGIN), + ElementsAreArray(responseRaw, kResponseSize), + wvcdm::kLevelDefault, _, _)) .Times(2); - EXPECT_CALL(*cdm, HandleProvisioningResponse(HasOrigin(EMPTY_ORIGIN), - ElementsAreArray(responseRaw, - kResponseSize), - wvcdm::kLevel3, _, _)) + EXPECT_CALL(*cdm, HandleProvisioningResponse( + HasOrigin(EMPTY_ORIGIN), + ElementsAreArray(responseRaw, kResponseSize), + wvcdm::kLevel3, _, _)) .Times(1); std::vector cert; @@ -961,29 +957,25 @@ TEST_F(WVDrmPluginTest, HandlesProvisioningResponses) { plugin.provideProvisionResponse( toHidlVec(response), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - ASSERT_EQ(Status::OK, status); - }); + hidl_vec /* key */) { ASSERT_EQ(Status::OK, status); }); // Set L3 security level - Status status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L3")); + Status status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L3")); + ASSERT_EQ(Status::OK, status); + plugin.provideProvisionResponse( toHidlVec(response), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - ASSERT_EQ(Status::OK, status); - }); + hidl_vec /* key */) { ASSERT_EQ(Status::OK, status); }); // Reset security level to L1 - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L1")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); plugin.provideProvisionResponse( toHidlVec(response), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - ASSERT_EQ(Status::OK, status); - }); + hidl_vec /* key */) { ASSERT_EQ(Status::OK, status); }); } TEST_F(WVDrmPluginTest, UnprovisionsDevice) { @@ -1032,8 +1024,8 @@ TEST_F(WVDrmPluginTest, UnprovisionsOrigin) { std::string appPackageName; std::vector specialResponse; - specialResponse.assign( - kUnprovisionResponse, kUnprovisionResponse + kUnprovisionResponseSize); + specialResponse.assign(kUnprovisionResponse, + kUnprovisionResponse + kUnprovisionResponseSize); EXPECT_CALL(*cdm, Unprovision(kSecurityLevelL1, HasOrigin(kOrigin.c_str()))) .Times(1); @@ -1042,16 +1034,14 @@ TEST_F(WVDrmPluginTest, UnprovisionsOrigin) { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("origin"), - hidl_string(kOrigin)); + Status status = + plugin.setPropertyString(hidl_string("origin"), hidl_string(kOrigin)); ASSERT_EQ(Status::OK, status); plugin.provideProvisionResponse( toHidlVec(specialResponse), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - EXPECT_EQ(Status::OK, status); - }); + hidl_vec /* key */) { EXPECT_EQ(Status::OK, status); }); } TEST_F(WVDrmPluginTest, UnprovisionsGloballyWithSpoid) { @@ -1060,12 +1050,12 @@ TEST_F(WVDrmPluginTest, UnprovisionsGloballyWithSpoid) { std::string appPackageName; std::vector specialResponse; - specialResponse.assign( - kUnprovisionResponse, kUnprovisionResponse + kUnprovisionResponseSize); + specialResponse.assign(kUnprovisionResponse, + kUnprovisionResponse + kUnprovisionResponseSize); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_DEVICE_ID, _)) - .WillRepeatedly(DoAll(SetArgPointee<2>(kDeviceId), - testing::Return(wvcdm::NO_ERROR))); + .WillRepeatedly( + DoAll(SetArgPointee<2>(kDeviceId), testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, Unprovision(kSecurityLevelL1, HasOrigin(EMPTY_ORIGIN))) .Times(1); @@ -1076,9 +1066,7 @@ TEST_F(WVDrmPluginTest, UnprovisionsGloballyWithSpoid) { plugin.provideProvisionResponse( toHidlVec(specialResponse), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - EXPECT_EQ(Status::OK, status); - }); + hidl_vec /* key */) { EXPECT_EQ(Status::OK, status); }); } TEST_F(WVDrmPluginTest, WillNotUnprovisionWithoutOriginOrSpoid) { @@ -1087,19 +1075,16 @@ TEST_F(WVDrmPluginTest, WillNotUnprovisionWithoutOriginOrSpoid) { std::string appPackageName; std::vector specialResponse; - specialResponse.assign( - kUnprovisionResponse, kUnprovisionResponse + kUnprovisionResponseSize); + specialResponse.assign(kUnprovisionResponse, + kUnprovisionResponse + kUnprovisionResponseSize); - EXPECT_CALL(*cdm, Unprovision(_, _)) - .Times(0); + EXPECT_CALL(*cdm, Unprovision(_, _)).Times(0); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); plugin.provideProvisionResponse( toHidlVec(specialResponse), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - EXPECT_NE(Status::OK, status); - }); + hidl_vec /* key */) { EXPECT_NE(Status::OK, status); }); } TEST_F(WVDrmPluginTest, MuxesOriginUnprovisioningErrors) { @@ -1108,8 +1093,8 @@ TEST_F(WVDrmPluginTest, MuxesOriginUnprovisioningErrors) { std::string appPackageName; std::vector specialResponse; - specialResponse.assign( - kUnprovisionResponse, kUnprovisionResponse + kUnprovisionResponseSize); + specialResponse.assign(kUnprovisionResponse, + kUnprovisionResponse + kUnprovisionResponseSize); // Tests that both Unprovisions are called even if one fails. Also tests that // no matter which fails, the function always propagates the error. @@ -1124,30 +1109,24 @@ TEST_F(WVDrmPluginTest, MuxesOriginUnprovisioningErrors) { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("origin"), - hidl_string(kOrigin)); + Status status = + plugin.setPropertyString(hidl_string("origin"), hidl_string(kOrigin)); ASSERT_EQ(Status::OK, status); plugin.provideProvisionResponse( toHidlVec(specialResponse), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - EXPECT_NE(Status::OK, status); - }); + hidl_vec /* key */) { EXPECT_NE(Status::OK, status); }); plugin.provideProvisionResponse( toHidlVec(specialResponse), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - EXPECT_NE(Status::OK, status); - }); + hidl_vec /* key */) { EXPECT_NE(Status::OK, status); }); plugin.provideProvisionResponse( toHidlVec(specialResponse), [&](Status status, hidl_vec /* cert */, - hidl_vec /* key */) { - EXPECT_NE(Status::OK, status); - }); + hidl_vec /* key */) { EXPECT_NE(Status::OK, status); }); } TEST_F(WVDrmPluginTest, RejectsAtscUnprovisionDeviceRequests) { @@ -1157,8 +1136,8 @@ TEST_F(WVDrmPluginTest, RejectsAtscUnprovisionDeviceRequests) { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("atscMode"), - hidl_string("enable")); + Status status = + plugin.setPropertyString(hidl_string("atscMode"), hidl_string("enable")); status = plugin.unprovisionDevice(); ASSERT_EQ(Status::ERROR_DRM_CANNOT_HANDLE, status); @@ -1185,14 +1164,14 @@ TEST_F(WVDrmPluginTest, GetsSecureStops) { const char* app_id = "my_app_id"; EXPECT_CALL(*cdm, GetUsageInfo(StrEq(app_id), _, _)) - .WillOnce(DoAll(SetArgPointee<2>(cdmStops), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce( + DoAll(SetArgPointee<2>(cdmStops), testing::Return(wvcdm::NO_ERROR))); - std::vector > stops; + std::vector> stops; WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("appId"), - hidl_string(app_id)); + Status status = + plugin.setPropertyString(hidl_string("appId"), hidl_string(app_id)); ASSERT_EQ(Status::OK, status); plugin.getSecureStops([&](Status status, hidl_vec hSecureStops) { @@ -1219,13 +1198,12 @@ TEST_F(WVDrmPluginTest, ReleasesAllSecureStops) { StrictMock crypto; std::string appPackageName; - EXPECT_CALL(*cdm, RemoveAllUsageInfo(StrEq(""), _)) - .Times(1); + EXPECT_CALL(*cdm, RemoveAllUsageInfo(StrEq(""), _)).Times(1); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString(hidl_string("appId"), - hidl_string("")); + Status status = + plugin.setPropertyString(hidl_string("appId"), hidl_string("")); ASSERT_EQ(Status::OK, status); status = plugin.releaseAllSecureStops(); @@ -1246,9 +1224,8 @@ TEST_F(WVDrmPluginTest, ReleasesSecureStop) { std::vector message; message.assign(messageRaw, messageRaw + kMessageSize); - EXPECT_CALL(*cdm, ReleaseUsageInfo(ElementsAreArray(messageRaw, - kMessageSize), - _)) + EXPECT_CALL(*cdm, + ReleaseUsageInfo(ElementsAreArray(messageRaw, kMessageSize), _)) .Times(1); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -1291,12 +1268,12 @@ TEST_F(WVDrmPluginTest, ReturnsExpectedPropertyValues) { testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_DEVICE_ID, _)) - .WillOnce(DoAll(SetArgPointee<2>(kDeviceId), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce( + DoAll(SetArgPointee<2>(kDeviceId), testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_SYSTEM_ID, _)) - .WillOnce(DoAll(SetArgPointee<2>(systemId), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce( + DoAll(SetArgPointee<2>(systemId), testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_PROVISIONING_ID, _)) .WillOnce(DoAll(SetArgPointee<2>(provisioningId), @@ -1315,8 +1292,8 @@ TEST_F(WVDrmPluginTest, ReturnsExpectedPropertyValues) { testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_SRM_UPDATE_SUPPORT, _)) - .WillOnce(DoAll(SetArgPointee<2>("True"), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce( + DoAll(SetArgPointee<2>("True"), testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_CURRENT_SRM_VERSION, _)) .WillOnce(DoAll(SetArgPointee<2>(currentSRMVersion), @@ -1331,8 +1308,7 @@ TEST_F(WVDrmPluginTest, ReturnsExpectedPropertyValues) { testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_DECRYPT_HASH_SUPPORT, _)) - .WillOnce(DoAll(SetArgPointee<2>("1"), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce(DoAll(SetArgPointee<2>("1"), testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_OEMCRYPTO_BUILD_INFORMATION, _)) .WillOnce(DoAll(SetArgPointee<2>(oemCryptoBuildInformation), @@ -1350,134 +1326,129 @@ TEST_F(WVDrmPluginTest, ReturnsExpectedPropertyValues) { std::string stringResult; std::vector vectorResult; - plugin.getPropertyString( - hidl_string("vendor"), [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ("Google", stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("vendor"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ("Google", stringResult.c_str()); + }); plugin.getPropertyString( hidl_string("version"), [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(cdmVersion.c_str(), stringResult.c_str()); - }); + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(cdmVersion.c_str(), stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("description"), [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ("Widevine CDM", stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("description"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ("Widevine CDM", stringResult.c_str()); + }); plugin.getPropertyString( hidl_string("algorithms"), [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ("AES/CBC/NoPadding,HmacSHA256", stringResult.c_str()); - }); + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ("AES/CBC/NoPadding,HmacSHA256", stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("securityLevel"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(QUERY_VALUE_SECURITY_LEVEL_L1.c_str(), stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("securityLevel"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(QUERY_VALUE_SECURITY_LEVEL_L1.c_str(), + stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("securityLevel"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(QUERY_VALUE_SECURITY_LEVEL_L3.c_str(), stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("securityLevel"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(QUERY_VALUE_SECURITY_LEVEL_L3.c_str(), + stringResult.c_str()); + }); plugin.getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - std::vector id(vectorResult); - EXPECT_THAT(id, ElementsAreArray(kDeviceId.data(), kDeviceId.size())); - }); + ASSERT_EQ(Status::OK, status); + std::vector id(vectorResult); + EXPECT_THAT(id, ElementsAreArray(kDeviceId.data(), kDeviceId.size())); + }); plugin.getPropertyString( - hidl_string("systemId"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(systemId.c_str(), stringResult.c_str()); - }); + hidl_string("systemId"), [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(systemId.c_str(), stringResult.c_str()); + }); plugin.getPropertyByteArray( hidl_string("provisioningUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - std::vector id(vectorResult); - EXPECT_THAT(id, ElementsAreArray(provisioningId.data(), - provisioningId.size())); - }); + ASSERT_EQ(Status::OK, status); + std::vector id(vectorResult); + EXPECT_THAT( + id, ElementsAreArray(provisioningId.data(), provisioningId.size())); + }); - plugin.getPropertyString( - hidl_string("numberOfOpenSessions"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_EQ(openSessions, stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("numberOfOpenSessions"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_EQ(openSessions, stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("maxNumberOfSessions"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_EQ(maxSessions, stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("maxNumberOfSessions"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_EQ(maxSessions, stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("oemCryptoApiVersion"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(oemCryptoApiVersion.c_str(), stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("oemCryptoApiVersion"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(oemCryptoApiVersion.c_str(), + stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("SRMUpdateSupport"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ("True", stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("SRMUpdateSupport"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ("True", stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("CurrentSRMVersion"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(currentSRMVersion.c_str(), stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("CurrentSRMVersion"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(currentSRMVersion.c_str(), + stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("resourceRatingTier"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(resourceRatingTier.c_str(), stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("resourceRatingTier"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(resourceRatingTier.c_str(), + stringResult.c_str()); + }); - plugin.getPropertyString( - hidl_string("oemCryptoBuildInformation"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_STREQ(oemCryptoBuildInformation.c_str(), stringResult.c_str()); - }); + plugin.getPropertyString(hidl_string("oemCryptoBuildInformation"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_STREQ(oemCryptoBuildInformation.c_str(), + stringResult.c_str()); + }); std::stringstream ss; ss << oemCryptoHashNotSupported << " " << oemCryptoCrcClearBuffer << " " - << oemCryptoPartnerDefinedHash; + << oemCryptoPartnerDefinedHash; std::string validResults = ss.str(); - plugin.getPropertyString( - hidl_string("decryptHashSupport"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_EQ(oemCryptoCrcClearBuffer, stringResult); - }); + plugin.getPropertyString(hidl_string("decryptHashSupport"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_EQ(oemCryptoCrcClearBuffer, stringResult); + }); - plugin.getPropertyString( - hidl_string("decryptHashError"), - [&](Status status, hidl_string stringResult) { - ASSERT_EQ(Status::OK, status); - EXPECT_EQ(decryptHashErrorBadHashAndFrameNumber, stringResult); - }); + plugin.getPropertyString(hidl_string("decryptHashError"), + [&](Status status, hidl_string stringResult) { + ASSERT_EQ(Status::OK, status); + EXPECT_EQ(decryptHashErrorBadHashAndFrameNumber, + stringResult); + }); // This call occurs before any open session or other call. This means // that the cdm identifer is not yet sealed, and metrics return empty @@ -1485,31 +1456,29 @@ TEST_F(WVDrmPluginTest, ReturnsExpectedPropertyValues) { plugin.getPropertyByteArray( hidl_string("metrics"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - std::vector id(vectorResult); - const char empty[] = {}; - EXPECT_THAT(id, ElementsAreArray(empty, sizeof(empty))); - }); + ASSERT_EQ(Status::OK, status); + std::vector id(vectorResult); + const char empty[] = {}; + EXPECT_THAT(id, ElementsAreArray(empty, sizeof(empty))); + }); // Set expectations for the OpenSession call and a CloseSession call. - EXPECT_CALL(*cdm, - OpenSession(StrEq("com.widevine"), _, HasOrigin(EMPTY_ORIGIN), _, _)) - .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), - testing::Return(wvcdm::NO_ERROR))); + EXPECT_CALL(*cdm, OpenSession(StrEq("com.widevine"), _, + HasOrigin(EMPTY_ORIGIN), _, _)) + .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), + testing::Return(wvcdm::NO_ERROR))); // Provide expected behavior when plugin requests session control info EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); // This call causes the cdm identifier to become sealed. std::vector sessionId; plugin.openSession([&](Status status, hidl_vec hSessionId) { - ASSERT_EQ(Status::OK, status); - sessionId.clear(); - sessionId.assign(hSessionId.data(), - hSessionId.data() + hSessionId.size()); + ASSERT_EQ(Status::OK, status); + sessionId.clear(); + sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); // This call occurs after open session. The CDM identifer should be sealed. @@ -1517,11 +1486,11 @@ TEST_F(WVDrmPluginTest, ReturnsExpectedPropertyValues) { plugin.getPropertyByteArray( hidl_string("metrics"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - std::vector id(vectorResult); - EXPECT_THAT(id, ElementsAreArray(serialized_metrics.data(), - serialized_metrics.size())); - }); + ASSERT_EQ(Status::OK, status); + std::vector id(vectorResult); + EXPECT_THAT(id, ElementsAreArray(serialized_metrics.data(), + serialized_metrics.size())); + }); ASSERT_EQ(Status::OK, plugin.closeSession(toHidlVec(sessionId))); } @@ -1535,19 +1504,18 @@ TEST_F(WVDrmPluginTest, DoesNotGetUnknownProperties) { std::string stringResult; std::vector vectorResult; - plugin.getPropertyString( - hidl_string("unknownProperty"), - [&](Status status, hidl_string stringResult) { - ASSERT_NE(Status::OK, status); - EXPECT_TRUE(stringResult.empty()); - }); + plugin.getPropertyString(hidl_string("unknownProperty"), + [&](Status status, hidl_string stringResult) { + ASSERT_NE(Status::OK, status); + EXPECT_TRUE(stringResult.empty()); + }); plugin.getPropertyByteArray( hidl_string("unknownProperty"), [&](Status status, hidl_vec vectorResult) { - ASSERT_NE(Status::OK, status); - EXPECT_EQ(0u, vectorResult.size()); - }); + ASSERT_NE(Status::OK, status); + EXPECT_EQ(0u, vectorResult.size()); + }); } TEST_F(WVDrmPluginTest, DoesNotSetUnknownProperties) { @@ -1578,21 +1546,21 @@ TEST_F(WVDrmPluginTest, CompliesWithSpoidVariability) { StrictMock crypto; const std::string kDeviceIds[] = { - kDeviceId, - kDeviceId + " the Second", + kDeviceId, + kDeviceId + " the Second", }; const size_t kDeviceCount = N_ELEM(kDeviceIds); const std::string kAppNames[] = { - std::string("com.google.widevine"), - std::string("com.youtube"), + std::string("com.google.widevine"), + std::string("com.youtube"), }; const size_t kAppCount = N_ELEM(kAppNames); const std::string kOrigins[] = { - kOrigin, - kOrigin + " but not that one, the other one.", - std::string(/* Intentionally Empty */), + kOrigin, + kOrigin + " but not that one, the other one.", + std::string(/* Intentionally Empty */), }; const size_t kOriginCount = N_ELEM(kOrigins); @@ -1602,8 +1570,8 @@ TEST_F(WVDrmPluginTest, CompliesWithSpoidVariability) { // We will get kPluginCount SPOIDs for every app package name + device id + // origin combination. - std::vector - spoids[kDeviceCount][kAppCount][kOriginCount][kPluginCount]; + std::vector spoids[kDeviceCount][kAppCount][kOriginCount] + [kPluginCount]; for (size_t deviceIndex = 0; deviceIndex < kDeviceCount; ++deviceIndex) { const std::string& deviceId = kDeviceIds[deviceIndex]; @@ -1621,8 +1589,7 @@ TEST_F(WVDrmPluginTest, CompliesWithSpoidVariability) { for (size_t originIndex = 0; originIndex < kOriginCount; ++originIndex) { const std::string& origin = kOrigins[originIndex]; - for (size_t pluginIndex = 0; - pluginIndex < kPluginCount; + for (size_t pluginIndex = 0; pluginIndex < kPluginCount; ++pluginIndex) { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, true); @@ -1635,10 +1602,10 @@ TEST_F(WVDrmPluginTest, CompliesWithSpoidVariability) { plugin.getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoids[deviceIndex][appIndex][originIndex][pluginIndex] = - vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoids[deviceIndex][appIndex][originIndex][pluginIndex] = + vectorResult; + }); } } } @@ -1649,27 +1616,23 @@ TEST_F(WVDrmPluginTest, CompliesWithSpoidVariability) { for (size_t deviceIndex = 0; deviceIndex < kDeviceCount; ++deviceIndex) { for (size_t appIndex = 0; appIndex < kAppCount; ++appIndex) { for (size_t originIndex = 0; originIndex < kOriginCount; ++originIndex) { - for (size_t pluginIndex = 0; - pluginIndex < kPluginCount; + for (size_t pluginIndex = 0; pluginIndex < kPluginCount; ++pluginIndex) { const std::vector& firstSpoid = spoids[deviceIndex][appIndex][originIndex][pluginIndex]; - for (size_t deviceIndex2 = 0; - deviceIndex2 < kDeviceCount; + for (size_t deviceIndex2 = 0; deviceIndex2 < kDeviceCount; ++deviceIndex2) { for (size_t appIndex2 = 0; appIndex2 < kAppCount; ++appIndex2) { - for (size_t originIndex2 = 0; - originIndex2 < kOriginCount; + for (size_t originIndex2 = 0; originIndex2 < kOriginCount; ++originIndex2) { - for (size_t pluginIndex2 = 0; - pluginIndex2 < kPluginCount; + for (size_t pluginIndex2 = 0; pluginIndex2 < kPluginCount; ++pluginIndex2) { const std::vector& secondSpoid = - spoids[deviceIndex2][appIndex2][originIndex2][pluginIndex2]; + spoids[deviceIndex2][appIndex2][originIndex2] + [pluginIndex2]; - if (deviceIndex == deviceIndex2 && - appIndex == appIndex2 && + if (deviceIndex == deviceIndex2 && appIndex == appIndex2 && originIndex == originIndex2) { EXPECT_EQ(firstSpoid, secondSpoid); } else { @@ -1711,8 +1674,7 @@ TEST_F(WVDrmPluginTest, ReturnsSameL1Spoid) { .Times(kSpoidQuery) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(kSpoidQuery); + EXPECT_CALL(*cdm, CloseSession(_)).Times(kSpoidQuery); // Open a session twice with the same security level, app package name and // origin and make sure the spoids returned are the same @@ -1731,9 +1693,9 @@ TEST_F(WVDrmPluginTest, ReturnsSameL1Spoid) { plugin.getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoid[i] = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoid[i] = vectorResult; + }); } EXPECT_EQ(spoid[0], spoid[1]); @@ -1769,8 +1731,7 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3ProvisionedUsingL3Spoid) { .Times(kSpoidQuery) .WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(kSpoidQuery); + EXPECT_CALL(*cdm, CloseSession(_)).Times(kSpoidQuery); // The device is provisioned at L3 security level. Open a session twice // and make sure that the spoids returned are the same when the @@ -1784,7 +1745,6 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3ProvisionedUsingL3Spoid) { hidl_string("L3")); ASSERT_EQ(Status::OK, status); - plugin.openSession([&](Status status, hidl_vec hSessionId) { ASSERT_EQ(Status::OK, status); sessionId.clear(); @@ -1797,9 +1757,9 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3ProvisionedUsingL3Spoid) { plugin.getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoid[i] = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoid[i] = vectorResult; + }); } EXPECT_EQ(spoid[0], spoid[1]); @@ -1843,16 +1803,15 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3Unprovisioned) { EXPECT_CALL(*cdm, IsProvisioned(wvcdm::kSecurityLevelL1, _, _, _)) .WillOnce(testing::Return(false)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(1); + EXPECT_CALL(*cdm, CloseSession(_)).Times(1); // This device is unprovisioned at the L3 security level. An attempt to // open a session results in an ERROR_DRM_NOT_PROVISIONED error. // Spoids are computed using device Unique IDs at each security level. // Since provisioning has not occurred for either spoid, the spoid // using the L3 device ID is used. - android::sp plugin = new WVDrmPlugin(cdm.get(), kAppPackageName, - &crypto, true); + android::sp plugin = + new WVDrmPlugin(cdm.get(), kAppPackageName, &crypto, true); // Force L3 Status status = plugin->setPropertyString(hidl_string("securityLevel"), @@ -1866,9 +1825,9 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3Unprovisioned) { plugin->getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoid[0] = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoid[0] = vectorResult; + }); // Try to open a session again. If provisioning took place, this time the // attempt will be successful. Retrieve the spoid. This time only @@ -1884,8 +1843,7 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3Unprovisioned) { plugin->openSession([&](Status status, hidl_vec hSessionId) { ASSERT_EQ(Status::OK, status); sessionId.clear(); - sessionId.assign(hSessionId.data(), - hSessionId.data() + hSessionId.size()); + sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); EXPECT_EQ(Status::OK, plugin->closeSession(toHidlVec(sessionId))); @@ -1893,9 +1851,9 @@ TEST_F(WVDrmPluginTest, ReturnsL3SpoidsWhenL3Unprovisioned) { plugin->getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoid[1] = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoid[1] = vectorResult; + }); EXPECT_EQ(spoid[0], spoid[1]); } @@ -1921,7 +1879,7 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { // Provide expected behavior to support session creation EXPECT_CALL(*cdm1, OpenSession(StrEq("com.widevine"), _, _, _, _)) .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), - testing::Return(wvcdm::NO_ERROR))) + testing::Return(wvcdm::NO_ERROR))) .WillOnce(testing::Return(wvcdm::NEED_PROVISIONING)); EXPECT_CALL(*cdm1, QueryOemCryptoSessionId(cdmSessionId, _)) @@ -1931,14 +1889,13 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { // Open a session at L1 security level. The spoid is now computed with // the L1 device unique ID - android::sp plugin = new WVDrmPlugin(cdm1.get(), kAppPackageName, - &crypto, true); + android::sp plugin = + new WVDrmPlugin(cdm1.get(), kAppPackageName, &crypto, true); plugin->openSession([&](Status status, hidl_vec hSessionId) { ASSERT_EQ(Status::OK, status); sessionId.clear(); - sessionId.assign(hSessionId.data(), - hSessionId.data() + hSessionId.size()); + sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); EXPECT_EQ(Status::OK, plugin->closeSession(toHidlVec(sessionId))); @@ -1946,9 +1903,9 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { plugin->getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoidL1 = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoidL1 = vectorResult; + }); // Force L3. This should not be allowed since the spoid has been // computed. We defer correcting this, as this might have an @@ -1956,7 +1913,7 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { // returns a ERROR_DRM_NOT_PROVISIONED error. No spoid computation takes // place. Status status = plugin->setPropertyString(hidl_string("securityLevel"), - hidl_string("L3")); + hidl_string("L3")); ASSERT_EQ(Status::OK, status); plugin->openSession([&](Status status, hidl_vec) { @@ -1966,9 +1923,9 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { plugin->getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoidL3[0] = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoidL3[0] = vectorResult; + }); // Set expectations for the second plugin instance android::sp> cdm2 = new StrictMock(); @@ -2012,8 +1969,7 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { plugin->openSession([&](Status status, hidl_vec hSessionId) { ASSERT_EQ(Status::OK, status); sessionId.clear(); - sessionId.assign(hSessionId.data(), - hSessionId.data() + hSessionId.size()); + sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); EXPECT_EQ(Status::OK, plugin->closeSession(toHidlVec(sessionId))); @@ -2021,9 +1977,9 @@ TEST_F(WVDrmPluginTest, ReturnsL1SpoidsWhenL3ProvisionedUsingL1Spoid) { plugin->getPropertyByteArray( hidl_string("deviceUniqueId"), [&](Status status, hidl_vec vectorResult) { - ASSERT_EQ(Status::OK, status); - spoidL3[1] = vectorResult; - }); + ASSERT_EQ(Status::OK, status); + spoidL3[1] = vectorResult; + }); EXPECT_EQ(spoidL3[0], spoidL3[1]); EXPECT_EQ(spoidL1, spoidL3[0]); @@ -2049,8 +2005,7 @@ TEST_F(WVDrmPluginTest, FailsGenericMethodsWithoutAnAlgorithmSet) { .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2064,25 +2019,27 @@ TEST_F(WVDrmPluginTest, FailsGenericMethodsWithoutAnAlgorithmSet) { // to fail. plugin.encrypt(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(input), - toHidlVec(iv), [&](Status status, hidl_vec /* output */) { - // NO_INIT is converted to Status::ERROR_DRM_UNKNOWN - EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); - }); + toHidlVec(iv), + [&](Status status, hidl_vec /* output */) { + // NO_INIT is converted to Status::ERROR_DRM_UNKNOWN + EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); + }); plugin.decrypt(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(input), - toHidlVec(iv), [&](Status status, hidl_vec /* output */) { - EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); - }); + toHidlVec(iv), + [&](Status status, hidl_vec /* output */) { + EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); + }); plugin.sign(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(input), [&](Status status, hidl_vec /* signature */) { - EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); - }); + EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); + }); plugin.verify(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(input), toHidlVec(output), [&](Status status, bool /* match */) { - EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); - }); + EXPECT_EQ(Status::ERROR_DRM_UNKNOWN, status); + }); } MATCHER_P(IsIV, iv, "") { @@ -2142,8 +2099,7 @@ TEST_F(WVDrmPluginTest, CallsGenericEncrypt) { .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2158,9 +2114,10 @@ TEST_F(WVDrmPluginTest, CallsGenericEncrypt) { ASSERT_EQ(Status::OK, status); plugin.encrypt(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(input), - toHidlVec(iv), [&](Status status, hidl_vec /* output */) { - ASSERT_EQ(Status::OK, status); - }); + toHidlVec(iv), + [&](Status status, hidl_vec /* output */) { + ASSERT_EQ(Status::OK, status); + }); } TEST_F(WVDrmPluginTest, CallsGenericDecrypt) { @@ -2210,8 +2167,7 @@ TEST_F(WVDrmPluginTest, CallsGenericDecrypt) { .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2226,9 +2182,10 @@ TEST_F(WVDrmPluginTest, CallsGenericDecrypt) { ASSERT_EQ(Status::OK, status); plugin.decrypt(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(input), - toHidlVec(iv), [&](Status status, hidl_vec /* output */) { - ASSERT_EQ(Status::OK, status); - }); + toHidlVec(iv), + [&](Status status, hidl_vec /* output */) { + ASSERT_EQ(Status::OK, status); + }); } TEST_F(WVDrmPluginTest, CallsGenericSign) { @@ -2258,14 +2215,14 @@ TEST_F(WVDrmPluginTest, CallsGenericSign) { .With(Args<1, 2>(ElementsAreArray(keyIdRaw, KEY_ID_SIZE))) .Times(1); - EXPECT_CALL(crypto, sign(4, _, kDataSize, OEMCrypto_HMAC_SHA256, _, - Pointee(0))) + EXPECT_CALL(crypto, + sign(4, _, kDataSize, OEMCrypto_HMAC_SHA256, _, Pointee(0))) .With(Args<1, 2>(ElementsAreArray(messageRaw, kDataSize))) .WillOnce(DoAll(SetArgPointee<5>(64), testing::Return(OEMCrypto_ERROR_SHORT_BUFFER))); - EXPECT_CALL(crypto, sign(4, _, kDataSize, OEMCrypto_HMAC_SHA256, _, - Pointee(64))) + EXPECT_CALL(crypto, + sign(4, _, kDataSize, OEMCrypto_HMAC_SHA256, _, Pointee(64))) .With(Args<1, 2>(ElementsAreArray(messageRaw, kDataSize))) .Times(1); } @@ -2280,8 +2237,7 @@ TEST_F(WVDrmPluginTest, CallsGenericSign) { .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2291,15 +2247,15 @@ TEST_F(WVDrmPluginTest, CallsGenericSign) { sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); - Status status = plugin.setMacAlgorithm(toHidlVec(sessionId), - hidl_string("HmacSHA256")); + Status status = + plugin.setMacAlgorithm(toHidlVec(sessionId), hidl_string("HmacSHA256")); ASSERT_EQ(Status::OK, status); plugin.sign(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(message), [&](Status status, hidl_vec signature) { - ASSERT_EQ(Status::OK, status); - ASSERT_NE(0u, signature.size()); - }); + ASSERT_EQ(Status::OK, status); + ASSERT_NE(0u, signature.size()); + }); } TEST_F(WVDrmPluginTest, CallsGenericVerify) { @@ -2360,8 +2316,7 @@ TEST_F(WVDrmPluginTest, CallsGenericVerify) { .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2371,21 +2326,21 @@ TEST_F(WVDrmPluginTest, CallsGenericVerify) { sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); - Status status = plugin.setMacAlgorithm(toHidlVec(sessionId), - hidl_string("HmacSHA256")); + Status status = + plugin.setMacAlgorithm(toHidlVec(sessionId), hidl_string("HmacSHA256")); ASSERT_EQ(Status::OK, status); plugin.verify(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(message), toHidlVec(signature), [&](Status status, bool match) { - ASSERT_EQ(Status::OK, status); - EXPECT_TRUE(match); - }); + ASSERT_EQ(Status::OK, status); + EXPECT_TRUE(match); + }); plugin.verify(toHidlVec(sessionId), toHidlVec(keyId), toHidlVec(message), toHidlVec(signature), [&](Status status, bool match) { - ASSERT_EQ(Status::OK, status); - EXPECT_FALSE(match); - }); + ASSERT_EQ(Status::OK, status); + EXPECT_FALSE(match); + }); } TEST_F(WVDrmPluginTest, RegistersForEvents) { @@ -2403,8 +2358,7 @@ TEST_F(WVDrmPluginTest, RegistersForEvents) { .Times(AtLeast(1)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); plugin.openSession([&](Status status, hidl_vec /* hSessionId */) { @@ -2439,8 +2393,7 @@ TEST_F(WVDrmPluginTest, UnregistersForAllEventsOnDestruction) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId2, _)) .WillOnce(Invoke(setSessionIdOnMap<5>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2461,7 +2414,7 @@ TEST_F(WVDrmPluginTest, DISABLED_MarshalsEvents) { StrictMock crypto; std::string appPackageName; - sp > listener = + sp> listener = new StrictMock(); const int64_t kExpiryTimeInSeconds = 123456789012LL; @@ -2491,9 +2444,8 @@ TEST_F(WVDrmPluginTest, DISABLED_MarshalsEvents) { EXPECT_CALL(*listener, sendKeysChange_1_2(hSessionId, hKeyStatusList, false)); - EXPECT_CALL( - *listener, - sendEvent(EventType::KEY_EXPIRED, hSessionId, hEmptyData)); + EXPECT_CALL(*listener, + sendEvent(EventType::KEY_EXPIRED, hSessionId, hEmptyData)); EXPECT_CALL(*listener, sendEvent(EventType::KEY_NEEDED, hSessionId, hEmptyData)); @@ -2522,7 +2474,8 @@ TEST_F(WVDrmPluginTest, DISABLED_MarshalsEvents) { keyStatusList.push_back(keyStatus); hidl_vec hKeyStatusList2 = toHidlVec(keyStatusList); - EXPECT_CALL(*listener, sendKeysChange_1_2(hSessionId, hKeyStatusList2, false)); + EXPECT_CALL(*listener, + sendKeysChange_1_2(hSessionId, hKeyStatusList2, false)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2550,7 +2503,7 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesProvisioningNeededEvent) { StrictMock crypto; std::string appPackageName; - sp > listener = + sp> listener = new StrictMock(); hidl_vec hEmptyData; @@ -2566,8 +2519,7 @@ TEST_F(WVDrmPluginTest, DISABLED_GeneratesProvisioningNeededEvent) { .WillRepeatedly(DoAll(SetArgPointee<4>(cdmSessionId), testing::Return(wvcdm::NEED_PROVISIONING))); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); plugin.setListener(listener); @@ -2597,8 +2549,7 @@ TEST_F(WVDrmPluginTest, ProvidesExpectedDefaultPropertiesToCdm) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2641,20 +2592,18 @@ TEST_F(WVDrmPluginTest, CanSetAppId) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); // Test setting an empty string - Status status = plugin.setPropertyString(hidl_string("appId"), - hidl_string("")); + Status status = + plugin.setPropertyString(hidl_string("appId"), hidl_string("")); ASSERT_EQ(Status::OK, status); // Test setting an application id before a session is opened. - status = plugin.setPropertyString(hidl_string("appId"), - hidl_string(kAppId)); + status = plugin.setPropertyString(hidl_string("appId"), hidl_string(kAppId)); ASSERT_EQ(Status::OK, status); plugin.openSession([&](Status status, hidl_vec /* hSessionId */) { @@ -2666,8 +2615,7 @@ TEST_F(WVDrmPluginTest, CanSetAppId) { EXPECT_STREQ(kAppId.c_str(), propertySet->app_id().c_str()); // Test setting application id while session is opened, this should fail. - status = plugin.setPropertyString(hidl_string("appId"), - hidl_string(kAppId)); + status = plugin.setPropertyString(hidl_string("appId"), hidl_string(kAppId)); ASSERT_EQ(Status::ERROR_DRM_UNKNOWN, status); } @@ -2685,8 +2633,7 @@ TEST_P(WVDrmPluginOriginTest, CanSetOrigin) { .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); // Provide expected behavior when plugin closes a session - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } // Note which mock calls we expect @@ -2698,24 +2645,23 @@ TEST_P(WVDrmPluginOriginTest, CanSetOrigin) { WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); if (!params.origin.empty()) { - ASSERT_EQ(Status::OK, - plugin.setPropertyString(hidl_string("origin"), - hidl_string(params.origin))); + ASSERT_EQ(Status::OK, plugin.setPropertyString(hidl_string("origin"), + hidl_string(params.origin))); } plugin.openSession([&](Status status, hidl_vec /* hSessionId */) { EXPECT_EQ(Status::OK, status); }); // Test setting an origin while sessions are opened. This should fail. - EXPECT_NE(Status::OK, - plugin.setPropertyString(hidl_string("origin"), - hidl_string(kOrigin))); + EXPECT_NE(Status::OK, plugin.setPropertyString(hidl_string("origin"), + hidl_string(kOrigin))); EXPECT_EQ(Status::OK, plugin.closeSession(toHidlVec(sessionId))); } -INSTANTIATE_TEST_CASE_P(OriginTests, WVDrmPluginOriginTest, Values( - OriginTestVariant("No Origin", kEmptyString, EMPTY_ORIGIN), - OriginTestVariant("With an Origin", kOrigin, kOrigin.c_str()))); +INSTANTIATE_TEST_CASE_P( + OriginTests, WVDrmPluginOriginTest, + Values(OriginTestVariant("No Origin", kEmptyString, EMPTY_ORIGIN), + OriginTestVariant("With an Origin", kOrigin, kOrigin.c_str()))); TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { android::sp> cdm = new StrictMock(); @@ -2743,15 +2689,14 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); // Test forcing L3 - Status status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L3")); + Status status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L3")); ASSERT_EQ(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -2765,8 +2710,8 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { ASSERT_EQ(Status::OK, status); // Test returning to L1 on an L3 device (Should Fail) - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L1")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); ASSERT_NE(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -2780,8 +2725,8 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { ASSERT_EQ(Status::OK, status); // Test returning to L1 on an L1 device - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L1")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); ASSERT_EQ(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -2795,8 +2740,8 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { ASSERT_EQ(Status::OK, status); // Test un-forcing a level (first forcing to L3 so we have something to reset) - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L3")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L3")); ASSERT_EQ(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -2809,8 +2754,8 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { status = plugin.closeSession(toHidlVec(sessionId)); ASSERT_EQ(Status::OK, status); - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("")); ASSERT_EQ(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -2825,7 +2770,7 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { // Test nonsense (Should Fail) status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("nonsense")); + hidl_string("nonsense")); ASSERT_NE(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -2842,8 +2787,8 @@ TEST_F(WVDrmPluginTest, CanSetSecurityLevel) { plugin.openSession([&](Status status, hidl_vec /* hSessionId */) { ASSERT_EQ(Status::OK, status); }); - status = plugin.setPropertyString(hidl_string("securityLevel"), - hidl_string("L3")); + status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L3")); ASSERT_NE(Status::OK, status); } @@ -2867,8 +2812,7 @@ TEST_F(WVDrmPluginTest, CanSetPrivacyMode) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -2931,8 +2875,7 @@ TEST_F(WVDrmPluginTest, CanSetServiceCertificate) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } // Validate that the certificate is validated. Accept it once and reject it @@ -2991,8 +2934,7 @@ TEST_F(WVDrmPluginTest, CanSetSessionSharing) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -3014,7 +2956,7 @@ TEST_F(WVDrmPluginTest, CanSetSessionSharing) { // Test turning off session sharing status = plugin.setPropertyString(hidl_string("sessionSharing"), - hidl_string("disable")); + hidl_string("disable")); ASSERT_EQ(Status::OK, status); plugin.openSession([&](Status status, hidl_vec hSessionId) { @@ -3029,7 +2971,7 @@ TEST_F(WVDrmPluginTest, CanSetSessionSharing) { // Test nonsense (Should Fail) status = plugin.setPropertyString(hidl_string("sessionSharing"), - hidl_string("nonsense")); + hidl_string("nonsense")); ASSERT_NE(Status::OK, status); // Test changing sharing with a session open (Should Fail) @@ -3039,7 +2981,7 @@ TEST_F(WVDrmPluginTest, CanSetSessionSharing) { sessionId.assign(hSessionId.data(), hSessionId.data() + hSessionId.size()); }); status = plugin.setPropertyString(hidl_string("sessionSharing"), - hidl_string("enable")); + hidl_string("enable")); ASSERT_NE(Status::OK, status); status = plugin.closeSession(toHidlVec(sessionId)); @@ -3071,8 +3013,7 @@ TEST_F(WVDrmPluginTest, AllowsStoringOfSessionSharingId) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -3102,25 +3043,21 @@ TEST_F(WVDrmPluginTest, CanSetAtscMode) { // Provide expected behavior in response to OpenSession and store the // property set EXPECT_CALL(*cdm, OpenSession(_, _, _, _, _)) + .WillOnce(DoAll( + SetArgPointee<4>(cdmSessionId), SaveArg<1>(&propertySet), + SaveArg<2>(&cdmIdAtscModeNotSet), testing::Return(wvcdm::NO_ERROR))) .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), - SaveArg<1>(&propertySet), - SaveArg<2>(&cdmIdAtscModeNotSet), - testing::Return(wvcdm::NO_ERROR))) - .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), - SaveArg<1>(&propertySet), - SaveArg<2>(&cdmIdAtscModeSet), - testing::Return(wvcdm::NO_ERROR))) - .WillOnce(DoAll(SetArgPointee<4>(cdmSessionId), - SaveArg<1>(&propertySet), - SaveArg<2>(&cdmIdAtscModeReset), - testing::Return(wvcdm::NO_ERROR))); + SaveArg<1>(&propertySet), SaveArg<2>(&cdmIdAtscModeSet), + testing::Return(wvcdm::NO_ERROR))) + .WillOnce(DoAll( + SetArgPointee<4>(cdmSessionId), SaveArg<1>(&propertySet), + SaveArg<2>(&cdmIdAtscModeReset), testing::Return(wvcdm::NO_ERROR))); // Provide expected behavior when plugin requests session control info EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin1(cdm.get(), appPackageName, &crypto, false); @@ -3140,8 +3077,8 @@ TEST_F(WVDrmPluginTest, CanSetAtscMode) { WVDrmPlugin plugin2(cdm.get(), appPackageName, &crypto, false); // Test turning on ATSC mode - status = plugin2.setPropertyString(hidl_string("atscMode"), - hidl_string("enable")); + status = + plugin2.setPropertyString(hidl_string("atscMode"), hidl_string("enable")); ASSERT_EQ(Status::OK, status); plugin2.openSession([&](Status status, hidl_vec hSessionId) { @@ -3154,13 +3091,12 @@ TEST_F(WVDrmPluginTest, CanSetAtscMode) { status = plugin2.closeSession(toHidlVec(sessionId)); ASSERT_EQ(Status::OK, status); - // Verify that ATSC mode can be enabled and disabled WVDrmPlugin plugin3(cdm.get(), appPackageName, &crypto, false); // Test turning on ATSC mode - status = plugin3.setPropertyString(hidl_string("atscMode"), - hidl_string("enable")); + status = + plugin3.setPropertyString(hidl_string("atscMode"), hidl_string("enable")); ASSERT_EQ(Status::OK, status); // Test turning off ATSC mode @@ -3180,8 +3116,8 @@ TEST_F(WVDrmPluginTest, CanSetAtscMode) { // Test turning on and off ATSC mode. They should be rejected since the SPOID // has been calculated - status = plugin3.setPropertyString(hidl_string("atscMode"), - hidl_string("enable")); + status = + plugin3.setPropertyString(hidl_string("atscMode"), hidl_string("enable")); ASSERT_NE(Status::OK, status); status = plugin3.setPropertyString(hidl_string("atscMode"), @@ -3206,8 +3142,7 @@ TEST_F(WVDrmPluginTest, CanSetDecryptHashProperties) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -3256,8 +3191,7 @@ TEST_F(WVDrmPluginTest, DoesNotSetDecryptHashProperties) { EXPECT_CALL(*cdm, QueryOemCryptoSessionId(cdmSessionId, _)) .WillRepeatedly(Invoke(setSessionIdOnMap<4>)); - EXPECT_CALL(*cdm, CloseSession(_)) - .Times(AtLeast(0)); + EXPECT_CALL(*cdm, CloseSession(_)).Times(AtLeast(0)); } WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); @@ -3278,14 +3212,14 @@ TEST_F(WVDrmPluginTest, DoesNotSetDecryptHashProperties) { value.append(frameNumber.c_str()); // Tests for missing token handling - Status status = plugin.setPropertyString(hidl_string("decryptHash"), - hidl_string(value)); + Status status = + plugin.setPropertyString(hidl_string("decryptHash"), hidl_string(value)); EXPECT_NE(Status::OK, status); // Tests for empty token value.append(","); - status = plugin.setPropertyString(hidl_string("decryptHash"), - hidl_string(value)); + status = + plugin.setPropertyString(hidl_string("decryptHash"), hidl_string(value)); EXPECT_NE(Status::OK, status); // Tests for invalid sessionId @@ -3293,8 +3227,8 @@ TEST_F(WVDrmPluginTest, DoesNotSetDecryptHashProperties) { value.append("bad session id"); value.append(",1"); value.append(hash.c_str()); - status = plugin.setPropertyString(hidl_string("decryptHash"), - hidl_string(value)); + status = + plugin.setPropertyString(hidl_string("decryptHash"), hidl_string(value)); EXPECT_NE(Status::OK, status); // Tests for malformed Base64encode hash, with a "," @@ -3325,41 +3259,40 @@ TEST_F(WVDrmPluginTest, GetOfflineLicenseIds) { std::vector mockIdsL1; for (uint32_t i = 0; i < kLicenseCount; ++i) { - mockIdsL1.push_back(std::string(mockIdsRaw[i], - mockIdsRaw[i] + kKeySetIdSize)); + mockIdsL1.push_back( + std::string(mockIdsRaw[i], mockIdsRaw[i] + kKeySetIdSize)); } std::vector mockIdsL3; for (uint32_t i = 0; i < kLicenseCount; ++i) { - mockIdsL3.push_back(std::string(mockIdsRaw[i+5], - mockIdsRaw[i+5] + kKeySetIdSize)); + mockIdsL3.push_back( + std::string(mockIdsRaw[i + 5], mockIdsRaw[i + 5] + kKeySetIdSize)); } EXPECT_CALL(*cdm, ListStoredLicenses(kSecurityLevelL1, HasOrigin(EMPTY_ORIGIN), _)) - .WillOnce(DoAll(SetArgPointee<2>(mockIdsL1), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce( + DoAll(SetArgPointee<2>(mockIdsL1), testing::Return(wvcdm::NO_ERROR))); EXPECT_CALL(*cdm, ListStoredLicenses(kSecurityLevelL3, HasOrigin(EMPTY_ORIGIN), _)) - .WillOnce(DoAll(SetArgPointee<2>(mockIdsL3), - testing::Return(wvcdm::NO_ERROR))); + .WillOnce( + DoAll(SetArgPointee<2>(mockIdsL3), testing::Return(wvcdm::NO_ERROR))); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - std::vector > offlineIds; + std::vector> offlineIds; offlineIds.clear(); plugin.getOfflineLicenseKeySetIds( [&](Status status, hidl_vec hKeySetIds) { - ASSERT_EQ(Status::OK, status); + ASSERT_EQ(Status::OK, status); - std::vector ids(hKeySetIds); - - for (auto id : ids) { - offlineIds.push_back(id); - } - }); + std::vector ids(hKeySetIds); + for (auto id : ids) { + offlineIds.push_back(id); + } + }); size_t index = 0; for (auto id : offlineIds) { @@ -3375,11 +3308,10 @@ TEST_F(WVDrmPluginTest, GetOfflineLicenseState) { EXPECT_CALL(*cdm, QueryStatus(_, QUERY_KEY_SECURITY_LEVEL, _)) .WillRepeatedly(DoAll(SetArgPointee<2>(QUERY_VALUE_SECURITY_LEVEL_L1), - testing::Return(wvcdm::NO_ERROR))); + testing::Return(wvcdm::NO_ERROR))); - EXPECT_CALL(*cdm, - GetOfflineLicenseState(_, kSecurityLevelL1, - HasOrigin(EMPTY_ORIGIN), _)) + EXPECT_CALL(*cdm, GetOfflineLicenseState(_, kSecurityLevelL1, + HasOrigin(EMPTY_ORIGIN), _)) .WillOnce(DoAll(SetArgPointee<3>(wvcdm::kLicenseStateActive), testing::Return(wvcdm::NO_ERROR))) .WillOnce(DoAll(SetArgPointee<3>(wvcdm::kLicenseStateReleasing), @@ -3388,27 +3320,30 @@ TEST_F(WVDrmPluginTest, GetOfflineLicenseState) { testing::Return(wvcdm::NO_ERROR))); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); - Status status = plugin.setPropertyString( - hidl_string("securityLevel"), hidl_string("L1")); + Status status = + plugin.setPropertyString(hidl_string("securityLevel"), hidl_string("L1")); ASSERT_EQ(Status::OK, status); - plugin.getOfflineLicenseState(toHidlVec(keySetId), + plugin.getOfflineLicenseState( + toHidlVec(keySetId), [&](Status status, OfflineLicenseState hLicenseState) { - ASSERT_EQ(Status::OK, status); - ASSERT_EQ(OfflineLicenseState::USABLE, hLicenseState); - }); + ASSERT_EQ(Status::OK, status); + ASSERT_EQ(OfflineLicenseState::USABLE, hLicenseState); + }); - plugin.getOfflineLicenseState(toHidlVec(keySetId), + plugin.getOfflineLicenseState( + toHidlVec(keySetId), [&](Status status, OfflineLicenseState hLicenseState) { - ASSERT_EQ(Status::OK, status); - ASSERT_EQ(OfflineLicenseState::INACTIVE, hLicenseState); - }); + ASSERT_EQ(Status::OK, status); + ASSERT_EQ(OfflineLicenseState::INACTIVE, hLicenseState); + }); - plugin.getOfflineLicenseState(toHidlVec(keySetId), + plugin.getOfflineLicenseState( + toHidlVec(keySetId), [&](Status status, OfflineLicenseState hLicenseState) { - ASSERT_EQ(Status::OK, status); - ASSERT_EQ(OfflineLicenseState::UNKNOWN, hLicenseState); - }); + ASSERT_EQ(Status::OK, status); + ASSERT_EQ(OfflineLicenseState::UNKNOWN, hLicenseState); + }); } TEST_F(WVDrmPluginTest, RemoveOfflineLicense) { @@ -3416,9 +3351,8 @@ TEST_F(WVDrmPluginTest, RemoveOfflineLicense) { StrictMock crypto; std::string appPackageName; - EXPECT_CALL(*cdm, - RemoveOfflineLicense(_, kSecurityLevelL1, - HasOrigin(EMPTY_ORIGIN))) + EXPECT_CALL( + *cdm, RemoveOfflineLicense(_, kSecurityLevelL1, HasOrigin(EMPTY_ORIGIN))) .Times(1); WVDrmPlugin plugin(cdm.get(), appPackageName, &crypto, false); diff --git a/libwvdrmengine/oemcrypto/include/OEMCryptoCENCCommon.h b/libwvdrmengine/oemcrypto/include/OEMCryptoCENCCommon.h index dd929640..cc0c0720 120000 --- a/libwvdrmengine/oemcrypto/include/OEMCryptoCENCCommon.h +++ b/libwvdrmengine/oemcrypto/include/OEMCryptoCENCCommon.h @@ -1 +1 @@ -../../oemcrypto/odk/include/OEMCryptoCENCCommon.h \ No newline at end of file +../odk/include/OEMCryptoCENCCommon.h \ No newline at end of file diff --git a/libwvdrmengine/oemcrypto/test/common.mk b/libwvdrmengine/oemcrypto/test/common.mk index 698a7d77..4e98dbdb 100644 --- a/libwvdrmengine/oemcrypto/test/common.mk +++ b/libwvdrmengine/oemcrypto/test/common.mk @@ -34,12 +34,11 @@ LOCAL_C_INCLUDES += \ LOCAL_STATIC_LIBRARIES := \ libcdm \ - libcdm_utils \ libgtest \ libgtest_main \ libwvlevel3 \ libcdm_protos \ - libcdm_utils \ + libcdm_utils_hidl \ libwv_kdo \ libwv_odk \ diff --git a/libwvdrmengine/src_hidl/WVDrmFactory.cpp b/libwvdrmengine/src_hidl/WVDrmFactory.cpp index 52ff40f1..1b549a4d 100644 --- a/libwvdrmengine/src_hidl/WVDrmFactory.cpp +++ b/libwvdrmengine/src_hidl/WVDrmFactory.cpp @@ -220,8 +220,8 @@ void WVDrmFactory::printCdmProperties(FILE* out) { std::string value; for (const auto& property : cdmProperties) { - cdm->QueryStatus(wvcdm::SecurityLevel::kLevelDefault, property.second, - &value); + cdm->QueryStatus(wvcdm::RequestedSecurityLevel::kLevelDefault, + property.second, &value); std::string outString = stringToHex(value); fprintf(out, "%s [%s]\n", property.first.c_str(), outString.c_str()); value.clear(); diff --git a/libwvdrmengine/vts/vendor_module/Android.bp b/libwvdrmengine/vts/vendor_module/Android.bp index a6d26004..c14e1f09 100644 --- a/libwvdrmengine/vts/vendor_module/Android.bp +++ b/libwvdrmengine/vts/vendor_module/Android.bp @@ -57,8 +57,8 @@ cc_library_shared { shared_libs: [ "libbase", + "libbinder", "libcrypto", - "libhidlbase", "liblog", "libssl", "libutils",