Reformat wv core/src files

[ Merge of http://go/wvgerrit/80484 ]

Clang-format has been run on files in core/src. clang-format has been turned
off for some blocks but otherwise no other changes have been made.

Bug: 134365840
Test: WV unit/integration tests
Change-Id: I6e509f25136f84d37de3d920084302f0f2c23dc4
This commit is contained in:
Rahul Frias
2019-06-03 17:14:18 -07:00
parent 47c2068d6a
commit a178eed57d
20 changed files with 713 additions and 760 deletions

View File

@@ -11,14 +11,16 @@ namespace wvcdm {
bool BufferReader::Read1(uint8_t* v) {
if (v == NULL) {
LOGE("BufferReader::Read1 : Failure during parse: Null output parameter "
"when expecting non-null");
LOGE(
"BufferReader::Read1 : Failure during parse: Null output parameter "
"when expecting non-null");
return false;
}
if (!HasBytes(1)) {
LOGV("BufferReader::Read1 : Failure while parsing: "
"Not enough bytes (1)");
LOGV(
"BufferReader::Read1 : Failure while parsing: "
"Not enough bytes (1)");
return false;
}
@@ -30,14 +32,18 @@ bool BufferReader::Read1(uint8_t* v) {
template <typename T>
bool BufferReader::Read(T* v) {
if (v == NULL) {
LOGE("BufferReader::Read<T> : Failure during parse: Null output parameter "
"when expecting non-null (%s)", __PRETTY_FUNCTION__);
LOGE(
"BufferReader::Read<T> : Failure during parse: Null output parameter "
"when expecting non-null (%s)",
__PRETTY_FUNCTION__);
return false;
}
if (!HasBytes(sizeof(T))) {
LOGV("BufferReader::Read<T> : Failure during parse: "
"Not enough bytes (%u)", sizeof(T));
LOGV(
"BufferReader::Read<T> : Failure during parse: "
"Not enough bytes (%u)",
sizeof(T));
return false;
}
@@ -59,14 +65,17 @@ bool BufferReader::Read8s(int64_t* v) { return Read(v); }
bool BufferReader::ReadString(std::string* str, size_t count) {
if (str == NULL) {
LOGE("BufferReader::ReadString : Failure during parse: Null output "
"parameter when expecting non-null");
LOGE(
"BufferReader::ReadString : Failure during parse: Null output "
"parameter when expecting non-null");
return false;
}
if (!HasBytes(count)) {
LOGV("BufferReader::ReadString : Parse Failure: "
"Not enough bytes (%d)", count);
LOGV(
"BufferReader::ReadString : Parse Failure: "
"Not enough bytes (%d)",
count);
return false;
}
@@ -77,14 +86,17 @@ bool BufferReader::ReadString(std::string* str, size_t count) {
bool BufferReader::ReadVec(std::vector<uint8_t>* vec, size_t count) {
if (vec == NULL) {
LOGE("BufferReader::ReadVec : Failure during parse: Null output parameter "
"when expecting non-null");
LOGE(
"BufferReader::ReadVec : Failure during parse: Null output parameter "
"when expecting non-null");
return false;
}
if (!HasBytes(count)) {
LOGV("BufferReader::ReadVec : Parse Failure: "
"Not enough bytes (%d)", count);
LOGV(
"BufferReader::ReadVec : Parse Failure: "
"Not enough bytes (%d)",
count);
return false;
}
@@ -96,8 +108,10 @@ bool BufferReader::ReadVec(std::vector<uint8_t>* vec, size_t count) {
bool BufferReader::SkipBytes(size_t bytes) {
if (!HasBytes(bytes)) {
LOGV("BufferReader::SkipBytes : Parse Failure: "
"Not enough bytes (%d)", bytes);
LOGV(
"BufferReader::SkipBytes : Parse Failure: "
"Not enough bytes (%d)",
bytes);
return false;
}
@@ -107,8 +121,9 @@ bool BufferReader::SkipBytes(size_t bytes) {
bool BufferReader::Read4Into8(uint64_t* v) {
if (v == NULL) {
LOGE("BufferReader::Read4Into8 : Failure during parse: Null output "
"parameter when expecting non-null");
LOGE(
"BufferReader::Read4Into8 : Failure during parse: Null output "
"parameter when expecting non-null");
return false;
}
@@ -122,8 +137,9 @@ bool BufferReader::Read4Into8(uint64_t* v) {
bool BufferReader::Read4sInto8s(int64_t* v) {
if (v == NULL) {
LOGE("BufferReader::Read4sInto8s : Failure during parse: Null output "
"parameter when expecting non-null");
LOGE(
"BufferReader::Read4sInto8s : Failure during parse: Null output "
"parameter when expecting non-null");
return false;
}

View File

@@ -24,7 +24,7 @@
#include "wv_cdm_event_listener.h"
namespace {
const uint64_t kReleaseSessionTimeToLive = 60; // seconds
const uint64_t kReleaseSessionTimeToLive = 60; // seconds
const uint32_t kUpdateUsageInformationPeriod = 60; // seconds
const size_t kUsageReportsPerRequest = 1;
@@ -96,23 +96,27 @@ CdmEngine::~CdmEngine() {
session_map_.Terminate();
}
CdmResponseType CdmEngine::OpenSession(
const CdmKeySystem& key_system, CdmClientPropertySet* property_set,
const CdmSessionId& forced_session_id, WvCdmEventListener* event_listener) {
CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system,
CdmClientPropertySet* property_set,
const CdmSessionId& forced_session_id,
WvCdmEventListener* event_listener) {
return OpenSession(key_system, property_set, event_listener,
&forced_session_id, NULL);
}
CdmResponseType CdmEngine::OpenSession(
const CdmKeySystem& key_system, CdmClientPropertySet* property_set,
WvCdmEventListener* event_listener, CdmSessionId* session_id) {
return OpenSession(key_system, property_set, event_listener, NULL, session_id);
CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system,
CdmClientPropertySet* property_set,
WvCdmEventListener* event_listener,
CdmSessionId* session_id) {
return OpenSession(key_system, property_set, event_listener, NULL,
session_id);
}
CdmResponseType CdmEngine::OpenSession(
const CdmKeySystem& key_system, CdmClientPropertySet* property_set,
WvCdmEventListener* event_listener, const CdmSessionId* forced_session_id,
CdmSessionId* session_id) {
CdmResponseType CdmEngine::OpenSession(const CdmKeySystem& key_system,
CdmClientPropertySet* property_set,
WvCdmEventListener* event_listener,
const CdmSessionId* forced_session_id,
CdmSessionId* session_id) {
LOGI("CdmEngine::OpenSession");
if (!ValidateKeySystem(key_system)) {
@@ -135,15 +139,14 @@ CdmResponseType CdmEngine::OpenSession(
std::unique_ptr<CdmSession> new_session(
new CdmSession(file_system_, metrics_->AddSession()));
CdmResponseType sts = new_session->Init(property_set, forced_session_id,
event_listener);
CdmResponseType sts =
new_session->Init(property_set, forced_session_id, event_listener);
if (sts != NO_ERROR) {
if (sts == NEED_PROVISIONING) {
cert_provisioning_requested_security_level_ =
new_session->GetRequestedSecurityLevel();
// Reserve a session ID so the CDM can return success.
if (session_id)
*session_id = new_session->GenerateSessionId();
if (session_id) *session_id = new_session->GenerateSessionId();
} else {
LOGE("CdmEngine::OpenSession: bad session init: %d", sts);
}
@@ -176,8 +179,7 @@ CdmResponseType CdmEngine::OpenKeySetSession(
key_set_in_use =
release_key_sets_.find(key_set_id) != release_key_sets_.end();
}
if (key_set_in_use)
CloseKeySetSession(key_set_id);
if (key_set_in_use) CloseKeySetSession(key_set_id);
CdmSessionId session_id;
CdmResponseType sts = OpenSession(KEY_SYSTEM, property_set, event_listener,
@@ -186,8 +188,8 @@ CdmResponseType CdmEngine::OpenKeySetSession(
if (sts != NO_ERROR) return sts;
std::unique_lock<std::mutex> lock(release_key_sets_lock_);
release_key_sets_[key_set_id] = std::make_pair(session_id,
clock_.GetCurrentTime() + kReleaseSessionTimeToLive);
release_key_sets_[key_set_id] = std::make_pair(
session_id, clock_.GetCurrentTime() + kReleaseSessionTimeToLive);
return NO_ERROR;
}
@@ -283,16 +285,17 @@ CdmResponseType CdmEngine::GenerateKeyRequest(
key_request->message.clear();
if (license_type == kLicenseTypeRelease &&
!session->license_received()) {
if (license_type == kLicenseTypeRelease && !session->license_received()) {
int error_detail = NO_ERROR;
sts = session->RestoreOfflineSession(key_set_id, kLicenseTypeRelease,
&error_detail);
session->GetMetrics()->cdm_session_restore_offline_session_.Increment(
sts, error_detail);
if (sts != KEY_ADDED) {
LOGE("CdmEngine::GenerateKeyRequest: key release restoration failed,"
"sts = %d", static_cast<int>(sts));
LOGE(
"CdmEngine::GenerateKeyRequest: key release restoration failed,"
"sts = %d",
static_cast<int>(sts));
return sts;
}
}
@@ -307,8 +310,10 @@ CdmResponseType CdmEngine::GenerateKeyRequest(
cert_provisioning_requested_security_level_ =
session->GetRequestedSecurityLevel();
}
LOGE("CdmEngine::GenerateKeyRequest: key request generation failed, "
"sts = %d", static_cast<int>(sts));
LOGE(
"CdmEngine::GenerateKeyRequest: key request generation failed, "
"sts = %d",
static_cast<int>(sts));
return sts;
}
@@ -325,8 +330,8 @@ CdmResponseType CdmEngine::AddKey(const CdmSessionId& session_id,
CdmKeySetId* key_set_id) {
LOGI("CdmEngine::AddKey: %s", session_id.c_str());
if (license_type == nullptr) {
LOGE("CdmEngine::AddKey: license_type cannot be null.");
return PARAMETER_NULL;
LOGE("CdmEngine::AddKey: license_type cannot be null.");
return PARAMETER_NULL;
}
CdmSessionId id = session_id;
@@ -364,7 +369,6 @@ CdmResponseType CdmEngine::AddKey(const CdmSessionId& session_id,
return EMPTY_KEY_DATA_1;
}
CdmResponseType sts = (session->AddKey(key_data));
if (sts == KEY_ADDED) {
@@ -380,8 +384,8 @@ CdmResponseType CdmEngine::AddKey(const CdmSessionId& session_id,
}
if (key_set_id) {
if ((session->is_offline() ||
session->has_provider_session_token()) && !license_type_release) {
if ((session->is_offline() || session->has_provider_session_token()) &&
!license_type_release) {
*key_set_id = session->key_set_id();
LOGI("CdmEngine::AddKey: key set ID: %s", key_set_id->c_str());
} else {
@@ -508,12 +512,8 @@ CdmResponseType CdmEngine::RenewKey(const CdmSessionId& session_id,
}
CdmResponseType sts;
M_TIME(
sts = session->RenewKey(
key_data),
session->GetMetrics(),
cdm_session_renew_key_,
sts);
M_TIME(sts = session->RenewKey(key_data), session->GetMetrics(),
cdm_session_renew_key_, sts);
if (KEY_ADDED != sts) {
LOGE("CdmEngine::RenewKey: keys not added, sts=%d", static_cast<int>(sts));
@@ -571,24 +571,23 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level,
LOGW("CdmEngine::QueryStatus: GetHdcpCapabilities failed: %d", status);
return status;
}
*query_response =
MapHdcpVersion(query_token == QUERY_KEY_CURRENT_HDCP_LEVEL ?
current_hdcp : max_hdcp);
*query_response = MapHdcpVersion(
query_token == QUERY_KEY_CURRENT_HDCP_LEVEL ? current_hdcp : max_hdcp);
return NO_ERROR;
} else if (query_token == QUERY_KEY_USAGE_SUPPORT) {
bool supports_usage_reporting;
bool got_info = crypto_session->UsageInformationSupport(
security_level,
&supports_usage_reporting);
security_level, &supports_usage_reporting);
if (!got_info) {
LOGW("CdmEngine::QueryStatus: UsageInformationSupport failed");
metrics_->GetCryptoMetrics()->crypto_session_usage_information_support_
.SetError(got_info);
metrics_->GetCryptoMetrics()
->crypto_session_usage_information_support_.SetError(got_info);
return UNKNOWN_ERROR;
}
metrics_->GetCryptoMetrics()->crypto_session_usage_information_support_
.Record(supports_usage_reporting);
metrics_->GetCryptoMetrics()
->crypto_session_usage_information_support_.Record(
supports_usage_reporting);
*query_response =
supports_usage_reporting ? QUERY_VALUE_TRUE : QUERY_VALUE_FALSE;
@@ -607,9 +606,8 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level,
return NO_ERROR;
} else if (query_token == QUERY_KEY_MAX_NUMBER_OF_SESSIONS) {
size_t maximum_number_of_sessions = 0;
status =
crypto_session->GetMaxNumberOfSessions(security_level,
&maximum_number_of_sessions);
status = crypto_session->GetMaxNumberOfSessions(
security_level, &maximum_number_of_sessions);
if (status != NO_ERROR) {
LOGW("CdmEngine::QueryStatus: GetMaxNumberOfOpenSessions failed: %d",
@@ -671,18 +669,14 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level,
}
return NO_ERROR;
} else if (query_token == QUERY_KEY_DECRYPT_HASH_SUPPORT) {
*query_response = std::to_string(crypto_session->IsDecryptHashSupported(
security_level));
*query_response =
std::to_string(crypto_session->IsDecryptHashSupported(security_level));
return NO_ERROR;
}
M_TIME(
status = crypto_session->Open(
security_level),
metrics_->GetCryptoMetrics(),
crypto_session_open_,
status,
security_level);
M_TIME(status = crypto_session->Open(security_level),
metrics_->GetCryptoMetrics(), crypto_session_open_, status,
security_level);
if (status != NO_ERROR) return status;
@@ -690,8 +684,8 @@ CdmResponseType CdmEngine::QueryStatus(SecurityLevel security_level,
if (query_token == QUERY_KEY_DEVICE_ID) {
std::string deviceId;
status = crypto_session->GetExternalDeviceUniqueId(&deviceId);
metrics_->GetCryptoMetrics()->crypto_session_get_device_unique_id_
.Increment(status);
metrics_->GetCryptoMetrics()
->crypto_session_get_device_unique_id_.Increment(status);
if (status != NO_ERROR) return status;
*query_response = deviceId;
@@ -800,8 +794,8 @@ CdmResponseType CdmEngine::QueryKeyAllowedUsage(const std::string& key_id,
CdmSessionList sessions;
session_map_.GetSessionList(sessions);
for (CdmSessionList::iterator iter = sessions.begin();
iter != sessions.end(); ++iter) {
for (CdmSessionList::iterator iter = sessions.begin(); iter != sessions.end();
++iter) {
session_sts = (*iter)->QueryKeyAllowedUsage(key_id, &found_in_this_session);
if (session_sts == NO_ERROR) {
if (found) {
@@ -844,8 +838,8 @@ bool CdmEngine::IsSecurityLevelSupported(CdmSecurityLevel level) {
switch (level) {
case kSecurityLevelL1:
return
crypto_session->GetSecurityLevel(kLevelDefault) == kSecurityLevelL1;
return crypto_session->GetSecurityLevel(kLevelDefault) ==
kSecurityLevelL1;
case kSecurityLevelL3:
return crypto_session->GetSecurityLevel(kLevel3) == kSecurityLevelL3;
default:
@@ -917,8 +911,9 @@ CdmResponseType CdmEngine::HandleProvisioningResponse(
return INVALID_PROVISIONING_PARAMETERS_1;
}
if (wrapped_key == NULL) {
LOGE("CdmEngine::HandleProvisioningResponse: invalid wrapped key "
"destination");
LOGE(
"CdmEngine::HandleProvisioningResponse: invalid wrapped key "
"destination");
cert_provisioning_.reset(NULL);
return INVALID_PROVISIONING_PARAMETERS_2;
}
@@ -928,13 +923,10 @@ CdmResponseType CdmEngine::HandleProvisioningResponse(
std::unique_ptr<CryptoSession> crypto_session(
CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics()));
CdmResponseType status;
M_TIME(
status = crypto_session->Open(
cert_provisioning_requested_security_level_),
metrics_->GetCryptoMetrics(),
crypto_session_open_,
status,
cert_provisioning_requested_security_level_);
M_TIME(status = crypto_session->Open(
cert_provisioning_requested_security_level_),
metrics_->GetCryptoMetrics(), crypto_session_open_, status,
cert_provisioning_requested_security_level_);
if (NO_ERROR != status) {
LOGE(
"CdmEngine::HandleProvisioningResponse: provisioning object "
@@ -967,7 +959,7 @@ bool CdmEngine::IsProvisioned(CdmSecurityLevel security_level) {
// attempts to load it. If this fails, initialization will return an error.
UsagePropertySet property_set;
property_set.set_security_level(
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault);
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault);
CdmSession session(file_system_, metrics_->AddSession());
@@ -986,8 +978,8 @@ CdmResponseType CdmEngine::Unprovision(CdmSecurityLevel security_level) {
CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics()));
CdmClientTokenType token_type = kClientTokenUninitialized;
CdmResponseType res = crypto_session->GetProvisioningMethod(
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault,
&token_type);
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault,
&token_type);
if (res != NO_ERROR) {
return res;
} else if (token_type == kClientTokenDrmCert) {
@@ -1020,23 +1012,18 @@ CdmResponseType CdmEngine::DeleteUsageTable(CdmSecurityLevel security_level) {
std::unique_ptr<CryptoSession> crypto_session(
CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics()));
CdmResponseType status;
M_TIME(
status = crypto_session->Open(
security_level == kSecurityLevelL3 ?
kLevel3 :
kLevelDefault),
metrics_->GetCryptoMetrics(),
crypto_session_open_,
status,
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault);
M_TIME(status = crypto_session->Open(
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault),
metrics_->GetCryptoMetrics(), crypto_session_open_, status,
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault);
if (NO_ERROR != status) {
LOGE("CdmEngine::DeleteUsageTable: error opening crypto session: %d",
status);
status);
return UNPROVISION_ERROR_4;
}
status = crypto_session->DeleteAllUsageReports();
metrics_->GetCryptoMetrics()->crypto_session_delete_all_usage_reports_
.Increment(status);
metrics_->GetCryptoMetrics()
->crypto_session_delete_all_usage_reports_.Increment(status);
if (status != NO_ERROR) {
LOGE("CdmEngine::DeleteUsageTable: error deleteing usage reports: %d",
status);
@@ -1063,8 +1050,7 @@ CdmResponseType CdmEngine::ListStoredLicenses(
}
CdmResponseType CdmEngine::ListUsageIds(
const std::string& app_id,
CdmSecurityLevel security_level,
const std::string& app_id, CdmSecurityLevel security_level,
std::vector<std::string>* ksids,
std::vector<std::string>* provider_session_tokens) {
DeviceFiles handle(file_system_);
@@ -1105,8 +1091,7 @@ CdmResponseType CdmEngine::DeleteUsageRecord(const std::string& app_id,
}
CdmResponseType CdmEngine::GetOfflineLicenseState(
const CdmKeySetId &key_set_id,
CdmSecurityLevel security_level,
const CdmKeySetId& key_set_id, CdmSecurityLevel security_level,
CdmOfflineLicenseState* license_state) {
DeviceFiles handle(file_system_);
if (!handle.Init(security_level)) {
@@ -1132,33 +1117,31 @@ CdmResponseType CdmEngine::GetOfflineLicenseState(
uint32_t usage_entry_number;
DeviceFiles::ResponseType sub_error_code = DeviceFiles::kNoError;
if (handle.RetrieveLicense(key_set_id, &state, &offline_init_data,
&key_request, &key_response,
if (handle.RetrieveLicense(
key_set_id, &state, &offline_init_data, &key_request, &key_response,
&offline_key_renewal_request, &offline_key_renewal_response,
&offline_release_server_url,
&playback_start_time, &last_playback_time, &grace_period_end_time,
&app_parameters, &usage_entry, &usage_entry_number,
&sub_error_code)) {
*license_state = MapDeviceFilesLicenseState(state);
&offline_release_server_url, &playback_start_time,
&last_playback_time, &grace_period_end_time, &app_parameters,
&usage_entry, &usage_entry_number, &sub_error_code)) {
*license_state = MapDeviceFilesLicenseState(state);
} else {
LOGE("CdmEngine::GetOfflineLicenseState:: failed to retrieve license state "
"key set id = %s",
key_set_id.c_str());
return GET_OFFLINE_LICENSE_STATE_ERROR_2;
LOGE(
"CdmEngine::GetOfflineLicenseState:: failed to retrieve license state "
"key set id = %s",
key_set_id.c_str());
return GET_OFFLINE_LICENSE_STATE_ERROR_2;
}
return NO_ERROR;
}
CdmResponseType CdmEngine::RemoveOfflineLicense(
const CdmKeySetId &key_set_id,
CdmSecurityLevel security_level) {
const CdmKeySetId& key_set_id, CdmSecurityLevel security_level) {
UsagePropertySet property_set;
property_set.set_security_level(
security_level == kSecurityLevelL3 ? kLevel3 : kLevelDefault);
DeviceFiles handle(file_system_);
CdmResponseType sts = OpenKeySetSession(key_set_id,
&property_set, nullptr /* event listener */);
CdmResponseType sts = OpenKeySetSession(key_set_id, &property_set,
nullptr /* event listener */);
if (sts != NO_ERROR) {
if (!handle.Init(security_level)) {
LOGE("CdmEngine::RemoveOfflineLicense: cannot initialize device files");
@@ -1173,7 +1156,7 @@ CdmResponseType CdmEngine::RemoveOfflineLicense(
CdmKeyRequest key_request;
// Calling with no session_id is okay
sts = GenerateKeyRequest(session_id, key_set_id, dummy_init_data,
kLicenseTypeRelease, dummy_app_params, &key_request);
kLicenseTypeRelease, dummy_app_params, &key_request);
if (sts == KEY_MESSAGE) {
std::unique_lock<std::mutex> lock(release_key_sets_lock_);
CdmReleaseKeySetMap::iterator iter = release_key_sets_.find(key_set_id);
@@ -1226,8 +1209,8 @@ CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id,
CdmKeyResponse license_response;
std::string usage_entry;
DeviceFiles::CdmUsageData usage_data;
if (!handle.RetrieveUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id),
ssid, &usage_data)) {
if (!handle.RetrieveUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id), ssid,
&usage_data)) {
usage_property_set_->set_security_level(kLevel3);
usage_property_set_->set_app_id(app_id);
usage_session_.reset(new CdmSession(file_system_, metrics_->AddSession()));
@@ -1376,8 +1359,8 @@ CdmResponseType CdmEngine::GetUsageInfo(const std::string& app_id,
CdmResponseType CdmEngine::RemoveAllUsageInfo(
const std::string& app_id, CdmSecurityLevel cdm_security_level) {
LOGI("CdmEngine::RemoveAllUsageInfo: %s, security level: %d",
app_id.c_str(), cdm_security_level);
LOGI("CdmEngine::RemoveAllUsageInfo: %s, security level: %d", app_id.c_str(),
cdm_security_level);
if (usage_property_set_.get() == nullptr) {
usage_property_set_.reset(new UsagePropertySet());
}
@@ -1400,36 +1383,38 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo(
// might cause other entries to be shifted and information updated.
do {
if (!handle.RetrieveUsageInfo(
DeviceFiles::GetUsageInfoFileName(app_id),
&usage_data)) {
LOGW("CdmEngine::RemoveAllUsageInfo: failed to retrieve usage info");
DeviceFiles::GetUsageInfoFileName(app_id), &usage_data)) {
LOGW(
"CdmEngine::RemoveAllUsageInfo: failed to retrieve usage info");
break;
}
if (usage_data.empty()) break;
CdmResponseType res = usage_session_->DeleteUsageEntry(
usage_data[0].usage_entry_number);
usage_data[0].usage_entry_number);
if (res != NO_ERROR) {
LOGW("CdmEngine::RemoveAllUsageInfo: failed to delete usage "
"entry: error: %d", res);
LOGW(
"CdmEngine::RemoveAllUsageInfo: failed to delete usage "
"entry: error: %d",
res);
break;
}
if (!handle.DeleteUsageInfo(
DeviceFiles::GetUsageInfoFileName(app_id),
usage_data[0].provider_session_token)) {
LOGW("CdmEngine::RemoveAllUsageInfo: failed to delete usage "
"info");
if (!handle.DeleteUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id),
usage_data[0].provider_session_token)) {
LOGW(
"CdmEngine::RemoveAllUsageInfo: failed to delete usage "
"info");
break;
}
} while (!usage_data.empty());
std::vector<std::string> provider_session_tokens;
if (!handle.DeleteAllUsageInfoForApp(
DeviceFiles::GetUsageInfoFileName(app_id),
&provider_session_tokens)) {
DeviceFiles::GetUsageInfoFileName(app_id),
&provider_session_tokens)) {
status = REMOVE_ALL_USAGE_INFO_ERROR_5;
}
break;
@@ -1437,14 +1422,17 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo(
case kUsageTableSupport: {
std::vector<std::string> provider_session_tokens;
if (!handle.DeleteAllUsageInfoForApp(
DeviceFiles::GetUsageInfoFileName(app_id),
&provider_session_tokens)) {
LOGE("CdmEngine::RemoveAllUsageInfo: failed to delete %d secure"
"stops", cdm_security_level);
DeviceFiles::GetUsageInfoFileName(app_id),
&provider_session_tokens)) {
LOGE(
"CdmEngine::RemoveAllUsageInfo: failed to delete %d secure"
"stops",
cdm_security_level);
status = REMOVE_ALL_USAGE_INFO_ERROR_1;
} else {
CdmResponseType status2 = usage_session_->
DeleteMultipleUsageInformation(provider_session_tokens);
CdmResponseType status2 =
usage_session_->DeleteMultipleUsageInformation(
provider_session_tokens);
if (status2 != NO_ERROR) status = status2;
}
break;
@@ -1468,8 +1456,7 @@ CdmResponseType CdmEngine::RemoveAllUsageInfo(const std::string& app_id) {
}
CdmResponseType CdmEngine::RemoveUsageInfo(
const std::string& app_id,
const CdmSecureStopId& provider_session_token) {
const std::string& app_id, const CdmSecureStopId& provider_session_token) {
LOGI("CdmEngine::RemoveUsageInfo: %s, PST: %s", app_id.c_str(),
provider_session_token.c_str());
if (NULL == usage_property_set_.get()) {
@@ -1482,11 +1469,11 @@ CdmResponseType CdmEngine::RemoveUsageInfo(
DeviceFiles handle(file_system_);
if (handle.Init(static_cast<CdmSecurityLevel>(j))) {
SecurityLevel security_level =
static_cast<CdmSecurityLevel>(j) == kSecurityLevelL3
? kLevel3
: kLevelDefault;
static_cast<CdmSecurityLevel>(j) == kSecurityLevelL3 ? kLevel3
: kLevelDefault;
usage_property_set_->set_security_level(security_level);
usage_session_.reset(new CdmSession(file_system_, metrics_->AddSession()));
usage_session_.reset(
new CdmSession(file_system_, metrics_->AddSession()));
usage_session_->Init(usage_property_set_.get());
std::vector<DeviceFiles::CdmUsageData> usage_data;
@@ -1495,10 +1482,10 @@ CdmResponseType CdmEngine::RemoveUsageInfo(
CdmUsageEntry usage_entry;
uint32_t usage_entry_number;
if (!handle.RetrieveUsageInfo(
DeviceFiles::GetUsageInfoFileName(app_id), provider_session_token,
&license_request, &license_response, &usage_entry,
&usage_entry_number)) {
if (!handle.RetrieveUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id),
provider_session_token, &license_request,
&license_response, &usage_entry,
&usage_entry_number)) {
// Try other security level
continue;
}
@@ -1507,24 +1494,23 @@ CdmResponseType CdmEngine::RemoveUsageInfo(
case kUsageEntrySupport: {
status = usage_session_->DeleteUsageEntry(usage_entry_number);
if (!handle.DeleteUsageInfo(
DeviceFiles::GetUsageInfoFileName(app_id),
provider_session_token)) {
status = REMOVE_USAGE_INFO_ERROR_1;
if (!handle.DeleteUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id),
provider_session_token)) {
status = REMOVE_USAGE_INFO_ERROR_1;
}
usage_session_.reset(NULL);
return status;
}
case kUsageTableSupport: {
std::vector<std::string> provider_session_tokens;
handle.DeleteUsageInfo(
DeviceFiles::GetUsageInfoFileName(app_id),
provider_session_token);
handle.DeleteUsageInfo(DeviceFiles::GetUsageInfoFileName(app_id),
provider_session_token);
std::unique_ptr<CryptoSession> crypto_session(
CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics()));
status = crypto_session->Open(
static_cast<CdmSecurityLevel>(j) == kSecurityLevelL3
? kLevel3 : kLevelDefault);
status = crypto_session->Open(static_cast<CdmSecurityLevel>(j) ==
kSecurityLevelL3
? kLevel3
: kLevelDefault);
if (status == NO_ERROR) {
crypto_session->UpdateUsageInformation();
status =
@@ -1598,19 +1584,18 @@ CdmResponseType CdmEngine::LoadUsageSession(const CdmKeySetId& key_set_id,
DeviceFiles::CdmUsageData usage_data;
if (!handle.RetrieveUsageInfoByKeySetId(
DeviceFiles::GetUsageInfoFileName(app_id), key_set_id,
&(usage_data.provider_session_token),
&(usage_data.license_request),
&(usage_data.license), &(usage_data.usage_entry),
&(usage_data.usage_entry_number))) {
DeviceFiles::GetUsageInfoFileName(app_id), key_set_id,
&(usage_data.provider_session_token), &(usage_data.license_request),
&(usage_data.license), &(usage_data.usage_entry),
&(usage_data.usage_entry_number))) {
LOGE("CdmEngine::LoadUsageSession: unable to find usage information");
return LOAD_USAGE_INFO_MISSING;
}
int error_detail = NO_ERROR;
usage_data.key_set_id = key_set_id;
CdmResponseType status = session->RestoreUsageSession(usage_data,
&error_detail);
CdmResponseType status =
session->RestoreUsageSession(usage_data, &error_detail);
session->GetMetrics()->cdm_session_restore_usage_session_.Increment(
status, error_detail);
if (KEY_ADDED != status) {
@@ -1698,10 +1683,12 @@ CdmResponseType CdmEngine::Decrypt(const CdmSessionId& session_id,
return session->Decrypt(parameters);
}
CdmResponseType CdmEngine::GenericEncrypt(
const std::string& session_id, const std::string& in_buffer,
const std::string& key_id, const std::string& iv,
CdmEncryptionAlgorithm algorithm, std::string* out_buffer) {
CdmResponseType CdmEngine::GenericEncrypt(const std::string& session_id,
const std::string& in_buffer,
const std::string& key_id,
const std::string& iv,
CdmEncryptionAlgorithm algorithm,
std::string* out_buffer) {
if (out_buffer == NULL) {
LOGE("CdmEngine::GenericEncrypt: no out_buffer provided");
return PARAMETER_NULL;
@@ -1715,11 +1702,12 @@ CdmResponseType CdmEngine::GenericEncrypt(
return session->GenericEncrypt(in_buffer, key_id, iv, algorithm, out_buffer);
}
CdmResponseType CdmEngine::GenericDecrypt(
const std::string& session_id, const std::string& in_buffer,
const std::string& key_id, const std::string& iv,
CdmEncryptionAlgorithm algorithm,
std::string* out_buffer) {
CdmResponseType CdmEngine::GenericDecrypt(const std::string& session_id,
const std::string& in_buffer,
const std::string& key_id,
const std::string& iv,
CdmEncryptionAlgorithm algorithm,
std::string* out_buffer) {
if (out_buffer == NULL) {
LOGE("CdmEngine::GenericDecrypt: no out_buffer provided");
return PARAMETER_NULL;
@@ -1733,10 +1721,11 @@ CdmResponseType CdmEngine::GenericDecrypt(
return session->GenericDecrypt(in_buffer, key_id, iv, algorithm, out_buffer);
}
CdmResponseType CdmEngine::GenericSign(
const std::string& session_id, const std::string& message,
const std::string& key_id, CdmSigningAlgorithm algorithm,
std::string* signature) {
CdmResponseType CdmEngine::GenericSign(const std::string& session_id,
const std::string& message,
const std::string& key_id,
CdmSigningAlgorithm algorithm,
std::string* signature) {
if (signature == NULL) {
LOGE("CdmEngine::GenericSign: no signature buffer provided");
return PARAMETER_NULL;
@@ -1750,10 +1739,11 @@ CdmResponseType CdmEngine::GenericSign(
return session->GenericSign(message, key_id, algorithm, signature);
}
CdmResponseType CdmEngine::GenericVerify(
const std::string& session_id, const std::string& message,
const std::string& key_id, CdmSigningAlgorithm algorithm,
const std::string& signature) {
CdmResponseType CdmEngine::GenericVerify(const std::string& session_id,
const std::string& message,
const std::string& key_id,
CdmSigningAlgorithm algorithm,
const std::string& signature) {
std::shared_ptr<CdmSession> session;
if (!session_map_.FindSession(session_id, &session)) {
LOGE("CdmEngine::GenericVerify: session_id not found = %s ",
@@ -1764,10 +1754,8 @@ CdmResponseType CdmEngine::GenericVerify(
}
CdmResponseType CdmEngine::ParseDecryptHashString(
const std::string& hash_string,
CdmSessionId* session_id,
uint32_t* frame_number,
std::string* hash) {
const std::string& hash_string, CdmSessionId* session_id,
uint32_t* frame_number, std::string* hash) {
if (session_id == nullptr) {
LOGE("CdmEngine::ParseDecryptHashString: |session_id| was not provided");
return PARAMETER_NULL;
@@ -1788,16 +1776,19 @@ CdmResponseType CdmEngine::ParseDecryptHashString(
tokens.push_back(token);
}
if (tokens.size() != 3) {
LOGE("CdmEngine::ParseDecryptHashString: |hash_string| has invalid format, "
"unexpected number of tokens: %d (%s)",
tokens.size(), hash_string.c_str());
LOGE(
"CdmEngine::ParseDecryptHashString: |hash_string| has invalid format, "
"unexpected number of tokens: %d (%s)",
tokens.size(), hash_string.c_str());
return INVALID_DECRYPT_HASH_FORMAT;
}
for (size_t i = 0; i < tokens.size(); ++i) {
if (tokens[i].empty()) {
LOGE("CdmEngine::ParseDecryptHashString: |hash_string| has invalid "
"format, token %d of length 0: %s", i, hash_string.c_str());
LOGE(
"CdmEngine::ParseDecryptHashString: |hash_string| has invalid "
"format, token %d of length 0: %s",
i, hash_string.c_str());
return INVALID_DECRYPT_HASH_FORMAT;
}
}
@@ -1805,8 +1796,10 @@ CdmResponseType CdmEngine::ParseDecryptHashString(
*session_id = tokens[0];
std::istringstream iss(tokens[1]);
if (!(iss >> *frame_number)) {
LOGE("CdmEngine::ParseDecryptHashString: error while trying to convert "
"frame number to a numeric format: %s", hash_string.c_str());
LOGE(
"CdmEngine::ParseDecryptHashString: error while trying to convert "
"frame number to a numeric format: %s",
hash_string.c_str());
return INVALID_DECRYPT_HASH_FORMAT;
}
@@ -1820,10 +1813,9 @@ CdmResponseType CdmEngine::ParseDecryptHashString(
return NO_ERROR;
}
CdmResponseType CdmEngine::SetDecryptHash(
const CdmSessionId& session_id,
uint32_t frame_number,
const std::string& hash) {
CdmResponseType CdmEngine::SetDecryptHash(const CdmSessionId& session_id,
uint32_t frame_number,
const std::string& hash) {
LOGI("CdmEngine::SetDecryptHash: %s", session_id.c_str());
std::shared_ptr<CdmSession> session;
if (!session_map_.FindSession(session_id, &session)) {
@@ -1832,9 +1824,8 @@ CdmResponseType CdmEngine::SetDecryptHash(
return session->SetDecryptHash(frame_number, hash);
}
CdmResponseType CdmEngine::GetDecryptHashError(
const CdmSessionId& session_id,
std::string* error_string) {
CdmResponseType CdmEngine::GetDecryptHashError(const CdmSessionId& session_id,
std::string* error_string) {
LOGI("CdmEngine::GetDecryptHashError: %s", session_id.c_str());
std::shared_ptr<CdmSession> session;
if (!session_map_.FindSession(session_id, &session)) {
@@ -1847,8 +1838,8 @@ CdmResponseType CdmEngine::GetDecryptHashError(
bool CdmEngine::IsKeyLoaded(const KeyId& key_id) {
CdmSessionList sessions;
session_map_.GetSessionList(sessions);
for (CdmSessionList::iterator iter = sessions.begin();
iter != sessions.end(); ++iter) {
for (CdmSessionList::iterator iter = sessions.begin(); iter != sessions.end();
++iter) {
if ((*iter)->IsKeyLoaded(key_id)) {
return true;
}
@@ -1872,8 +1863,8 @@ bool CdmEngine::FindSessionForKey(const KeyId& key_id,
CdmSessionList::iterator session_iter = sessions.end();
int64_t seconds_remaining = 0;
for (CdmSessionList::iterator iter = sessions.begin();
iter != sessions.end(); ++iter) {
for (CdmSessionList::iterator iter = sessions.begin(); iter != sessions.end();
++iter) {
CdmSessionId id = (*iter)->session_id();
if (Properties::GetSessionSharingId(id) == session_sharing_id) {
if ((*iter)->IsKeyLoaded(key_id)) {
@@ -1927,9 +1918,8 @@ void CdmEngine::OnTimerEvent() {
session_map_.GetSessionList(sessions);
while (!sessions.empty()) {
is_initial_usage_update =
is_initial_usage_update ||
sessions.front()->is_initial_usage_update();
is_initial_usage_update = is_initial_usage_update ||
sessions.front()->is_initial_usage_update();
is_usage_update_needed =
is_usage_update_needed || sessions.front()->is_usage_update_needed();
@@ -1990,8 +1980,7 @@ CdmResponseType CdmEngine::ValidateServiceCertificate(const std::string& cert) {
return certificate.Init(cert);
}
std::string CdmEngine::MapHdcpVersion(
CryptoSession::HdcpCapability version) {
std::string CdmEngine::MapHdcpVersion(CryptoSession::HdcpCapability version) {
switch (version) {
case HDCP_NONE:
return QUERY_VALUE_HDCP_NONE;
@@ -2048,27 +2037,26 @@ void CdmEngine::DeleteAllUsageReportsUponFactoryReset() {
std::unique_ptr<CryptoSession> crypto_session(
CryptoSession::MakeCryptoSession(metrics_->GetCryptoMetrics()));
CdmResponseType status;
M_TIME(
status = crypto_session->Open(
cert_provisioning_requested_security_level_),
metrics_->GetCryptoMetrics(),
crypto_session_open_,
status,
cert_provisioning_requested_security_level_);
M_TIME(status = crypto_session->Open(
cert_provisioning_requested_security_level_),
metrics_->GetCryptoMetrics(), crypto_session_open_, status,
cert_provisioning_requested_security_level_);
if (NO_ERROR == status) {
status = crypto_session->DeleteAllUsageReports();
metrics_->GetCryptoMetrics()->crypto_session_delete_all_usage_reports_
.Increment(status);
metrics_->GetCryptoMetrics()
->crypto_session_delete_all_usage_reports_.Increment(status);
if (NO_ERROR != status) {
LOGW(
"CdmEngine::DeleteAllUsageReportsUponFactoryReset: "
"Fails to delete usage reports: %d", status);
"Fails to delete usage reports: %d",
status);
}
} else {
LOGW(
"CdmEngine::DeleteAllUsageReportsUponFactoryReset: "
"Fails to open crypto session: error=%d.\n"
"Usage reports are not removed after factory reset.", status);
"Usage reports are not removed after factory reset.",
status);
}
}
}

View File

@@ -6,6 +6,7 @@
#include <memory>
#include <string>
#include "cdm_engine.h"
#include "cdm_engine_metrics_decorator.h"
#include "clock.h"

View File

@@ -23,7 +23,7 @@ namespace {
const size_t kKeySetIdLength = 14;
// Helper function for setting the error detail value.
template<typename T>
template <typename T>
void SetErrorDetail(int* error_detail, T error_code) {
if (error_detail != nullptr) {
*error_detail = error_code;
@@ -63,8 +63,7 @@ CdmSession::CdmSession(FileSystem* file_system,
CdmSession::~CdmSession() {
if (usage_support_type_ == kUsageEntrySupport &&
has_provider_session_token() &&
usage_table_header_ != NULL &&
has_provider_session_token() && usage_table_header_ != NULL &&
!is_release_) {
UpdateUsageEntryInformation();
}
@@ -107,8 +106,8 @@ CdmResponseType CdmSession::Init(CdmClientPropertySet* cdm_client_property_set,
security_level_ = crypto_session_->GetSecurityLevel();
crypto_metrics_->crypto_session_security_level_.Record(security_level_);
std::string oemcrypto_build;
if(crypto_session_->GetBuildInformation(requested_security_level_,
&oemcrypto_build)) {
if (crypto_session_->GetBuildInformation(requested_security_level_,
&oemcrypto_build)) {
metrics_->oemcrypto_build_info_.Record(oemcrypto_build);
} else {
metrics_->oemcrypto_build_info_.SetError(false);
@@ -152,7 +151,8 @@ CdmResponseType CdmSession::Init(CdmClientPropertySet* cdm_client_property_set,
crypto_metrics_, crypto_session_load_certificate_private_key_,
load_cert_sts);
switch (load_cert_sts) {
case NO_ERROR: break;
case NO_ERROR:
break;
case SESSION_LOST_STATE_ERROR:
case SYSTEM_INVALIDATED_ERROR:
return load_cert_sts;
@@ -207,9 +207,9 @@ CdmResponseType CdmSession::Init(CdmClientPropertySet* cdm_client_property_set,
return NO_ERROR;
}
CdmResponseType CdmSession::RestoreOfflineSession(
const CdmKeySetId& key_set_id, CdmLicenseType license_type,
int* error_detail) {
CdmResponseType CdmSession::RestoreOfflineSession(const CdmKeySetId& key_set_id,
CdmLicenseType license_type,
int* error_detail) {
if (!initialized_) {
LOGE("CdmSession::RestoreOfflineSession: not initialized");
return NOT_INITIALIZED_ERROR;
@@ -237,9 +237,8 @@ CdmResponseType CdmSession::RestoreOfflineSession(
"sub error: %d, key set id = %s",
sub_error_code, key_set_id.c_str());
SetErrorDetail(error_detail, sub_error_code);
return sub_error_code == DeviceFiles::kFileNotFound
? KEYSET_ID_NOT_FOUND_4
: GET_LICENSE_ERROR;
return sub_error_code == DeviceFiles::kFileNotFound ? KEYSET_ID_NOT_FOUND_4
: GET_LICENSE_ERROR;
}
// Attempts to restore a released offline license are treated as a release
@@ -341,8 +340,8 @@ CdmResponseType CdmSession::RestoreUsageSession(
CdmResponseType sts = NO_ERROR;
if (usage_support_type_ == kUsageEntrySupport &&
usage_table_header_ != NULL) {
sts = usage_table_header_->LoadEntry(
crypto_session_.get(), usage_entry_, usage_entry_number_);
sts = usage_table_header_->LoadEntry(crypto_session_.get(), usage_entry_,
usage_entry_number_);
crypto_metrics_->usage_table_header_load_entry_.Increment(sts);
if (sts != NO_ERROR) {
LOGE("CdmSession::RestoreUsageSession: failed to load usage entry = %d",
@@ -391,16 +390,14 @@ CdmResponseType CdmSession::GenerateKeyRequest(
// for calling GenerateReleaseRequest and GenerateRenewalRequest.
if (result == KEY_MESSAGE) {
key_request_type_ = key_request->type;
license_request_latency_.Start(); // Start or restart timer.
license_request_latency_.Start(); // Start or restart timer.
}
return result;
}
CdmResponseType CdmSession::GenerateKeyRequestInternal(
const InitializationData& init_data, CdmLicenseType license_type,
const CdmAppParameterMap& app_parameters,
CdmKeyRequest* key_request) {
const CdmAppParameterMap& app_parameters, CdmKeyRequest* key_request) {
if (!initialized_) {
LOGE("CdmSession::GenerateKeyRequest: not initialized");
return NOT_INITIALIZED_ERROR;
@@ -527,7 +524,8 @@ CdmResponseType CdmSession::AddKeyInternal(const CdmKeyResponse& key_response) {
// Update the license sdk and service versions.
const VersionInfo& version_info = license_parser_->GetServiceVersion();
metrics_->license_sdk_version_.Record(version_info.license_sdk_version());
metrics_->license_sdk_version_.Record(version_info.license_service_version());
metrics_->license_sdk_version_.Record(
version_info.license_service_version());
// Update or delete entry if usage table header+entries are supported
if (usage_support_type_ == kUsageEntrySupport &&
@@ -684,7 +682,7 @@ CdmResponseType CdmSession::GenerateRenewalRequest(CdmKeyRequest* key_request) {
offline_key_renewal_request_ = key_request->message;
}
key_request_type_ = key_request->type;
license_request_latency_.Start(); // Start or restart timer.
license_request_latency_.Start(); // Start or restart timer.
return KEY_MESSAGE;
}
@@ -750,7 +748,7 @@ CdmResponseType CdmSession::GenerateReleaseRequest(CdmKeyRequest* key_request) {
}
key_request_type_ = key_request->type;
license_request_latency_.Start(); // Start or restart timer.
license_request_latency_.Start(); // Start or restart timer.
return KEY_MESSAGE;
}
@@ -805,8 +803,8 @@ CdmResponseType CdmSession::DeleteUsageEntry(uint32_t usage_entry_number) {
return INCORRECT_USAGE_SUPPORT_TYPE_1;
}
sts = usage_table_header_->DeleteEntry(usage_entry_number,
file_handle_.get(), crypto_metrics_);
sts = usage_table_header_->DeleteEntry(usage_entry_number, file_handle_.get(),
crypto_metrics_);
crypto_metrics_->usage_table_header_delete_entry_.Increment(sts);
return sts;
}
@@ -835,8 +833,8 @@ bool CdmSession::GenerateKeySetId(CdmKeySetId* key_set_id) {
(kKeySetIdLength - sizeof(KEY_SET_ID_PREFIX)) / 2, 0);
while (key_set_id->empty()) {
if (crypto_session_->GetRandom(random_data.size(), &random_data[0])
!= NO_ERROR) {
if (crypto_session_->GetRandom(random_data.size(), &random_data[0]) !=
NO_ERROR) {
return false;
}
@@ -906,8 +904,7 @@ CdmResponseType CdmSession::StoreLicense() {
}
std::vector<std::string> provider_session_tokens;
file_handle_->DeleteAllUsageInfoForApp(
DeviceFiles::GetUsageInfoFileName(app_id),
&provider_session_tokens);
DeviceFiles::GetUsageInfoFileName(app_id), &provider_session_tokens);
return STORE_USAGE_INFO_ERROR;
}
@@ -934,21 +931,16 @@ CdmResponseType CdmSession::RemoveKeys() {
CdmResponseType sts;
crypto_session_.reset(CryptoSession::MakeCryptoSession(crypto_metrics_));
// Ignore errors
M_TIME(
sts = crypto_session_->Open(requested_security_level_),
crypto_metrics_,
crypto_session_open_,
sts,
requested_security_level_);
policy_engine_.reset(new PolicyEngine(
session_id_, NULL, crypto_session_.get()));
M_TIME(sts = crypto_session_->Open(requested_security_level_),
crypto_metrics_, crypto_session_open_, sts, requested_security_level_);
policy_engine_.reset(
new PolicyEngine(session_id_, NULL, crypto_session_.get()));
return NO_ERROR;
}
CdmResponseType CdmSession::RemoveLicense() {
CdmResponseType sts = NO_ERROR;
if (is_offline_ || has_provider_session_token()) {
if (usage_support_type_ == kUsageEntrySupport &&
has_provider_session_token()) {
sts = DeleteUsageEntry(usage_entry_number_);
@@ -1058,7 +1050,8 @@ CdmResponseType CdmSession::UpdateUsageEntryInformation() {
if (is_offline_)
StoreLicense(is_release_ ? DeviceFiles::kLicenseStateReleasing
: DeviceFiles::kLicenseStateActive, nullptr);
: DeviceFiles::kLicenseStateActive,
nullptr);
else if (!usage_provider_session_token_.empty())
UpdateUsageInfo();
@@ -1132,8 +1125,7 @@ CdmResponseType CdmSession::SetDecryptHash(uint32_t frame_number,
return crypto_session_->SetDecryptHash(frame_number, hash);
}
CdmResponseType CdmSession::GetDecryptHashError(
std::string* error_string) {
CdmResponseType CdmSession::GetDecryptHashError(std::string* error_string) {
return crypto_session_->GetDecryptHashError(error_string);
}

View File

@@ -11,13 +11,11 @@
namespace wvcdm {
CdmSessionMap::~CdmSessionMap() {
Terminate();
}
CdmSessionMap::~CdmSessionMap() { Terminate(); }
void CdmSessionMap::Terminate() {
for (CdmIdToSessionMap::iterator i = sessions_.begin();
i != sessions_.end(); ++i) {
for (CdmIdToSessionMap::iterator i = sessions_.begin(); i != sessions_.end();
++i) {
i->second->Close();
i->second.reset();
}

View File

@@ -3,6 +3,7 @@
// License Agreement.
#include "certificate_provisioning.h"
#include "client_identification.h"
#include "device_files.h"
#include "file_store.h"
@@ -110,9 +111,9 @@ using video_widevine::SignedProvisioningMessage;
CdmResponseType CertificateProvisioning::Init(
const std::string& service_certificate) {
std::string certificate = service_certificate.empty() ?
kCpProductionServiceCertificate : service_certificate;
std::string certificate = service_certificate.empty()
? kCpProductionServiceCertificate
: service_certificate;
return service_certificate_->Init(certificate);
}
@@ -126,8 +127,9 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter(
const std::string& origin, const std::string& spoid,
ProvisioningRequest* request) {
if (!request) {
LOGE("CertificateProvisioning::SetSpoidParameter: No request buffer "
"passed to method.");
LOGE(
"CertificateProvisioning::SetSpoidParameter: No request buffer "
"passed to method.");
return PARAMETER_NULL;
}
if (!spoid.empty()) {
@@ -137,8 +139,9 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter(
if (!service_certificate_->provider_id().empty()) {
request->set_provider_id(service_certificate_->provider_id());
} else {
LOGE("CertificateProvisioning::SetSpoidParameter: Failure getting "
"provider ID");
LOGE(
"CertificateProvisioning::SetSpoidParameter: Failure getting "
"provider ID");
return SERVICE_CERTIFICATE_PROVIDER_ID_EMPTY;
}
} else if (origin != EMPTY_ORIGIN) {
@@ -148,8 +151,9 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter(
crypto_session_->GetInternalDeviceUniqueId(&device_unique_id);
if (status != NO_ERROR) {
LOGE("CertificateProvisioning::SetSpoidParameter: Failure getting "
"device unique ID");
LOGE(
"CertificateProvisioning::SetSpoidParameter: Failure getting "
"device unique ID");
return status;
}
request->set_stable_id(device_unique_id + origin);
@@ -162,7 +166,7 @@ CdmResponseType CertificateProvisioning::SetSpoidParameter(
* support for OEM certificates.
*/
SignedProvisioningMessage::ProtocolVersion
CertificateProvisioning::GetProtocolVersion() {
CertificateProvisioning::GetProtocolVersion() {
if (crypto_session_->GetPreProvisionTokenType() == kClientTokenOemCert)
return SignedProvisioningMessage::VERSION_3;
else
@@ -209,8 +213,9 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest(
if (status != NO_ERROR) return status;
if (!service_certificate_->has_certificate()) {
LOGE("CertificateProvisioning::GetProvisioningRequest: Service "
"Certificate not staged");
LOGE(
"CertificateProvisioning::GetProvisioningRequest: Service "
"Certificate not staged");
return CERT_PROVISIONING_EMPTY_SERVICE_CERTIFICATE;
}
@@ -226,8 +231,9 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest(
if (status != NO_ERROR) {
LOGE("GetProvisioningRequest: fails to generate a nonce: %d", status);
return status == NONCE_GENERATION_ERROR ?
CERT_PROVISIONING_NONCE_GENERATION_ERROR : status;
return status == NONCE_GENERATION_ERROR
? CERT_PROVISIONING_NONCE_GENERATION_ERROR
: status;
}
// The provisioning server does not convert the nonce to uint32_t, it just
@@ -303,7 +309,6 @@ CdmResponseType CertificateProvisioning::GetProvisioningRequest(
CdmResponseType CertificateProvisioning::HandleProvisioningResponse(
FileSystem* file_system, const CdmProvisioningResponse& response_message,
std::string* cert, std::string* wrapped_key) {
if (response_message.empty()) {
LOGE("HandleProvisioningResponse: response message is empty.");
return CERT_PROVISIONING_RESPONSE_ERROR_1;
@@ -317,8 +322,9 @@ CdmResponseType CertificateProvisioning::HandleProvisioningResponse(
// Extract it and decode it. On error return an empty string.
ExtractAndDecodeSignedMessage(response_message, &response);
if (response.empty()) {
LOGE("HandleProvisioningResponse: response message is "
"an invalid JSON/base64 string.");
LOGE(
"HandleProvisioningResponse: response message is "
"an invalid JSON/base64 string.");
return CERT_PROVISIONING_RESPONSE_ERROR_1;
}
}
@@ -362,8 +368,8 @@ CdmResponseType CertificateProvisioning::HandleProvisioningResponse(
// If Provisioning 3.0 (OEM Cert provisioned), verify that the
// message is properly signed.
if (crypto_session_->GetPreProvisionTokenType() == kClientTokenOemCert) {
if (service_certificate_->VerifySignedMessage(signed_message, signature)
!= NO_ERROR) {
if (service_certificate_->VerifySignedMessage(signed_message, signature) !=
NO_ERROR) {
// TODO(b/69562876): if the cert is bad, request a new one.
LOGE("HandleProvisioningResponse: message not properly signed");
return CERT_PROVISIONING_RESPONSE_ERROR_6;
@@ -374,15 +380,15 @@ CdmResponseType CertificateProvisioning::HandleProvisioningResponse(
const std::string& nonce = provisioning_response.nonce();
const std::string& iv = provisioning_response.device_rsa_key_iv();
const std::string& wrapping_key = (provisioning_response.has_wrapping_key()) ?
provisioning_response.wrapping_key() : std::string();
const std::string& wrapping_key = (provisioning_response.has_wrapping_key())
? provisioning_response.wrapping_key()
: std::string();
std::string wrapped_private_key;
CdmResponseType status =
crypto_session_->RewrapCertificate(signed_message, signature, nonce,
new_private_key, iv, wrapping_key,
&wrapped_private_key);
CdmResponseType status = crypto_session_->RewrapCertificate(
signed_message, signature, nonce, new_private_key, iv, wrapping_key,
&wrapped_private_key);
if (status != NO_ERROR) {
LOGE("HandleProvisioningResponse: RewrapCertificate fails");

View File

@@ -77,7 +77,6 @@ CdmResponseType ClientIdentification::Prepare(
const CdmAppParameterMap& app_parameters,
const std::string& provider_client_token,
video_widevine::ClientIdentification* client_id) {
if (is_license_request_) {
client_id->set_type(
video_widevine::ClientIdentification::DRM_DEVICE_CERTIFICATE);
@@ -85,8 +84,9 @@ CdmResponseType ClientIdentification::Prepare(
} else {
video_widevine::ClientIdentification::TokenType token_type;
if (!GetProvisioningTokenType(&token_type)) {
LOGE("ClientIdentification::Prepare: failure getting provisioning token "
"type");
LOGE(
"ClientIdentification::Prepare: failure getting provisioning token "
"type");
return CLIENT_IDENTIFICATION_TOKEN_ERROR_1;
}
client_id->set_type(token_type);
@@ -94,8 +94,10 @@ CdmResponseType ClientIdentification::Prepare(
std::string token;
CdmResponseType status = crypto_session_->GetProvisioningToken(&token);
if (status != NO_ERROR) {
LOGE("ClientIdentification::Prepare: failure getting provisioning token: "
"%d", status);
LOGE(
"ClientIdentification::Prepare: failure getting provisioning token: "
"%d",
status);
return status;
}
client_id->set_token(token);
@@ -223,7 +225,8 @@ CdmResponseType ClientIdentification::Prepare(
default:
LOGW(
"ClientIdentification::PrepareClientId: unexpected HDCP max "
"capability version %d", max_version);
"capability version %d",
max_version);
}
}
}
@@ -252,23 +255,27 @@ CdmResponseType ClientIdentification::Prepare(
bool can_support_output;
bool can_disable_output;
bool can_support_cgms_a;
if (crypto_session_->GetAnalogOutputCapabilities(&can_support_output,
&can_disable_output,
&can_support_cgms_a)) {
if (crypto_session_->GetAnalogOutputCapabilities(
&can_support_output, &can_disable_output, &can_support_cgms_a)) {
video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities
capabilities = video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_NONE;
capabilities = video_widevine::
ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_NONE;
if (can_support_output) {
if (can_support_cgms_a) {
capabilities = video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTS_CGMS_A;
capabilities = video_widevine::
ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTS_CGMS_A;
} else {
capabilities = video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTED;
capabilities = video_widevine::
ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_SUPPORTED;
}
}
client_capabilities->set_analog_output_capabilities(capabilities);
client_capabilities->set_can_disable_analog_output(can_disable_output);
} else {
client_capabilities->set_analog_output_capabilities(video_widevine::ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_UNKNOWN);
client_capabilities->set_analog_output_capabilities(
video_widevine::
ClientIdentification_ClientCapabilities_AnalogOutputCapabilities_ANALOG_OUTPUT_UNKNOWN);
}
uint32_t version, tier;
@@ -297,8 +304,10 @@ bool ClientIdentification::GetProvisioningTokenType(
case kClientTokenDrmCert:
default:
// shouldn't happen
LOGE("CertificateProvisioning::GetProvisioningTokenType: unexpected "
"provisioning type: %d", token);
LOGE(
"CertificateProvisioning::GetProvisioningTokenType: unexpected "
"provisioning type: %d",
token);
return false;
}
}

View File

@@ -3,6 +3,7 @@
// License Agreement.
#include "content_key_session.h"
#include "crypto_key.h"
#include "crypto_session.h"
#include "log.h"
@@ -36,8 +37,7 @@ OEMCryptoResult ContentKeySession::GenerateDerivedKeys(
// Generate Derived Keys (from session key) for ContentKeySession
OEMCryptoResult ContentKeySession::GenerateDerivedKeys(
const std::string& message,
const std::string& session_key) {
const std::string& message, const std::string& session_key) {
std::string mac_deriv_message;
std::string enc_deriv_message;
GenerateMacContext(message, &mac_deriv_message);

View File

@@ -8,6 +8,7 @@
#include "crypto_session.h"
#include <string.h>
#include <algorithm>
#include <iostream>
#include <memory>
@@ -129,17 +130,16 @@ OEMCrypto_LicenseType OEMCryptoLicenseType(CdmLicenseKeyType cdm_license_type) {
}
OEMCryptoCipherMode ToOEMCryptoCipherMode(CdmCipherMode cipher_mode) {
return cipher_mode == kCipherModeCtr
? OEMCrypto_CipherMode_CTR : OEMCrypto_CipherMode_CBC;
return cipher_mode == kCipherModeCtr ? OEMCrypto_CipherMode_CTR
: OEMCrypto_CipherMode_CBC;
}
// This maps a few common OEMCryptoResult to CdmResponseType. Many mappings
// are not universal but are OEMCrypto method specific. Those will be
// specified in the CryptoSession method rather than here.
CdmResponseType MapOEMCryptoResult(
OEMCryptoResult result,
CdmResponseType default_status,
const char* error_string) {
CdmResponseType MapOEMCryptoResult(OEMCryptoResult result,
CdmResponseType default_status,
const char* error_string) {
if (result != OEMCrypto_SUCCESS) {
LOGE("%s: error %d", error_string, result);
}
@@ -187,8 +187,7 @@ CryptoSession::~CryptoSession() {
}
CdmResponseType CryptoSession::GetProvisioningMethod(
SecurityLevel requested_security_level,
CdmClientTokenType* token_type) {
SecurityLevel requested_security_level, CdmClientTokenType* token_type) {
OEMCrypto_ProvisioningMethod method;
WithOecReadLock("GetProvisioningMethod", [&] {
method = OEMCrypto_GetProvisioningMethod(requested_security_level);
@@ -252,9 +251,7 @@ void CryptoSession::Terminate() {
}
if (session_count_ > 0 || !initialized_) return;
OEMCryptoResult sts;
WithOecWriteLock("Terminate", [&] {
sts = OEMCrypto_Terminate();
});
WithOecWriteLock("Terminate", [&] { sts = OEMCrypto_Terminate(); });
if (OEMCrypto_SUCCESS != sts) {
LOGE("OEMCrypto_Terminate failed: %d", sts);
}
@@ -283,19 +280,18 @@ CdmResponseType CryptoSession::GetTokenFromKeybox(std::string* token) {
OEMCryptoResult status;
WithOecReadLock("GetTokenFromKeybox", [&] {
M_TIME(
status =
OEMCrypto_GetKeyData(buf, &buf_size, requested_security_level_),
metrics_, oemcrypto_get_key_data_, status,
metrics::Pow2Bucket(buf_size));
M_TIME(status =
OEMCrypto_GetKeyData(buf, &buf_size, requested_security_level_),
metrics_, oemcrypto_get_key_data_, status,
metrics::Pow2Bucket(buf_size));
});
if (OEMCrypto_SUCCESS == status) {
token->swap(temp_buffer);
}
return MapOEMCryptoResult(
status, GET_TOKEN_FROM_KEYBOX_ERROR, "GetTokenFromKeybox");
return MapOEMCryptoResult(status, GET_TOKEN_FROM_KEYBOX_ERROR,
"GetTokenFromKeybox");
}
CdmResponseType CryptoSession::GetTokenFromOemCert(std::string* token) {
@@ -314,8 +310,8 @@ CdmResponseType CryptoSession::GetTokenFromOemCert(std::string* token) {
size_t buf_size = temp_buffer.size();
uint8_t* buf = reinterpret_cast<uint8_t*>(&temp_buffer[0]);
WithOecSessionLock("GetTokenFromOemCert", [&] {
status = OEMCrypto_GetOEMPublicCertificate(oec_session_id_, buf,
&buf_size);
status =
OEMCrypto_GetOEMPublicCertificate(oec_session_id_, buf, &buf_size);
});
metrics_->oemcrypto_get_oem_public_certificate_.Increment(status);
@@ -332,8 +328,8 @@ CdmResponseType CryptoSession::GetTokenFromOemCert(std::string* token) {
continue;
}
return MapOEMCryptoResult(
status, GET_TOKEN_FROM_OEM_CERT_ERROR, "GetTokenFromOemCert");
return MapOEMCryptoResult(status, GET_TOKEN_FROM_OEM_CERT_ERROR,
"GetTokenFromOemCert");
}
}
@@ -345,7 +341,8 @@ CdmResponseType CryptoSession::GetProvisioningToken(std::string* token) {
}
if (!IsInitialized()) {
metrics_->crypto_session_get_token_.Increment(CRYPTO_SESSION_NOT_INITIALIZED);
metrics_->crypto_session_get_token_.Increment(
CRYPTO_SESSION_NOT_INITIALIZED);
return CRYPTO_SESSION_NOT_INITIALIZED;
}
@@ -431,8 +428,8 @@ CdmResponseType CryptoSession::GetInternalDeviceUniqueId(
if (sts == OEMCrypto_ERROR_SHORT_BUFFER) {
id.resize(id_length);
WithOecReadLock("GetInternalDeviceUniqueId Attempt 2", [&] {
sts = OEMCrypto_GetDeviceID(&id[0], &id_length,
requested_security_level_);
sts =
OEMCrypto_GetDeviceID(&id[0], &id_length, requested_security_level_);
});
metrics_->oemcrypto_get_device_id_.Increment(sts);
}
@@ -451,8 +448,8 @@ CdmResponseType CryptoSession::GetInternalDeviceUniqueId(
device_id->assign(reinterpret_cast<char*>(&id[0]), id_length);
}
return MapOEMCryptoResult(
sts, GET_DEVICE_ID_ERROR, "GetInternalDeviceUniqueId");
return MapOEMCryptoResult(sts, GET_DEVICE_ID_ERROR,
"GetInternalDeviceUniqueId");
}
}
@@ -507,9 +504,8 @@ bool CryptoSession::GetApiVersion(SecurityLevel security_level,
return false;
}
WithOecReadLock("GetApiVersion", [&] {
*version = OEMCrypto_APIVersion(security_level);
});
WithOecReadLock("GetApiVersion",
[&] { *version = OEMCrypto_APIVersion(security_level); });
// Record the version into the metrics.
metrics_->oemcrypto_api_version_.Record(*version);
@@ -544,7 +540,7 @@ CdmResponseType CryptoSession::GetSystemIdInternal(uint32_t* system_id) {
if (status != NO_ERROR) return status;
if (token.size() < 2*sizeof(uint32_t)) {
if (token.size() < 2 * sizeof(uint32_t)) {
LOGE("CryptoSession::GetSystemIdInternal: Keybox token too small: %d",
token.size());
return KEYBOX_TOKEN_TOO_SHORT;
@@ -568,13 +564,15 @@ CdmResponseType CryptoSession::GetSystemIdInternal(uint32_t* system_id) {
return NO_ERROR;
// TODO(blueeyes): Support loading the system id from a pre-provisioned
// Drm certificate.
// TODO(blueeyes): Support loading the system id from a pre-provisioned
// Drm certificate.
} else if (pre_provision_token_type_ == kClientTokenDrmCert) {
return NO_ERROR;
} else {
LOGE("CryptoSession::GetSystemIdInternal: "
"Unsupported pre-provision token type %d", pre_provision_token_type_);
LOGE(
"CryptoSession::GetSystemIdInternal: "
"Unsupported pre-provision token type %d",
pre_provision_token_type_);
return UNKNOWN_CLIENT_TOKEN_TYPE;
}
}
@@ -647,9 +645,8 @@ CdmResponseType CryptoSession::Open(SecurityLevel requested_security_level) {
if (!IsInitialized()) return UNKNOWN_ERROR;
if (open_) return NO_ERROR;
CdmResponseType result =
GetProvisioningMethod(requested_security_level,
&pre_provision_token_type_);
CdmResponseType result = GetProvisioningMethod(requested_security_level,
&pre_provision_token_type_);
if (result != NO_ERROR) return result;
OEMCrypto_SESSION sid;
@@ -661,8 +658,7 @@ CdmResponseType CryptoSession::Open(SecurityLevel requested_security_level) {
if (sts != OEMCrypto_SUCCESS) {
WithStaticFieldReadLock(
"Open() reporting OEMCrypto_OpenSession Failure",
[&] {
"Open() reporting OEMCrypto_OpenSession Failure", [&] {
LOGE("OEMCrypto_Open failed: %d, open sessions: %ld, initialized: %d",
sts, session_count_, (int)initialized_);
});
@@ -757,9 +753,8 @@ void CryptoSession::Close() {
OEMCryptoResult close_sts;
bool update_usage_table = false;
WithOecWriteLock("Close", [&] {
close_sts = OEMCrypto_CloseSession(oec_session_id_);
});
WithOecWriteLock(
"Close", [&] { close_sts = OEMCrypto_CloseSession(oec_session_id_); });
metrics_->oemcrypto_close_session_.Increment(close_sts);
if (OEMCrypto_SUCCESS == close_sts) open_ = false;
update_usage_table = update_usage_table_after_close_session_;
@@ -816,9 +811,9 @@ CdmResponseType CryptoSession::LoadKeys(
}
LOGV("LoadKeys: id=%lu", oec_session_id_);
sts = key_session_->LoadKeys(
message, signature, mac_key_iv, mac_key, keys, provider_session_token,
&cipher_mode_, srm_requirement);
sts = key_session_->LoadKeys(message, signature, mac_key_iv, mac_key, keys,
provider_session_token, &cipher_mode_,
srm_requirement);
});
if (sts != OEMCrypto_SUCCESS) {
@@ -896,8 +891,7 @@ CdmResponseType CryptoSession::LoadCertificatePrivateKey(
LOGV("LoadDeviceRSAKey: id=%lu", oec_session_id_);
WithOecSessionLock(
"LoadCertificatePrivateKey() calling OEMCrypto_LoadDeviceRSAKey()",
[&] {
"LoadCertificatePrivateKey() calling OEMCrypto_LoadDeviceRSAKey()", [&] {
M_TIME(sts = OEMCrypto_LoadDeviceRSAKey(
oec_session_id_,
reinterpret_cast<const uint8_t*>(wrapped_key.data()),
@@ -905,8 +899,8 @@ CdmResponseType CryptoSession::LoadCertificatePrivateKey(
metrics_, oemcrypto_load_device_rsa_key_, sts);
});
return MapOEMCryptoResult(
sts, LOAD_DEVICE_RSA_KEY_ERROR, "LoadCertificatePrivateKey");
return MapOEMCryptoResult(sts, LOAD_DEVICE_RSA_KEY_ERROR,
"LoadCertificatePrivateKey");
}
CdmResponseType CryptoSession::RefreshKeys(const std::string& message,
@@ -937,16 +931,14 @@ CdmResponseType CryptoSession::RefreshKeys(const std::string& message,
if (refresh_sts == OEMCrypto_SUCCESS) return KEY_ADDED;
return MapOEMCryptoResult(
refresh_sts, REFRESH_KEYS_ERROR, "RefreshKeys");
return MapOEMCryptoResult(refresh_sts, REFRESH_KEYS_ERROR, "RefreshKeys");
}
CdmResponseType CryptoSession::SelectKey(const std::string& key_id,
CdmCipherMode cipher_mode) {
OEMCryptoResult sts;
WithOecSessionLock("SelectKey", [&] {
sts = key_session_->SelectKey(key_id, cipher_mode);
});
WithOecSessionLock(
"SelectKey", [&] { sts = key_session_->SelectKey(key_id, cipher_mode); });
switch (sts) {
case OEMCrypto_SUCCESS:
@@ -982,12 +974,11 @@ CdmResponseType CryptoSession::SelectKey(const std::string& key_id,
CdmResponseType CryptoSession::GenerateDerivedKeys(const std::string& message) {
OEMCryptoResult sts;
WithOecSessionLock("GenerateDerivedKeys without session_key", [&] {
sts = key_session_->GenerateDerivedKeys(message);
});
WithOecSessionLock("GenerateDerivedKeys without session_key",
[&] { sts = key_session_->GenerateDerivedKeys(message); });
return MapOEMCryptoResult(
sts, GENERATE_DERIVED_KEYS_ERROR_2, "GenerateDerivedKeys");
return MapOEMCryptoResult(sts, GENERATE_DERIVED_KEYS_ERROR_2,
"GenerateDerivedKeys");
}
CdmResponseType CryptoSession::GenerateDerivedKeys(
@@ -997,8 +988,8 @@ CdmResponseType CryptoSession::GenerateDerivedKeys(
sts = key_session_->GenerateDerivedKeys(message, session_key);
});
return MapOEMCryptoResult(
sts, GENERATE_DERIVED_KEYS_ERROR, "GenerateDerivedKeys");
return MapOEMCryptoResult(sts, GENERATE_DERIVED_KEYS_ERROR,
"GenerateDerivedKeys");
}
CdmResponseType CryptoSession::GenerateSignature(const std::string& message,
@@ -1016,15 +1007,14 @@ CdmResponseType CryptoSession::GenerateSignature(const std::string& message,
// The first attempt may fail due to buffer too short
for (int i = 0; i < 2; ++i) {
WithOecSessionLock("GenerateSignature", [&] {
M_TIME(sts = OEMCrypto_GenerateSignature(
oec_session_id_,
reinterpret_cast<const uint8_t*>(message.data()),
message.size(),
reinterpret_cast<uint8_t*>(
const_cast<char*>(signature->data())),
&length),
metrics_, oemcrypto_generate_signature_, sts,
metrics::Pow2Bucket(length));
M_TIME(
sts = OEMCrypto_GenerateSignature(
oec_session_id_, reinterpret_cast<const uint8_t*>(message.data()),
message.size(),
reinterpret_cast<uint8_t*>(const_cast<char*>(signature->data())),
&length),
metrics_, oemcrypto_generate_signature_, sts,
metrics::Pow2Bucket(length));
});
if (OEMCrypto_SUCCESS == sts) {
// Trim signature buffer and done
@@ -1039,8 +1029,7 @@ CdmResponseType CryptoSession::GenerateSignature(const std::string& message,
signature->resize(length);
}
return MapOEMCryptoResult(
sts, GENERATE_SIGNATURE_ERROR, "GenerateSignature");
return MapOEMCryptoResult(sts, GENERATE_SIGNATURE_ERROR, "GenerateSignature");
}
CdmResponseType CryptoSession::GenerateRsaSignature(const std::string& message,
@@ -1059,15 +1048,14 @@ CdmResponseType CryptoSession::GenerateRsaSignature(const std::string& message,
// The first attempt may fail due to buffer too short
for (int i = 0; i < 2; ++i) {
WithOecSessionLock("GenerateRsaSignature", [&] {
M_TIME(sts = OEMCrypto_GenerateRSASignature(
oec_session_id_,
reinterpret_cast<const uint8_t*>(message.data()),
message.size(),
reinterpret_cast<uint8_t*>(
const_cast<char*>(signature->data())),
&length, kSign_RSASSA_PSS),
metrics_, oemcrypto_generate_rsa_signature_, sts,
metrics::Pow2Bucket(length));
M_TIME(
sts = OEMCrypto_GenerateRSASignature(
oec_session_id_, reinterpret_cast<const uint8_t*>(message.data()),
message.size(),
reinterpret_cast<uint8_t*>(const_cast<char*>(signature->data())),
&length, kSign_RSASSA_PSS),
metrics_, oemcrypto_generate_rsa_signature_, sts,
metrics::Pow2Bucket(length));
});
if (OEMCrypto_SUCCESS == sts) {
@@ -1083,8 +1071,8 @@ CdmResponseType CryptoSession::GenerateRsaSignature(const std::string& message,
signature->resize(length);
}
return MapOEMCryptoResult(
sts, RSA_SIGNATURE_GENERATION_ERROR, "OEMCrypto_GenerateRSASignature");
return MapOEMCryptoResult(sts, RSA_SIGNATURE_GENERATION_ERROR,
"OEMCrypto_GenerateRSASignature");
}
CdmResponseType CryptoSession::Decrypt(const CdmDecryptionParameters& params) {
@@ -1125,10 +1113,9 @@ CdmResponseType CryptoSession::Decrypt(const CdmDecryptionParameters& params) {
params.subsample_flags ==
(OEMCrypto_FirstSubsample | OEMCrypto_LastSubsample)) {
WithOecSessionLock("Decrypt() calling CopyBuffer", [&] {
M_TIME(sts = OEMCrypto_CopyBuffer(oec_session_id_, params.encrypt_buffer,
params.encrypt_length,
&buffer_descriptor,
params.subsample_flags),
M_TIME(sts = OEMCrypto_CopyBuffer(
oec_session_id_, params.encrypt_buffer, params.encrypt_length,
&buffer_descriptor, params.subsample_flags),
metrics_, oemcrypto_copy_buffer_, sts,
metrics::Pow2Bucket(params.encrypt_length));
});
@@ -1157,8 +1144,8 @@ CdmResponseType CryptoSession::Decrypt(const CdmDecryptionParameters& params) {
}
WithOecSessionLock("Decrypt() calling key_session_->Decrypt()", [&] {
sts = key_session_->Decrypt(params, buffer_descriptor,
pattern_descriptor);
sts =
key_session_->Decrypt(params, buffer_descriptor, pattern_descriptor);
});
if (sts == OEMCrypto_ERROR_BUFFER_TOO_LARGE) {
@@ -1232,8 +1219,7 @@ bool CryptoSession::UsageInformationSupport(SecurityLevel security_level,
}
CdmResponseType CryptoSession::UpdateUsageInformation() {
LOGV("CryptoSession::UpdateUsageInformation: id=%lu",
oec_session_id_);
LOGV("CryptoSession::UpdateUsageInformation: id=%lu", oec_session_id_);
if (!IsInitialized()) return UNKNOWN_ERROR;
if (usage_table_header_ != NULL) {
@@ -1242,9 +1228,8 @@ CdmResponseType CryptoSession::UpdateUsageInformation() {
}
OEMCryptoResult status;
WithOecWriteLock("UpdateUsageInformation", [&] {
status = OEMCrypto_UpdateUsageTable();
});
WithOecWriteLock("UpdateUsageInformation",
[&] { status = OEMCrypto_UpdateUsageTable(); });
metrics_->oemcrypto_update_usage_table_.Increment(status);
if (status != OEMCrypto_SUCCESS) {
LOGE("CryptoSession::UpdateUsageInformation: error=%ld", status);
@@ -1263,8 +1248,8 @@ CdmResponseType CryptoSession::DeactivateUsageInformation(
// TODO(fredgc or rfrias): make sure oec_session_id_ is valid.
OEMCryptoResult status;
WithOecWriteLock("DeactivateUsageInformation", [&] {
status = OEMCrypto_DeactivateUsageEntry(
oec_session_id_, pst, provider_session_token.length());
status = OEMCrypto_DeactivateUsageEntry(oec_session_id_, pst,
provider_session_token.length());
});
metrics_->oemcrypto_deactivate_usage_entry_.Increment(status);
@@ -1303,15 +1288,15 @@ CdmResponseType CryptoSession::GenerateUsageReport(
size_t usage_length = 0;
OEMCryptoResult status;
WithOecWriteLock("GenerateUsageReport Attempt 1", [&] {
status = OEMCrypto_ReportUsage(
oec_session_id_, pst, provider_session_token.length(), NULL,
&usage_length);
status = OEMCrypto_ReportUsage(oec_session_id_, pst,
provider_session_token.length(), NULL,
&usage_length);
});
metrics_->oemcrypto_report_usage_.Increment(status);
if (status != OEMCrypto_SUCCESS && status != OEMCrypto_ERROR_SHORT_BUFFER) {
return MapOEMCryptoResult(
status, GENERATE_USAGE_REPORT_ERROR, "GenerateUsageReport");
return MapOEMCryptoResult(status, GENERATE_USAGE_REPORT_ERROR,
"GenerateUsageReport");
}
std::vector<uint8_t> buffer(usage_length);
@@ -1324,8 +1309,8 @@ CdmResponseType CryptoSession::GenerateUsageReport(
metrics_->oemcrypto_report_usage_.Increment(status);
if (status != OEMCrypto_SUCCESS) {
return MapOEMCryptoResult(
status, GENERATE_USAGE_REPORT_ERROR, "OEMCrypto_ReportUsage");
return MapOEMCryptoResult(status, GENERATE_USAGE_REPORT_ERROR,
"OEMCrypto_ReportUsage");
}
if (usage_length != buffer.size()) {
@@ -1458,9 +1443,8 @@ CdmResponseType CryptoSession::DeleteMultipleUsageInformation(
CdmResponseType CryptoSession::DeleteAllUsageReports() {
LOGV("DeleteAllUsageReports");
OEMCryptoResult status;
WithOecWriteLock("DeleteAllUsageReports", [&] {
status = OEMCrypto_DeleteOldUsageTable();
});
WithOecWriteLock("DeleteAllUsageReports",
[&] { status = OEMCrypto_DeleteOldUsageTable(); });
metrics_->oemcrypto_delete_usage_table_.Increment(status);
if (OEMCrypto_SUCCESS != status) {
LOGE(
@@ -1513,12 +1497,9 @@ bool CryptoSession::SetDestinationBufferType() {
}
CdmResponseType CryptoSession::RewrapCertificate(
const std::string& signed_message,
const std::string& signature,
const std::string& nonce,
const std::string& private_key,
const std::string& iv,
const std::string& wrapping_key,
const std::string& signed_message, const std::string& signature,
const std::string& nonce, const std::string& private_key,
const std::string& iv, const std::string& wrapping_key,
std::string* wrapped_private_key) {
LOGV("CryptoSession::RewrapCertificate, session id=%lu", oec_session_id_);
@@ -1540,12 +1521,9 @@ CdmResponseType CryptoSession::RewrapCertificate(
}
CdmResponseType CryptoSession::RewrapDeviceRSAKey(
const std::string& message,
const std::string& signature,
const std::string& nonce,
const std::string& enc_rsa_key,
const std::string& rsa_key_iv,
std::string* wrapped_rsa_key) {
const std::string& message, const std::string& signature,
const std::string& nonce, const std::string& enc_rsa_key,
const std::string& rsa_key_iv, std::string* wrapped_rsa_key) {
LOGV("CryptoSession::RewrapDeviceRSAKey, session id=%lu", oec_session_id_);
const uint8_t* signed_msg = reinterpret_cast<const uint8_t*>(message.data());
@@ -1573,37 +1551,33 @@ CdmResponseType CryptoSession::RewrapDeviceRSAKey(
});
if (status != OEMCrypto_ERROR_SHORT_BUFFER) {
return MapOEMCryptoResult(
status, REWRAP_DEVICE_RSA_KEY_ERROR, "RewrapDeviceRSAKey");
return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_ERROR,
"RewrapDeviceRSAKey");
}
wrapped_rsa_key->resize(wrapped_rsa_key_length);
WithOecSessionLock("RewrapDeviceRSAKey Attempt 2", [&] {
M_TIME(status = OEMCrypto_RewrapDeviceRSAKey(
oec_session_id_, signed_msg, message.size(),
reinterpret_cast<const uint8_t*>(signature.data()),
signature.size(), msg_nonce, msg_rsa_key, enc_rsa_key.size(),
msg_rsa_key_iv,
reinterpret_cast<uint8_t*>(&(*wrapped_rsa_key)[0]),
&wrapped_rsa_key_length),
metrics_, oemcrypto_rewrap_device_rsa_key_, status);
M_TIME(
status = OEMCrypto_RewrapDeviceRSAKey(
oec_session_id_, signed_msg, message.size(),
reinterpret_cast<const uint8_t*>(signature.data()),
signature.size(), msg_nonce, msg_rsa_key, enc_rsa_key.size(),
msg_rsa_key_iv, reinterpret_cast<uint8_t*>(&(*wrapped_rsa_key)[0]),
&wrapped_rsa_key_length),
metrics_, oemcrypto_rewrap_device_rsa_key_, status);
});
wrapped_rsa_key->resize(wrapped_rsa_key_length);
return MapOEMCryptoResult(
status, REWRAP_DEVICE_RSA_KEY_ERROR, "RewrapDeviceRSAKey");
return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_ERROR,
"RewrapDeviceRSAKey");
}
CdmResponseType CryptoSession::RewrapDeviceRSAKey30(
const std::string& message,
const std::string& nonce,
const std::string& private_key,
const std::string& iv,
const std::string& wrapping_key,
std::string* wrapped_private_key) {
LOGV("CryptoSession::RewrapDeviceRSAKey30, session id=%lu",
oec_session_id_);
const std::string& message, const std::string& nonce,
const std::string& private_key, const std::string& iv,
const std::string& wrapping_key, std::string* wrapped_private_key) {
LOGV("CryptoSession::RewrapDeviceRSAKey30, session id=%lu", oec_session_id_);
const uint8_t* signed_msg = reinterpret_cast<const uint8_t*>(message.data());
const uint8_t* msg_private_key = NULL;
@@ -1623,38 +1597,32 @@ CdmResponseType CryptoSession::RewrapDeviceRSAKey30(
size_t wrapped_private_key_length = 0;
OEMCryptoResult status;
WithOecSessionLock("RewrapDeviceRSAKey30 Attempt 1", [&] {
M_TIME(
status = OEMCrypto_RewrapDeviceRSAKey30(
oec_session_id_, msg_nonce, msg_wrapping_key, wrapping_key.size(),
msg_private_key, private_key.size(), msg_iv, NULL,
&wrapped_private_key_length),
metrics_,
oemcrypto_rewrap_device_rsa_key_30_,
status);
M_TIME(status = OEMCrypto_RewrapDeviceRSAKey30(
oec_session_id_, msg_nonce, msg_wrapping_key,
wrapping_key.size(), msg_private_key, private_key.size(), msg_iv,
NULL, &wrapped_private_key_length),
metrics_, oemcrypto_rewrap_device_rsa_key_30_, status);
});
if (status != OEMCrypto_ERROR_SHORT_BUFFER) {
return MapOEMCryptoResult(
status, REWRAP_DEVICE_RSA_KEY_30_ERROR, "RewrapDeviceRSAKey30");
return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_30_ERROR,
"RewrapDeviceRSAKey30");
}
wrapped_private_key->resize(wrapped_private_key_length);
WithOecSessionLock("RewrapDeviceRSAKey30 Attempt 2", [&] {
M_TIME(
status = OEMCrypto_RewrapDeviceRSAKey30(
oec_session_id_, msg_nonce, msg_wrapping_key, wrapping_key.size(),
msg_private_key, private_key.size(), msg_iv,
reinterpret_cast<uint8_t*>(&(*wrapped_private_key)[0]),
&wrapped_private_key_length),
metrics_,
oemcrypto_rewrap_device_rsa_key_30_,
status);
M_TIME(status = OEMCrypto_RewrapDeviceRSAKey30(
oec_session_id_, msg_nonce, msg_wrapping_key,
wrapping_key.size(), msg_private_key, private_key.size(), msg_iv,
reinterpret_cast<uint8_t*>(&(*wrapped_private_key)[0]),
&wrapped_private_key_length),
metrics_, oemcrypto_rewrap_device_rsa_key_30_, status);
});
wrapped_private_key->resize(wrapped_private_key_length);
return MapOEMCryptoResult(
status, REWRAP_DEVICE_RSA_KEY_30_ERROR, "RewrapDeviceRSAKey30");
return MapOEMCryptoResult(status, REWRAP_DEVICE_RSA_KEY_30_ERROR,
"RewrapDeviceRSAKey30");
}
CdmResponseType CryptoSession::GetHdcpCapabilities(HdcpCapability* current,
@@ -1694,8 +1662,8 @@ CdmResponseType CryptoSession::GetHdcpCapabilities(SecurityLevel security_level,
metrics_->oemcrypto_max_hdcp_capability_.SetError(status);
}
return MapOEMCryptoResult(
status, GET_HDCP_CAPABILITY_FAILED, "GetHDCPCapability");
return MapOEMCryptoResult(status, GET_HDCP_CAPABILITY_FAILED,
"GetHDCPCapability");
}
bool CryptoSession::GetSupportedCertificateTypes(
@@ -1726,17 +1694,15 @@ CdmResponseType CryptoSession::GetRandom(size_t data_length,
return PARAMETER_NULL;
}
OEMCryptoResult sts;
WithOecReadLock("GetRandom", [&] {
sts = OEMCrypto_GetRandom(random_data, data_length);
});
WithOecReadLock("GetRandom",
[&] { sts = OEMCrypto_GetRandom(random_data, data_length); });
metrics_->oemcrypto_get_random_.Increment(sts);
return MapOEMCryptoResult(sts, RANDOM_GENERATION_ERROR, "GetRandom");
}
CdmResponseType CryptoSession::GetNumberOfOpenSessions(
SecurityLevel security_level,
size_t* count) {
SecurityLevel security_level, size_t* count) {
LOGV("GetNumberOfOpenSessions");
if (!IsInitialized()) {
LOGW("CryptoSession::GetNumberOfOpenSessions: not initialized");
@@ -1760,13 +1726,12 @@ CdmResponseType CryptoSession::GetNumberOfOpenSessions(
metrics_->oemcrypto_number_of_open_sessions_.SetError(status);
}
return MapOEMCryptoResult(
status, GET_NUMBER_OF_OPEN_SESSIONS_ERROR, "GetNumberOfOpenSessions");
return MapOEMCryptoResult(status, GET_NUMBER_OF_OPEN_SESSIONS_ERROR,
"GetNumberOfOpenSessions");
}
CdmResponseType CryptoSession::GetMaxNumberOfSessions(
SecurityLevel security_level,
size_t* max) {
SecurityLevel security_level, size_t* max) {
LOGV("GetMaxNumberOfSessions");
if (!IsInitialized()) {
LOGW("CryptoSession::GetMaxNumberOfSessions: not initialized");
@@ -1811,21 +1776,21 @@ CdmResponseType CryptoSession::GetSrmVersion(uint16_t* srm_version) {
// SRM is an optional feature. Whether it is implemented is up to the
// discretion of OEMs
if (status == OEMCrypto_ERROR_NOT_IMPLEMENTED) {
LOGV("CryptoSession::GetSrmVersion: OEMCrypto_GetCurrentSRMVersion not "
"implemented");
LOGV(
"CryptoSession::GetSrmVersion: OEMCrypto_GetCurrentSRMVersion not "
"implemented");
return NOT_IMPLEMENTED_ERROR;
}
return MapOEMCryptoResult(
status, GET_SRM_VERSION_ERROR, "GetCurrentSRMVersion");
return MapOEMCryptoResult(status, GET_SRM_VERSION_ERROR,
"GetCurrentSRMVersion");
}
bool CryptoSession::IsSrmUpdateSupported() {
LOGV("IsSrmUpdateSupported");
if (!IsInitialized()) return false;
return WithOecReadLock("IsSrmUpdateSupported", [&] {
return OEMCrypto_IsSRMUpdateSupported();
});
return WithOecReadLock("IsSrmUpdateSupported",
[&] { return OEMCrypto_IsSRMUpdateSupported(); });
}
CdmResponseType CryptoSession::LoadSrm(const std::string& srm) {
@@ -1838,8 +1803,8 @@ CdmResponseType CryptoSession::LoadSrm(const std::string& srm) {
OEMCryptoResult status;
WithOecWriteLock("LoadSrm", [&] {
status = OEMCrypto_LoadSRM(
reinterpret_cast<const uint8_t*>(srm.data()), srm.size());
status = OEMCrypto_LoadSRM(reinterpret_cast<const uint8_t*>(srm.data()),
srm.size());
});
return MapOEMCryptoResult(status, LOAD_SRM_ERROR, "LoadSRM");
@@ -1938,9 +1903,8 @@ uint32_t CryptoSession::IsDecryptHashSupported(SecurityLevel security_level) {
return secure_decrypt_support;
}
CdmResponseType CryptoSession::SetDecryptHash(
uint32_t frame_number,
const std::string& hash) {
CdmResponseType CryptoSession::SetDecryptHash(uint32_t frame_number,
const std::string& hash) {
LOGV("SetDecryptHash");
OEMCryptoResult sts;
WithOecSessionLock("SetDecryptHash", [&] {
@@ -2486,9 +2450,9 @@ CdmResponseType CryptoSession::ShrinkUsageTableHeader(
size_t usage_table_header_len = 0;
OEMCryptoResult result;
WithOecWriteLock("ShrinkUsageTableHeader Attempt 1", [&] {
result = OEMCrypto_ShrinkUsageTableHeader(
requested_security_level_, new_entry_count, NULL,
&usage_table_header_len);
result = OEMCrypto_ShrinkUsageTableHeader(requested_security_level_,
new_entry_count, NULL,
&usage_table_header_len);
metrics_->oemcrypto_shrink_usage_table_header_.Increment(result);
});
@@ -2522,8 +2486,8 @@ CdmResponseType CryptoSession::MoveUsageEntry(uint32_t new_entry_number) {
metrics_->oemcrypto_move_entry_.Increment(result);
});
return MapOEMCryptoResult(
result, MOVE_USAGE_ENTRY_UNKNOWN_ERROR, "MoveUsageEntry");
return MapOEMCryptoResult(result, MOVE_USAGE_ENTRY_UNKNOWN_ERROR,
"MoveUsageEntry");
}
bool CryptoSession::CreateOldUsageEntry(
@@ -2592,8 +2556,8 @@ CdmResponseType CryptoSession::CopyOldUsageEntry(
metrics_->oemcrypto_copy_old_usage_entry_.Increment(result);
});
return MapOEMCryptoResult(
result, COPY_OLD_USAGE_ENTRY_UNKNOWN_ERROR, "CopyOldUsageEntry");
return MapOEMCryptoResult(result, COPY_OLD_USAGE_ENTRY_UNKNOWN_ERROR,
"CopyOldUsageEntry");
}
bool CryptoSession::GetAnalogOutputCapabilities(bool* can_support_output,

View File

@@ -5,6 +5,7 @@
#include "device_files.h"
#include <string.h>
#include <string>
#include "file_store.h"
@@ -31,20 +32,20 @@ using video_widevine_client::sdk::UsageTableInfo;
using video_widevine_client::sdk::UsageTableInfo_UsageEntryInfo;
using video_widevine_client::sdk::
UsageTableInfo_UsageEntryInfo_UsageEntryStorage_LICENSE;
using video_widevine_client::sdk::
UsageTableInfo_UsageEntryInfo_UsageEntryStorage_USAGE_INFO;
using video_widevine_client::sdk::
UsageTableInfo_UsageEntryInfo_UsageEntryStorage_UNKNOWN;
using video_widevine_client::sdk::
UsageTableInfo_UsageEntryInfo_UsageEntryStorage_USAGE_INFO;
using video_widevine::SignedDrmDeviceCertificate;
using video_widevine::DrmDeviceCertificate;
using video_widevine::SignedDrmDeviceCertificate;
#define RETURN_FALSE_IF_NULL(PARAM) \
if (PARAM == nullptr) { \
LOGE("|PARAM| not provided"); \
*result = kParameterNull; \
return false; \
}
if (PARAM == nullptr) { \
LOGE("|PARAM| not provided"); \
*result = kParameterNull; \
return false; \
}
namespace {
@@ -107,8 +108,8 @@ bool DeviceFiles::StoreCertificate(const std::string& certificate,
std::string serialized_file;
file.SerializeToString(&serialized_file);
return
StoreFileWithHash(GetCertificateFileName(), serialized_file) == kNoError;
return StoreFileWithHash(GetCertificateFileName(), serialized_file) ==
kNoError;
}
bool DeviceFiles::RetrieveCertificate(std::string* certificate,
@@ -161,8 +162,9 @@ bool DeviceFiles::ExtractDeviceInfo(const std::string& device_certificate,
SignedDrmDeviceCertificate signed_drm_device_certificate;
if (!signed_drm_device_certificate.ParseFromString(device_certificate) ||
!signed_drm_device_certificate.has_drm_certificate()) {
LOGE("DeviceFiles::ExtractDeviceInfo: fails parsing signed drm device "
"certificate.");
LOGE(
"DeviceFiles::ExtractDeviceInfo: fails parsing signed drm device "
"certificate.");
return false;
}
DrmDeviceCertificate drm_device_certificate;
@@ -170,8 +172,9 @@ bool DeviceFiles::ExtractDeviceInfo(const std::string& device_certificate,
signed_drm_device_certificate.drm_certificate()) ||
(drm_device_certificate.type() !=
video_widevine::DrmDeviceCertificate::DRM_USER_DEVICE)) {
LOGE("DeviceFiles::ExtractDeviceInfo: fails parsing drm device "
"certificate message.");
LOGE(
"DeviceFiles::ExtractDeviceInfo: fails parsing drm device "
"certificate message.");
return false;
}
if (serial_number != NULL) {
@@ -209,10 +212,8 @@ bool DeviceFiles::StoreLicense(
const CdmKeyResponse& license_renewal,
const std::string& release_server_url, int64_t playback_start_time,
int64_t last_playback_time, int64_t grace_period_end_time,
const CdmAppParameterMap& app_parameters,
const CdmUsageEntry& usage_entry,
const uint32_t usage_entry_number,
ResponseType* result) {
const CdmAppParameterMap& app_parameters, const CdmUsageEntry& usage_entry,
const uint32_t usage_entry_number, ResponseType* result) {
if (result == nullptr) {
LOGE("DeviceFiles::StoreLicense: |result| not provided");
return false;
@@ -492,8 +493,7 @@ bool DeviceFiles::StoreUsageInfo(const std::string& provider_session_token,
}
bool DeviceFiles::ListUsageIds(
const std::string& app_id,
std::vector<std::string>* ksids,
const std::string& app_id, std::vector<std::string>* ksids,
std::vector<std::string>* provider_session_tokens) {
if (!initialized_) {
LOGW("DeviceFiles::ListUsageIds: not initialized");
@@ -718,12 +718,9 @@ bool DeviceFiles::RetrieveUsageInfo(const std::string& usage_info_file_name,
}
bool DeviceFiles::RetrieveUsageInfoByKeySetId(
const std::string& usage_info_file_name,
const std::string& key_set_id,
std::string* provider_session_token,
CdmKeyMessage* license_request,
CdmKeyResponse* license_response,
std::string* usage_entry,
const std::string& usage_info_file_name, const std::string& key_set_id,
std::string* provider_session_token, CdmKeyMessage* license_request,
CdmKeyResponse* license_response, std::string* usage_entry,
uint32_t* usage_entry_number) {
if (!initialized_) {
LOGW("DeviceFiles::RetrieveUsageInfoByKeySetId: not initialized");
@@ -798,7 +795,6 @@ bool DeviceFiles::UpdateUsageInfo(const std::string& usage_info_file_name,
return false;
}
if (RetrieveHashedFile(usage_info_file_name, &file) != kNoError) {
LOGW("DeviceFiles::UpdateUsageInfo: Unable to retrieve file");
return false;
@@ -818,8 +814,8 @@ bool DeviceFiles::UpdateUsageInfo(const std::string& usage_info_file_name,
std::string serialized_file;
file.SerializeToString(&serialized_file);
return
StoreFileWithHash(usage_info_file_name, serialized_file) == kNoError;
return StoreFileWithHash(usage_info_file_name, serialized_file) ==
kNoError;
}
}
@@ -860,7 +856,7 @@ bool DeviceFiles::RetrieveUsageInfo(const std::string& usage_info_file_name,
(*usage_data)[i].key_set_id = file.usage_info().sessions(i).key_set_id();
(*usage_data)[i].usage_entry = file.usage_info().sessions(i).usage_entry();
(*usage_data)[i].usage_entry_number =
file.usage_info().sessions(i).usage_entry_number();
file.usage_info().sessions(i).usage_entry_number();
}
return true;
@@ -928,8 +924,7 @@ bool DeviceFiles::ListUsageInfoFiles(
std::string* name = &filenames[i];
std::size_t pos_prefix = name->find(kUsageInfoFileNamePrefix);
std::size_t pos_suffix = name->find(kUsageInfoFileNameExt);
if (pos_prefix == std::string::npos ||
pos_suffix == std::string::npos) {
if (pos_prefix == std::string::npos || pos_suffix == std::string::npos) {
// Skip this file - extension does not match
continue;
}
@@ -1080,8 +1075,8 @@ bool DeviceFiles::StoreUsageTableInfo(
std::string serialized_file;
file.SerializeToString(&serialized_file);
return
StoreFileWithHash(GetUsageTableFileName(), serialized_file) == kNoError;
return StoreFileWithHash(GetUsageTableFileName(), serialized_file) ==
kNoError;
}
bool DeviceFiles::RetrieveUsageTableInfo(
@@ -1160,8 +1155,7 @@ bool DeviceFiles::DeleteUsageTableInfo() {
}
DeviceFiles::ResponseType DeviceFiles::StoreFileWithHash(
const std::string& name,
const std::string& serialized_file) {
const std::string& name, const std::string& serialized_file) {
std::string hash = Sha256Hash(serialized_file);
// Fill in hashed file data
@@ -1176,8 +1170,7 @@ DeviceFiles::ResponseType DeviceFiles::StoreFileWithHash(
}
DeviceFiles::ResponseType DeviceFiles::StoreFileRaw(
const std::string& name,
const std::string& serialized_file) {
const std::string& name, const std::string& serialized_file) {
std::string path;
if (!Properties::GetDeviceFilesBasePath(security_level_, &path)) {
LOGW("DeviceFiles::StoreFileRaw: Unable to get base path");
@@ -1335,9 +1328,7 @@ std::string DeviceFiles::GetCertificateFileName() {
return kCertificateFileName;
}
std::string DeviceFiles::GetUsageTableFileName() {
return kUsageTableFileName;
}
std::string DeviceFiles::GetUsageTableFileName() { return kUsageTableFileName; }
std::string DeviceFiles::GetHlsAttributesFileNameExtension() {
return kHlsAttributesFileNameExt;

View File

@@ -8,7 +8,6 @@
#include "crypto_session.h"
#include "log.h"
namespace wvcdm {
EntitlementKeySession::EntitlementKeySession(CryptoSessionId oec_session_id,
metrics::CryptoMetrics* metrics)
@@ -51,8 +50,8 @@ OEMCryptoResult EntitlementKeySession::SelectKey(const std::string& key_id,
}
CryptoKey entitled_content_key = entitled_keys_[key_id];
if (current_loaded_content_keys_[entitled_content_key
.entitlement_key_id()] != key_id) {
if (current_loaded_content_keys_[entitled_content_key.entitlement_key_id()] !=
key_id) {
// Before the key can be selected, it must be loaded under its associated
// entitlement key. This could, in theory, be done ahead of time during
// LoadEntitledContentKeys(), but OEMCrypto v14 only supports one content

View File

@@ -5,6 +5,7 @@
#include "initialization_data.h"
#include <string.h>
#include <string>
#include "buffer_reader.h"
@@ -134,7 +135,8 @@ bool InitializationData::SelectWidevinePssh(const CdmInitData& init_data,
if (!pssh.ParseFromString(pssh_payloads[i])) {
LOGE(
"InitializationData::SelectWidevinePssh: Unable to parse PSSH data "
"%lu into a protobuf.", i);
"%lu into a protobuf.",
i);
continue;
}
if (pssh.type() == WidevinePsshData_Type_ENTITLED_KEY) {
@@ -164,8 +166,8 @@ bool InitializationData::SelectWidevinePssh(const CdmInitData& init_data,
// 4 byte size of PSSH data, exclusive. (N)
// N byte PSSH data.
bool InitializationData::ExtractWidevinePsshs(
const CdmInitData& init_data, std::vector<CdmInitData>* psshs) {
bool InitializationData::ExtractWidevinePsshs(const CdmInitData& init_data,
std::vector<CdmInitData>* psshs) {
if (psshs == NULL) {
LOGE("InitializationData::ExtractWidevinePsshs: NULL psshs parameter");
return false;
@@ -173,7 +175,8 @@ bool InitializationData::ExtractWidevinePsshs(
psshs->clear();
psshs->reserve(2); // We expect 1 or 2 Widevine PSSHs
const uint8_t* data_start = reinterpret_cast<const uint8_t*>(init_data.data());
const uint8_t* data_start =
reinterpret_cast<const uint8_t*>(init_data.data());
BufferReader reader(data_start, init_data.length());
while (!reader.IsEOF()) {
@@ -243,8 +246,9 @@ bool InitializationData::ExtractWidevinePsshs(
// Checks if the given reader contains a Widevine PSSH. If so, it extracts the
// data from the box. Returns true if a PSSH was extracted, false if there was
// an error or if the data is not a Widevine PSSH.
bool InitializationData::ExtractWidevinePsshData(
const uint8_t* data, size_t length, CdmInitData* output) {
bool InitializationData::ExtractWidevinePsshData(const uint8_t* data,
size_t length,
CdmInitData* output) {
BufferReader reader(data, length);
// Read the 32-bit size only so we can check if we need to expect a 64-bit
@@ -267,8 +271,7 @@ bool InitializationData::ExtractWidevinePsshData(
return false;
}
if (memcmp(&atom_type[0], "pssh", 4) != 0) {
LOGV(
"InitializationData::ExtractWidevinePsshData: Atom type is not PSSH.");
LOGV("InitializationData::ExtractWidevinePsshData: Atom type is not PSSH.");
return false;
}
@@ -313,9 +316,8 @@ bool InitializationData::ExtractWidevinePsshData(
"system ID.");
return false;
}
if (memcmp(&system_id[0],
kWidevineSystemId,
sizeof(kWidevineSystemId)) != 0) {
if (memcmp(&system_id[0], kWidevineSystemId, sizeof(kWidevineSystemId)) !=
0) {
LOGV(
"InitializationData::ExtractWidevinePsshData: Found a non-Widevine "
"PSSH.");

View File

@@ -411,9 +411,8 @@ CdmResponseType CdmLicense::PrepareKeyUpdateRequest(
license_request.set_request_time(clock_->GetCurrentTime());
if (renew_with_client_id_) {
CdmResponseType status =
PrepareClientId(app_parameters, provider_client_token_,
&license_request);
CdmResponseType status = PrepareClientId(
app_parameters, provider_client_token_, &license_request);
if (NO_ERROR != status) return status;
}
@@ -567,9 +566,8 @@ CdmResponseType CdmLicense::HandleKeyResponse(
LOGE("CdmLicense::HandleKeyResponse: no session keys present");
return SESSION_KEYS_NOT_FOUND;
}
CdmResponseType status =
crypto_session_->GenerateDerivedKeys(key_request_,
signed_response.session_key());
CdmResponseType status = crypto_session_->GenerateDerivedKeys(
key_request_, signed_response.session_key());
if (status != NO_ERROR) return status;
@@ -726,10 +724,9 @@ CdmResponseType CdmLicense::HandleKeyUpdateResponse(
std::vector<CryptoKey> key_array = ExtractContentKeys(license);
CdmResponseType status =
crypto_session_->RefreshKeys(signed_response.msg(),
signed_response.signature(),
key_array.size(), &key_array[0]);
CdmResponseType status = crypto_session_->RefreshKeys(
signed_response.msg(), signed_response.signature(), key_array.size(),
&key_array[0]);
if (status == KEY_ADDED) {
policy_engine_->UpdateLicense(license);
@@ -983,8 +980,7 @@ CdmResponseType CdmLicense::HandleKeyErrorResponse(
CdmResponseType CdmLicense::PrepareClientId(
const CdmAppParameterMap& app_parameters,
const std::string& provider_client_token,
LicenseRequest* license_request) {
const std::string& provider_client_token, LicenseRequest* license_request) {
wvcdm::ClientIdentification id;
CdmResponseType status = id.Init(client_token_, device_id_, crypto_session_);
if (status != NO_ERROR) return status;

View File

@@ -9,7 +9,9 @@
// oemcrypto_adapter_static.cpp, but not both.
//
// clang-format off
#include "oemcrypto_adapter.h"
// clang-format on
#include <dlfcn.h>
#include <stdio.h>
@@ -34,12 +36,12 @@
#include "wv_cdm_constants.h"
using namespace wvoec3;
using wvcdm::kLevelDefault;
using wvcdm::kLevel3;
using wvcdm::kLevelDefault;
namespace {
static const size_t kMaxGenericEncryptChunkSize = 100*1024;
static const size_t kMaxGenericEncryptChunkSize = 100 * 1024;
const OEMCryptoResult kOemCryptoResultVendorSpecificError1 =
static_cast<OEMCryptoResult>(10008);
@@ -130,10 +132,9 @@ typedef OEMCryptoResult (*L1_DecryptCENC_t)(
bool is_encrypted, const uint8_t* iv, size_t offset,
OEMCrypto_DestBufferDesc* out_buffer,
const OEMCrypto_CENCEncryptPatternDesc* pattern, uint8_t subsample_flags);
typedef OEMCryptoResult (*L1_CopyBuffer_V14_t)(const uint8_t* data_addr,
size_t data_length,
OEMCrypto_DestBufferDesc* out_buffer,
uint8_t subsample_flags);
typedef OEMCryptoResult (*L1_CopyBuffer_V14_t)(
const uint8_t* data_addr, size_t data_length,
OEMCrypto_DestBufferDesc* out_buffer, uint8_t subsample_flags);
typedef OEMCryptoResult (*L1_CopyBuffer_t)(OEMCrypto_SESSION session,
const uint8_t* data_addr,
size_t data_length,
@@ -146,8 +147,8 @@ typedef OEMCryptoResult (*L1_WrapKeybox_t)(const uint8_t* keybox,
const uint8_t* transportKey,
size_t transportKeyLength);
typedef OEMCryptoResult (*L1_InstallKeyboxOrOEMCert_t)(const uint8_t* keybox,
size_t keyBoxLength);
typedef OEMCryptoResult (*L1_LoadTestKeybox_t)(const uint8_t *buffer,
size_t keyBoxLength);
typedef OEMCryptoResult (*L1_LoadTestKeybox_t)(const uint8_t* buffer,
size_t length);
typedef OEMCryptoResult (*L1_LoadTestKeybox_V13_t)();
typedef OEMCryptoResult (*L1_IsKeyboxOrOEMCertValid_t)();
@@ -213,8 +214,7 @@ typedef OEMCryptoResult (*L1_DeactivateUsageEntry_V12_t)(const uint8_t* pst,
size_t pst_length);
typedef OEMCryptoResult (*L1_ReportUsage_t)(OEMCrypto_SESSION session,
const uint8_t* pst,
size_t pst_length,
uint8_t* buffer,
size_t pst_length, uint8_t* buffer,
size_t* buffer_length);
typedef OEMCryptoResult (*L1_DeleteUsageEntry_t)(
OEMCrypto_SESSION session, const uint8_t* pst, size_t pst_length,
@@ -225,19 +225,14 @@ typedef OEMCryptoResult (*L1_ForceDeleteUsageEntry_t)(const uint8_t* pst,
typedef OEMCryptoResult (*L1_DeleteOldUsageTable_t)();
typedef OEMCrypto_ProvisioningMethod (*L1_GetProvisioningMethod_t)();
typedef OEMCryptoResult (*L1_GetOEMPublicCertificate_t)(
OEMCrypto_SESSION session,
uint8_t *public_cert,
size_t *public_cert_length);
OEMCrypto_SESSION session, uint8_t* public_cert,
size_t* public_cert_length);
typedef OEMCryptoResult (*L1_RewrapDeviceRSAKey30_t)(
OEMCrypto_SESSION session,
const uint32_t *nonce,
const uint8_t* encrypted_message_key,
size_t encrypted_message_key_length,
const uint8_t* enc_rsa_key,
size_t enc_rsa_key_length,
const uint8_t* enc_rsa_key_iv,
uint8_t* wrapped_rsa_key,
size_t* wrapped_rsa_key_length);
OEMCrypto_SESSION session, const uint32_t* nonce,
const uint8_t* encrypted_message_key, size_t encrypted_message_key_length,
const uint8_t* enc_rsa_key, size_t enc_rsa_key_length,
const uint8_t* enc_rsa_key_iv, uint8_t* wrapped_rsa_key,
size_t* wrapped_rsa_key_length);
typedef uint32_t (*L1_SupportedCertificates_t)();
typedef bool (*L1_IsSRMUpdateSupported_t)();
typedef OEMCryptoResult (*L1_GetCurrentSRMVersion_t)(uint16_t* version);
@@ -249,10 +244,10 @@ typedef OEMCryptoResult (*L1_CreateUsageTableHeader_t)(
typedef OEMCryptoResult (*L1_LoadUsageTableHeader_t)(const uint8_t* buffer,
size_t buffer_length);
typedef OEMCryptoResult (*L1_CreateNewUsageEntry_t)(
OEMCrypto_SESSION session, uint32_t *usage_entry_number);
OEMCrypto_SESSION session, uint32_t* usage_entry_number);
typedef OEMCryptoResult (*L1_LoadUsageEntry_t)(OEMCrypto_SESSION session,
uint32_t index,
const uint8_t *buffer,
const uint8_t* buffer,
size_t buffer_size);
typedef OEMCryptoResult (*L1_UpdateUsageEntry_t)(OEMCrypto_SESSION session,
uint8_t* header_buffer,
@@ -263,13 +258,12 @@ typedef OEMCryptoResult (*L1_DeactivateUsageEntry_t)(OEMCrypto_SESSION session,
const uint8_t* pst,
size_t pst_length);
typedef OEMCryptoResult (*L1_ShrinkUsageTableHeader_t)(
uint32_t new_table_size,
uint8_t* header_buffer,
uint32_t new_table_size, uint8_t* header_buffer,
size_t* header_buffer_length);
typedef OEMCryptoResult (*L1_MoveEntry_t)(OEMCrypto_SESSION session,
uint32_t new_index);
typedef OEMCryptoResult (*L1_CopyOldUsageEntry_t)(OEMCrypto_SESSION session,
const uint8_t*pst,
const uint8_t* pst,
size_t pst_length);
typedef OEMCryptoResult (*L1_CreateOldUsageEntry_t)(
uint64_t time_since_license_received, uint64_t time_since_first_decrypt,
@@ -396,8 +390,8 @@ class WatchDog {
}
// Function called by new worker thread.
static void RunWatchDog(void *watcher) {
WatchDog* dog = reinterpret_cast<WatchDog *>(watcher);
static void RunWatchDog(void* watcher) {
WatchDog* dog = reinterpret_cast<WatchDog*>(watcher);
dog->DoInit();
dog->SignalDoneAndCleanUp();
}
@@ -564,30 +558,28 @@ class WatchDog {
struct LevelSession {
FunctionPointers* fcn;
OEMCrypto_SESSION session;
LevelSession() : fcn(0), session(0) {};
LevelSession() : fcn(0), session(0){};
};
#define QUOTE_DEFINE(A) #A
#define QUOTE(A) QUOTE_DEFINE(A)
// This macro looks up a function name, but only if the API version is in the
// specified range.
#define LOOKUP(min, max, Name, Function) \
if ((level1_.version >= min) && (level1_.version <= max)) { \
#define LOOKUP(min, max, Name, Function) \
if ((level1_.version >= min) && (level1_.version <= max)) { \
level1_.Name = (L1_##Name##_t)dlsym(level1_library_, QUOTE(Function)); \
if (!level1_.Name) { \
LOGW("Could not load L1 %s. Falling Back to L3.", \
QUOTE(Function)); \
if (level1_.Terminate) level1_.Terminate(); \
return false; \
} \
if (!level1_.Name) { \
LOGW("Could not load L1 %s. Falling Back to L3.", QUOTE(Function)); \
if (level1_.Terminate) level1_.Terminate(); \
return false; \
} \
}
// This macro looks up a function name, but only if the API version is above
// the specified minimum.
#define LOOKUP_ALL(min, Name, Function) \
#define LOOKUP_ALL(min, Name, Function) \
LOOKUP(min, kMaximumVersion, Name, Function)
// The Adapter keeps a block of FunctionPointers for the built-in level 3 and
// the dynamically loaded level 1 oemcrypto. When initialized, it tries to load
// the level 1 library and verifies that all needed functions are present. If
@@ -611,8 +603,7 @@ class Adapter {
}
}
void SetSandbox(const uint8_t* sandbox_id,
size_t sandbox_id_length) {
void SetSandbox(const uint8_t* sandbox_id, size_t sandbox_id_length) {
sandbox_id_.assign(sandbox_id, sandbox_id + sandbox_id_length);
}
@@ -628,7 +619,7 @@ class Adapter {
level1_ = FunctionPointers(); // start with all null pointers.
level3_ = FunctionPointers(); // start with all null pointers.
LoadLevel3();
WatchDog *watcher = new WatchDog(sandbox_id_);
WatchDog* watcher = new WatchDog(sandbox_id_);
watcher->CheckForPreviousFailure(&metrics);
watcher->StartThread();
if (level3_.BuildInformation) {
@@ -693,15 +684,15 @@ class Adapter {
level1_.version = kMinimumVersion;
LOOKUP_ALL(8, Initialize, OEMCrypto_Initialize);
LOOKUP_ALL(8, APIVersion, OEMCrypto_APIVersion);
LOOKUP_ALL(8, Terminate, OEMCrypto_Terminate);
LOOKUP_ALL(8, Terminate, OEMCrypto_Terminate);
if (!level1_valid_) {
metrics->OemCryptoDynamicAdapterMetrics::SetInitializationMode(
wvcdm::metrics::OEMCrypto_INITIALIZED_USING_L3_INVALID_L1);
return false;
}
if (!sandbox_id_.empty()) {
level1_.SetSandbox = (L1_SetSandbox_t)dlsym(level1_library_,
QUOTE(OEMCrypto_SetSandbox));
level1_.SetSandbox =
(L1_SetSandbox_t)dlsym(level1_library_, QUOTE(OEMCrypto_SetSandbox));
if (level1_.SetSandbox != NULL) {
level1_.SetSandbox(&sandbox_id_[0], sandbox_id_.size());
}
@@ -872,8 +863,7 @@ class Adapter {
if (level1_.IsKeyboxOrOEMCertValid() != OEMCrypto_SUCCESS) {
// A keybox or cert file was read and installed, but it is still not
// valid. Give up.
LOGE("Installed bad key from %s. Falling Back to L3.",
filename.c_str());
LOGE("Installed bad key from %s. Falling Back to L3.", filename.c_str());
level1_.Terminate();
metrics->OemCryptoDynamicAdapterMetrics::SetInitializationMode(
wvcdm::metrics::
@@ -1055,8 +1045,8 @@ OEMCryptoResult OEMCrypto_OpenSession(OEMCrypto_SESSION* session,
}
OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert(const uint8_t* keybox,
size_t keyBoxLength,
SecurityLevel level) {
size_t keyBoxLength,
SecurityLevel level) {
if (!gAdapter.get()) return OEMCrypto_ERROR_UNKNOWN_FAILURE;
const FunctionPointers* fcn = gAdapter->GetFunctionPointers(level);
if (!fcn) return OEMCrypto_ERROR_INVALID_SESSION;
@@ -1298,7 +1288,6 @@ extern "C" OEMCryptoResult OEMCrypto_SetSandbox(const uint8_t* sandbox_id,
return OEMCrypto_SUCCESS;
}
extern "C" OEMCryptoResult OEMCrypto_Initialize(void) {
if (!gAdapter.get()) {
gAdapter.reset(new Adapter());
@@ -1768,10 +1757,9 @@ extern "C" OEMCryptoResult OEMCrypto_QueryKeyControl(
key_control_block, key_control_block_length);
}
extern "C" OEMCryptoResult OEMCrypto_SelectKey(const OEMCrypto_SESSION session,
const uint8_t* key_id,
size_t key_id_length,
OEMCryptoCipherMode cipher_mode) {
extern "C" OEMCryptoResult OEMCrypto_SelectKey(
const OEMCrypto_SESSION session, const uint8_t* key_id,
size_t key_id_length, OEMCryptoCipherMode cipher_mode) {
if (!gAdapter.get()) return OEMCrypto_ERROR_UNKNOWN_FAILURE;
LevelSession pair = gAdapter->GetSession(session);
if (!pair.fcn) return OEMCrypto_ERROR_INVALID_SESSION;
@@ -1838,8 +1826,8 @@ extern "C" OEMCryptoResult OEMCrypto_WrapKeybox(const uint8_t* keybox,
wrappedKeyBoxLength, transportKey, transportKeyLength);
}
extern "C" OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert(const uint8_t* keybox,
size_t keyBoxLength) {
extern "C" OEMCryptoResult OEMCrypto_InstallKeyboxOrOEMCert(
const uint8_t* keybox, size_t keyBoxLength) {
return OEMCrypto_InstallKeyboxOrOEMCert(keybox, keyBoxLength, kLevelDefault);
}
@@ -1898,27 +1886,21 @@ extern "C" OEMCryptoResult OEMCrypto_GetRandom(uint8_t* randomData,
}
extern "C" OEMCryptoResult OEMCrypto_RewrapDeviceRSAKey30(
OEMCrypto_SESSION session,
const uint32_t *nonce,
const uint8_t* encrypted_message_key,
size_t encrypted_message_key_length,
const uint8_t* enc_rsa_key,
size_t enc_rsa_key_length,
const uint8_t* enc_rsa_key_iv,
uint8_t* wrapped_rsa_key,
size_t* wrapped_rsa_key_length) {
OEMCrypto_SESSION session, const uint32_t* nonce,
const uint8_t* encrypted_message_key, size_t encrypted_message_key_length,
const uint8_t* enc_rsa_key, size_t enc_rsa_key_length,
const uint8_t* enc_rsa_key_iv, uint8_t* wrapped_rsa_key,
size_t* wrapped_rsa_key_length) {
if (!gAdapter.get()) return OEMCrypto_ERROR_UNKNOWN_FAILURE;
LevelSession pair = gAdapter->GetSession(session);
if (!pair.fcn) return OEMCrypto_ERROR_INVALID_SESSION;
if (pair.fcn->version < 12) return OEMCrypto_ERROR_NOT_IMPLEMENTED;
if (pair.fcn->RewrapDeviceRSAKey30 == NULL)
return OEMCrypto_ERROR_NOT_IMPLEMENTED;
return pair.fcn->RewrapDeviceRSAKey30(pair.session, nonce,
encrypted_message_key,
encrypted_message_key_length,
enc_rsa_key, enc_rsa_key_length,
enc_rsa_key_iv, wrapped_rsa_key,
wrapped_rsa_key_length);
return pair.fcn->RewrapDeviceRSAKey30(
pair.session, nonce, encrypted_message_key, encrypted_message_key_length,
enc_rsa_key, enc_rsa_key_length, enc_rsa_key_iv, wrapped_rsa_key,
wrapped_rsa_key_length);
}
extern "C" OEMCryptoResult OEMCrypto_RewrapDeviceRSAKey(
@@ -2231,8 +2213,8 @@ extern "C" OEMCryptoResult OEMCrypto_DeleteOldUsageTable() {
if (fcn3 && (fcn3->version > 8) && (fcn3->DeleteOldUsageTable != NULL)) {
sts = fcn3->DeleteOldUsageTable();
}
if (fcn1 && fcn1 != fcn3 &&
(fcn1->version > 8) && (fcn1->DeleteOldUsageTable != NULL)) {
if (fcn1 && fcn1 != fcn3 && (fcn1->version > 8) &&
(fcn1->DeleteOldUsageTable != NULL)) {
sts = fcn1->DeleteOldUsageTable();
}
return sts;
@@ -2367,25 +2349,26 @@ extern "C" OEMCryptoResult OEMCrypto_CreateOldUsageEntry(
pst_length);
}
extern "C" uint32_t OEMCrypto_SupportsDecryptHash(){
extern "C" uint32_t OEMCrypto_SupportsDecryptHash() {
return OEMCrypto_SupportsDecryptHash(kLevelDefault);
}
extern "C" OEMCryptoResult OEMCrypto_SetDecryptHash(OEMCrypto_SESSION session,
uint32_t frame_number,
const uint8_t* hash,
size_t hash_length) {
uint32_t frame_number,
const uint8_t* hash,
size_t hash_length) {
if (!gAdapter.get()) return OEMCrypto_ERROR_UNKNOWN_FAILURE;
LevelSession pair = gAdapter->GetSession(session);
if (!pair.fcn) return OEMCrypto_ERROR_INVALID_SESSION;
if (pair.fcn->SetDecryptHash == NULL) {
return OEMCrypto_ERROR_NOT_IMPLEMENTED;
}
return pair.fcn->SetDecryptHash(pair.session, frame_number, hash, hash_length);
return pair.fcn->SetDecryptHash(pair.session, frame_number, hash,
hash_length);
}
extern "C" OEMCryptoResult OEMCrypto_GetHashErrorCode(OEMCrypto_SESSION session,
uint32_t* failed_frame_number) {
extern "C" OEMCryptoResult OEMCrypto_GetHashErrorCode(
OEMCrypto_SESSION session, uint32_t* failed_frame_number) {
if (!gAdapter.get()) return OEMCrypto_ERROR_UNKNOWN_FAILURE;
LevelSession pair = gAdapter->GetSession(session);
if (!pair.fcn) return OEMCrypto_ERROR_INVALID_SESSION;

View File

@@ -5,6 +5,7 @@
#include "policy_engine.h"
#include <limits.h>
#include <string>
#include "clock.h"
@@ -253,8 +254,7 @@ bool PolicyEngine::BeginDecryption() {
default:
return false;
}
}
else {
} else {
return true;
}
}

View File

@@ -7,7 +7,9 @@
// for signature verification and encryption and decryption.
//
// clang-format off
#include "privacy_crypto.h"
// clang-format on
#include <openssl/aes.h>
#include <openssl/asn1.h>
@@ -68,7 +70,7 @@ class boringssl_ptr {
CORE_DISALLOW_COPY_AND_ASSIGN(boringssl_ptr);
};
void DeleteX509Stack(STACK_OF(X509)* stack) {
void DeleteX509Stack(STACK_OF(X509) * stack) {
sk_X509_pop_free(stack, X509_free);
}
@@ -224,17 +226,18 @@ bool RsaPublicKey::Encrypt(const std::string& clear_message,
return true;
}
// LogBoringSSLError is a callback from BoringSSL which is called with each error
// in the thread's error queue.
static int LogBoringSSLError(const char* msg, size_t /* len */, void* /* ctx */) {
// LogBoringSSLError is a callback from BoringSSL which is called with each
// error in the thread's error queue.
static int LogBoringSSLError(const char* msg, size_t /* len */,
void* /* ctx */) {
LOGE(" %s", msg);
return 1;
}
static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message,
const std::string &signature) {
static bool VerifyPSSSignature(EVP_PKEY* pkey, const std::string& message,
const std::string& signature) {
EVP_MD_CTX* evp_md_ctx = EVP_MD_CTX_new();
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY_CTX* pctx = NULL;
if (EVP_DigestVerifyInit(evp_md_ctx, &pctx, EVP_sha1(), NULL /* no ENGINE */,
pkey) != 1) {
@@ -242,8 +245,8 @@ static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message,
goto err;
}
if (EVP_PKEY_CTX_set_signature_md(pctx,
const_cast<EVP_MD *>(EVP_sha1())) != 1) {
if (EVP_PKEY_CTX_set_signature_md(pctx, const_cast<EVP_MD*>(EVP_sha1())) !=
1) {
LOGE("EVP_PKEY_CTX_set_signature_md failed in VerifyPSSSignature");
goto err;
}
@@ -264,8 +267,9 @@ static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message,
}
if (EVP_DigestVerifyFinal(
evp_md_ctx, const_cast<uint8_t *>(
reinterpret_cast<const uint8_t *>(signature.data())),
evp_md_ctx,
const_cast<uint8_t*>(
reinterpret_cast<const uint8_t*>(signature.data())),
signature.size()) != 1) {
LOGE(
"EVP_DigestVerifyFinal failed in VerifyPSSSignature. (Probably a bad "
@@ -273,7 +277,7 @@ static bool VerifyPSSSignature(EVP_PKEY *pkey, const std::string &message,
goto err;
}
EVP_MD_CTX_free(evp_md_ctx);
EVP_MD_CTX_free(evp_md_ctx);
return true;
err:
@@ -297,7 +301,7 @@ bool RsaPublicKey::VerifySignature(const std::string& message,
// Error already logged by GetKey.
return false;
}
EVP_PKEY *pkey = EVP_PKEY_new();
EVP_PKEY* pkey = EVP_PKEY_new();
if (pkey == NULL) {
LOGE("RsaPublicKey::VerifySignature: EVP_PKEY allocation failed");
FreeKey(rsa_key);
@@ -322,7 +326,6 @@ bool RsaPublicKey::VerifySignature(const std::string& message,
return true;
}
bool ExtractExtensionValueFromCertificate(const std::string& cert,
const std::string& extension_oid,
size_t cert_index, uint32_t* value) {
@@ -330,16 +333,18 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert,
const boringssl_ptr<STACK_OF(X509), DeleteX509Stack> x509_stack(
sk_X509_new_null());
if (x509_stack.get() == NULL) {
LOGE("ExtractExtensionValueFromCertificate: "
"Unable to allocate X509 Stack.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Unable to allocate X509 Stack.");
return false;
}
CBS pkcs7;
CBS_init(&pkcs7, reinterpret_cast<const uint8_t*>(cert.data()), cert.size());
if (!PKCS7_get_certificates(x509_stack.get(), &pkcs7)) {
LOGE("ExtractExtensionValueFromCertificate: "
"Error getting certificate chain.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Error getting certificate chain.");
return false;
}
@@ -347,16 +352,18 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert,
// Find the desired certificate from the stack.
if (sk_X509_num(certs) <= cert_index) {
LOGE("ExtractExtensionValueFromCertificate: "
"Expected at least %zu certificates in chain, got %d",
cert_index + 1, sk_X509_num(certs));
LOGE(
"ExtractExtensionValueFromCertificate: "
"Expected at least %zu certificates in chain, got %d",
cert_index + 1, sk_X509_num(certs));
return false;
}
X509* const intermediate_cert = sk_X509_value(certs, cert_index);
if (!intermediate_cert) {
LOGE("ExtractExtensionValueFromCertificate: "
"Unable to get intermediate cert.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Unable to get intermediate cert.");
return false;
}
@@ -365,8 +372,10 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert,
for (int i = 0; i < extension_count; ++i) {
X509_EXTENSION* const extension = X509_get_ext(intermediate_cert, i);
if (!extension) {
LOGE("ExtractExtensionValueFromCertificate: "
"Unable to get cert extension %d", i);
LOGE(
"ExtractExtensionValueFromCertificate: "
"Unable to get cert extension %d",
i);
continue;
}
@@ -378,31 +387,35 @@ bool ExtractExtensionValueFromCertificate(const std::string& cert,
ASN1_OCTET_STRING* const octet_str = X509_EXTENSION_get_data(extension);
if (!octet_str) {
LOGE("ExtractExtensionValueFromCertificate: "
"Unable to get data of extension.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Unable to get data of extension.");
return false;
}
const unsigned char* data = octet_str->data;
if (!data) {
LOGE("ExtractExtensionValueFromCertificate: "
"Null data in extension.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Null data in extension.");
return false;
}
ASN1_INTEGER* const asn1_integer =
d2i_ASN1_INTEGER(NULL, &data, octet_str->length);
if (!asn1_integer) {
LOGE("ExtractExtensionValueFromCertificate: "
"Unable to decode data in extension.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Unable to decode data in extension.");
return false;
}
const long system_id_long = ASN1_INTEGER_get(asn1_integer);
ASN1_INTEGER_free(asn1_integer);
if (system_id_long == -1) {
LOGE("ExtractExtensionValueFromCertificate: "
"Unable to decode ASN integer in extension.");
LOGE(
"ExtractExtensionValueFromCertificate: "
"Unable to decode ASN integer in extension.");
return false;
}

View File

@@ -7,18 +7,17 @@
// can't tolerate BoringSSL or OpenSSL as a dependency.
//
#include "log.h"
#include "privacy_crypto.h"
#include "log.h"
#ifdef __APPLE__
# include <CommonCrypto/CommonDigest.h>
# define SHA256 CC_SHA256
# define SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
# define MD5 CC_MD5
# define MD5_DIGEST_LENGTH CC_MD5_DIGEST_LENGTH
#include <CommonCrypto/CommonDigest.h>
#define SHA256 CC_SHA256
#define SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
#define MD5 CC_MD5
#define MD5_DIGEST_LENGTH CC_MD5_DIGEST_LENGTH
#else
# error "No hash algorithm known for this platform."
#error "No hash algorithm known for this platform."
#endif
namespace wvcdm {
@@ -50,7 +49,6 @@ bool RsaPublicKey::VerifySignature(const std::string& message,
return false;
}
bool ExtractExtensionValueFromCertificate(const std::string& cert,
const std::string& extension_oid,
size_t cert_index, uint32_t* value) {

View File

@@ -2,8 +2,9 @@
// source code may only be used and distributed under the Widevine Master
// License Agreement.
#include "log.h"
#include "properties.h"
#include "log.h"
#include "wv_cdm_constants.h"
namespace {
@@ -20,15 +21,15 @@ bool Properties::provisioning_messages_are_binary_;
bool Properties::allow_service_certificate_requests_;
std::unique_ptr<CdmClientPropertySetMap> Properties::session_property_set_;
bool Properties::AddSessionPropertySet(
const CdmSessionId& session_id, CdmClientPropertySet* property_set) {
bool Properties::AddSessionPropertySet(const CdmSessionId& session_id,
CdmClientPropertySet* property_set) {
if (NULL == session_property_set_.get()) {
return false;
}
std::pair<CdmClientPropertySetMap::iterator, bool> result =
session_property_set_->insert(
std::pair<const CdmSessionId, CdmClientPropertySet*>(
session_id, property_set));
std::pair<const CdmSessionId, CdmClientPropertySet*>(session_id,
property_set));
return result.second;
}
@@ -75,8 +76,7 @@ bool Properties::GetServiceCertificate(const CdmSessionId& session_id,
bool Properties::SetServiceCertificate(const CdmSessionId& session_id,
const std::string& service_certificate) {
CdmClientPropertySet* property_set =
GetCdmClientPropertySet(session_id);
CdmClientPropertySet* property_set = GetCdmClientPropertySet(session_id);
if (property_set == NULL) {
return false;
}

View File

@@ -16,6 +16,8 @@ namespace {
// Root certificate for all Google/Widevine certificates. I.e. all service
// certificates and DRM certificates are signed by this cert, or have this cert
// as the root of a signing chain.
// clang-format off
static const unsigned char kRootCertForProd[] = {
0x0a, 0x9c, 0x03, 0x08, 0x00, 0x12, 0x01, 0x00,
0x18, 0xdd, 0x94, 0x88, 0x8b, 0x05, 0x22, 0x8e,
@@ -119,6 +121,7 @@ static const unsigned char kRootCertForProd[] = {
0xa2, 0xe6, 0x80, 0x74, 0x55, 0x06, 0x49, 0xd5,
0x02, 0x0c
};
// clang-format on
} // namespace
@@ -228,23 +231,22 @@ CdmResponseType ServiceCertificate::EncryptClientId(
std::string iv(KEY_IV_SIZE, 0);
std::string key(SERVICE_KEY_SIZE, 0);
CdmResponseType status =
crypto_session->GetRandom(key.size(),
reinterpret_cast<uint8_t*>(&key[0]));
CdmResponseType status = crypto_session->GetRandom(
key.size(), reinterpret_cast<uint8_t*>(&key[0]));
if (status != NO_ERROR) {
LOGE("ServiceCertificate::EncryptClientId: GetRandom error: %d", status);
return status == RANDOM_GENERATION_ERROR ?
CLIENT_ID_GENERATE_RANDOM_ERROR : status;
return status == RANDOM_GENERATION_ERROR ? CLIENT_ID_GENERATE_RANDOM_ERROR
: status;
}
status = crypto_session->GetRandom(iv.size(),
reinterpret_cast<uint8_t*>(&iv[0]));
status =
crypto_session->GetRandom(iv.size(), reinterpret_cast<uint8_t*>(&iv[0]));
if (status != NO_ERROR) {
LOGE("ServiceCertificate::EncryptClientId: GetRandom error: %d", status);
return status == RANDOM_GENERATION_ERROR ?
CLIENT_ID_GENERATE_RANDOM_ERROR : status;
return status == RANDOM_GENERATION_ERROR ? CLIENT_ID_GENERATE_RANDOM_ERROR
: status;
}
std::string id, enc_id, enc_key;
clear_client_id->SerializeToString(&id);
@@ -254,8 +256,7 @@ CdmResponseType ServiceCertificate::EncryptClientId(
if (!aes.Encrypt(id, &enc_id, &iv)) return CLIENT_ID_AES_ENCRYPT_ERROR;
CdmResponseType encrypt_result = EncryptRsaOaep(key, &enc_key);
if (encrypt_result != NO_ERROR)
return encrypt_result;
if (encrypt_result != NO_ERROR) return encrypt_result;
encrypted_client_id->set_encrypted_client_id_iv(iv);
encrypted_client_id->set_encrypted_privacy_key(enc_key);
@@ -274,8 +275,8 @@ bool ServiceCertificate::GetRequest(CdmKeyMessage* request) {
return true;
}
CdmResponseType ServiceCertificate::ParseResponse(
const std::string& response, std::string* certificate) {
CdmResponseType ServiceCertificate::ParseResponse(const std::string& response,
std::string* certificate) {
if (response.empty()) {
LOGE("ServiceCertificate::ParseResponse: empty response");
return EMPTY_RESPONSE_ERROR_1;
@@ -312,6 +313,4 @@ CdmResponseType ServiceCertificate::ParseResponse(
return NO_ERROR;
}
} // namespace wvcdm

View File

@@ -21,7 +21,7 @@ std::string kOldUsageEntryServerMacKey(wvcdm::MAC_KEY_SIZE, 0);
std::string kOldUsageEntryClientMacKey(wvcdm::MAC_KEY_SIZE, 0);
std::string kOldUsageEntryPoviderSessionToken =
"nahZ6achSheiqua3TohQuei0ahwohv";
}
} // namespace
namespace wvcdm {
@@ -65,7 +65,7 @@ bool UsageTableHeader::Init(CdmSecurityLevel security_level,
if (metrics == NULL) metrics = &alternate_crypto_metrics_;
if (file_handle_->RetrieveUsageTableInfo(&usage_table_header_,
&usage_entry_info_)) {
&usage_entry_info_)) {
LOGI("UsageTableHeader::Init: number of usage entries: %d",
usage_entry_info_.size());
status = crypto_session->LoadUsageTableHeader(usage_table_header_);
@@ -93,17 +93,17 @@ bool UsageTableHeader::Init(CdmSecurityLevel security_level,
result = local_crypto_session->Open(requested_security_level_);
if (result == NO_ERROR) {
result = AddEntry(local_crypto_session, true,
kDummyKeySetId, kEmptyString,
&temporary_usage_entry_number);
result = AddEntry(local_crypto_session, true, kDummyKeySetId,
kEmptyString, &temporary_usage_entry_number);
}
}
if (result == NO_ERROR) {
result = DeleteEntry(temporary_usage_entry_number,
file_handle_.get(), metrics);
result = DeleteEntry(temporary_usage_entry_number, file_handle_.get(),
metrics);
}
if (result != NO_ERROR) {
LOGE("UsageTableHeader::Init: Unable to create/delete new entry. "
LOGE(
"UsageTableHeader::Init: Unable to create/delete new entry. "
"Clear usage entries, security level: %d, usage entries: %d",
security_level, usage_entry_info_.size());
status = result;
@@ -150,12 +150,10 @@ CdmResponseType UsageTableHeader::AddEntry(
// If usage entry creation fails due to insufficient resources, release a
// random entry and try again.
for (uint32_t retry_count = 0;
retry_count < kMaxCryptoRetries &&
status == INSUFFICIENT_CRYPTO_RESOURCES_3;
for (uint32_t retry_count = 0; retry_count < kMaxCryptoRetries &&
status == INSUFFICIENT_CRYPTO_RESOURCES_3;
++retry_count) {
int64_t entry_number_to_delete =
GetRandomInRange(usage_entry_info_.size());
int64_t entry_number_to_delete = GetRandomInRange(usage_entry_info_.size());
if (entry_number_to_delete < 0) break;
DeleteEntry(entry_number_to_delete, file_handle_.get(), metrics);
@@ -222,9 +220,8 @@ CdmResponseType UsageTableHeader::LoadEntry(CryptoSession* crypto_session,
// If loading a usage entry fails due to insufficient resources, release a
// random entry different from |usage_entry_number| and try again. If there
// are no more entries to release, we fail.
for (uint32_t retry_count = 0;
retry_count < kMaxCryptoRetries &&
status == INSUFFICIENT_CRYPTO_RESOURCES_3;
for (uint32_t retry_count = 0; retry_count < kMaxCryptoRetries &&
status == INSUFFICIENT_CRYPTO_RESOURCES_3;
++retry_count) {
// Get a random entry from the other entries.
int64_t entry_number_to_delete = GetRandomInRangeWithExclusion(
@@ -257,8 +254,10 @@ CdmResponseType UsageTableHeader::DeleteEntry(uint32_t usage_entry_number,
usage_entry_number);
std::unique_lock<std::mutex> auto_lock(usage_table_header_lock_);
if (usage_entry_number >= usage_entry_info_.size()) {
LOGE("UsageTableHeader::DeleteEntry: usage entry number %d larger than "
"usage entry size %d", usage_entry_number, usage_entry_info_.size());
LOGE(
"UsageTableHeader::DeleteEntry: usage entry number %d larger than "
"usage entry size %d",
usage_entry_number, usage_entry_info_.size());
return USAGE_INVALID_PARAMETERS_1;
}
@@ -510,8 +509,8 @@ CdmResponseType UsageTableHeader::Shrink(
if (usage_entry_info_.size() < number_of_usage_entries_to_delete) {
LOGW(
"UsageTableHeader::Shrink: cannot delete %d entries when usage entry "
"table size is %d", number_of_usage_entries_to_delete,
usage_entry_info_.size());
"table size is %d",
number_of_usage_entries_to_delete, usage_entry_info_.size());
return NO_ERROR;
}
@@ -581,7 +580,8 @@ bool UsageTableHeader::UpgradeLicensesFromUsageTable(
&usage_entry_number, &sub_error_code)) {
LOGW(
"UsageTableHeader::UpgradeLicensesFromUsageTable: Failed to "
"retrieve license, %d", sub_error_code);
"retrieve license, %d",
sub_error_code);
continue;
}
@@ -634,7 +634,8 @@ bool UsageTableHeader::UpgradeLicensesFromUsageTable(
app_parameters, usage_entry, usage_entry_number, &sub_error_code)) {
LOGE(
"UsageTableHeader::UpgradeLicensesFromUsageTable: Failed to store "
"license, %d", sub_error_code);
"license, %d",
sub_error_code);
continue;
}
}
@@ -737,8 +738,7 @@ int64_t UsageTableHeader::GetRandomInRange(size_t upper_bound_exclusive) {
int64_t UsageTableHeader::GetRandomInRangeWithExclusion(
size_t upper_bound_exclusive, size_t exclude) {
if ((upper_bound_exclusive <= 1) ||
(exclude >= upper_bound_exclusive)) {
if ((upper_bound_exclusive <= 1) || (exclude >= upper_bound_exclusive)) {
LOGE(
"upper_bound_exclusive must be > 1 and exclude must be < "
"upper_bound_exclusive.");
@@ -752,13 +752,10 @@ int64_t UsageTableHeader::GetRandomInRangeWithExclusion(
// TODO(fredgc): remove when b/65730828 is addressed
bool UsageTableHeader::CreateDummyOldUsageEntry(CryptoSession* crypto_session) {
return crypto_session->CreateOldUsageEntry(
kOldUsageEntryTimeSinceLicenseReceived,
kOldUsageEntryTimeSinceFirstDecrypt,
kOldUsageEntryTimeSinceLastDecrypt,
CryptoSession::kUsageDurationsInvalid,
kOldUsageEntryServerMacKey,
kOldUsageEntryClientMacKey,
kOldUsageEntryPoviderSessionToken);
kOldUsageEntryTimeSinceLicenseReceived,
kOldUsageEntryTimeSinceFirstDecrypt, kOldUsageEntryTimeSinceLastDecrypt,
CryptoSession::kUsageDurationsInvalid, kOldUsageEntryServerMacKey,
kOldUsageEntryClientMacKey, kOldUsageEntryPoviderSessionToken);
}
// Test only method.
@@ -766,9 +763,10 @@ void UsageTableHeader::DeleteEntryForTest(uint32_t usage_entry_number) {
LOGV("UsageTableHeader::DeleteEntryForTest: usage_entry_number: %d",
usage_entry_number);
if (usage_entry_number >= usage_entry_info_.size()) {
LOGE("UsageTableHeader::DeleteEntryForTest: usage entry number %d larger "
"than usage entry size %d", usage_entry_number,
usage_entry_info_.size());
LOGE(
"UsageTableHeader::DeleteEntryForTest: usage entry number %d larger "
"than usage entry size %d",
usage_entry_number, usage_entry_info_.size());
return;
}
// Move last entry into deleted location and shrink usage entries