Initial import of Widevine Common Encryption DRM engine
Builds libwvmdrmengine.so, which is loaded by the new MediaDrm APIs to support playback of Widevine/CENC protected content. Change-Id: I6f57dd37083dfd96c402cb9dd137c7d74edc8f1c
This commit is contained in:
94
libwvdrmengine/cdm/core/src/buffer_reader.cpp
Normal file
94
libwvdrmengine/cdm/core/src/buffer_reader.cpp
Normal file
@@ -0,0 +1,94 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
|
||||
#include "buffer_reader.h"
|
||||
|
||||
#include "log.h"
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
bool BufferReader::Read1(uint8_t* v) {
|
||||
if (!HasBytes(1)) {
|
||||
LOGE("BufferReader::Read1 : Failure while parsing: Not enough bytes (1)");
|
||||
return false;
|
||||
}
|
||||
|
||||
*v = buf_[pos_++];
|
||||
return true;
|
||||
}
|
||||
|
||||
// Internal implementation of multi-byte reads
|
||||
template<typename T> bool BufferReader::Read(T* v) {
|
||||
if (!HasBytes(sizeof(T))) {
|
||||
LOGE("BufferReader::Read<T> : Failure while parsing: Not enough bytes (%u)", sizeof(T));
|
||||
return false;
|
||||
}
|
||||
|
||||
T tmp = 0;
|
||||
for (size_t i = 0; i < sizeof(T); i++) {
|
||||
tmp <<= 8;
|
||||
tmp += buf_[pos_++];
|
||||
}
|
||||
*v = tmp;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BufferReader::Read2(uint16_t* v) { return Read(v); }
|
||||
bool BufferReader::Read2s(int16_t* v) { return Read(v); }
|
||||
bool BufferReader::Read4(uint32_t* v) { return Read(v); }
|
||||
bool BufferReader::Read4s(int32_t* v) { return Read(v); }
|
||||
bool BufferReader::Read8(uint64_t* v) { return Read(v); }
|
||||
bool BufferReader::Read8s(int64_t* v) { return Read(v); }
|
||||
|
||||
bool BufferReader::ReadString(std::string* str, int count) {
|
||||
if (!HasBytes(count)) {
|
||||
LOGE("BufferReader::ReadString : Failure while parsing: Not enough bytes (%d)", count);
|
||||
return false;
|
||||
}
|
||||
|
||||
str->assign(buf_ + pos_, buf_ + pos_ + count);
|
||||
pos_ += count;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BufferReader::ReadVec(std::vector<uint8_t>* vec, int count) {
|
||||
if (!HasBytes(count)) {
|
||||
LOGE("BufferReader::ReadVec : Failure while parsing: Not enough bytes (%d)", count);
|
||||
return false;
|
||||
}
|
||||
|
||||
vec->clear();
|
||||
vec->insert(vec->end(), buf_ + pos_, buf_ + pos_ + count);
|
||||
pos_ += count;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BufferReader::SkipBytes(int bytes) {
|
||||
if (!HasBytes(bytes)) {
|
||||
LOGE("BufferReader::SkipBytes : Failure while parsing: Not enough bytes (%d)", bytes);
|
||||
return false;
|
||||
}
|
||||
|
||||
pos_ += bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BufferReader::Read4Into8(uint64_t* v) {
|
||||
uint32_t tmp;
|
||||
if (!Read4(&tmp)) {
|
||||
return false;
|
||||
}
|
||||
*v = tmp;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BufferReader::Read4sInto8s(int64_t* v) {
|
||||
// Beware of the need for sign extension.
|
||||
int32_t tmp;
|
||||
if (!Read4s(&tmp)) {
|
||||
return false;
|
||||
}
|
||||
*v = tmp;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace wvcdm
|
||||
463
libwvdrmengine/cdm/core/src/cdm_engine.cpp
Normal file
463
libwvdrmengine/cdm/core/src/cdm_engine.cpp
Normal file
@@ -0,0 +1,463 @@
|
||||
// Copyright 2013 Google Inc. All Rights Reserved.
|
||||
|
||||
#include "cdm_engine.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "buffer_reader.h"
|
||||
#include "cdm_session.h"
|
||||
#include "log.h"
|
||||
#include "wv_cdm_constants.h"
|
||||
#include "wv_cdm_event_listener.h"
|
||||
|
||||
#ifndef CDM_POLICY_TIMER_DURATION_SECONDS
|
||||
#define CDM_POLICY_TIMER_DURATION_SECONDS 1
|
||||
#endif
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
typedef std::map<CdmSessionId,CdmSession*>::iterator CdmSessionIter;
|
||||
|
||||
CdmEngine::~CdmEngine() {
|
||||
CancelSessions();
|
||||
|
||||
CdmSessionMap::iterator i(sessions_.begin());
|
||||
for (; i != sessions_.end(); ++i)
|
||||
delete i->second;
|
||||
sessions_.clear();
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::OpenSession(
|
||||
const CdmKeySystem& key_system,
|
||||
CdmSessionId* session_id) {
|
||||
LOGI("CdmEngine::OpenSession");
|
||||
|
||||
if (!ValidateKeySystem(key_system)) {
|
||||
LOGI("CdmEngine::OpenSession: invalid key_system = %s", key_system.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (!session_id) {
|
||||
LOGE("CdmEngine::OpenSession: no session ID destination provided");
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
// TODO(edwinwong, rfrias): Save key_system in session for validation checks
|
||||
CdmSession* new_session = new CdmSession();
|
||||
if (!new_session) {
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (new_session->session_id().empty()) {
|
||||
LOGE("CdmEngine::OpenSession: failure to generate session ID");
|
||||
delete(new_session);
|
||||
return UNKNOWN_ERROR;
|
||||
}
|
||||
|
||||
CdmSessionId new_session_id = new_session->session_id();
|
||||
|
||||
if (!new_session->Init()) {
|
||||
LOGE("CdmEngine::OpenSession: bad session init");
|
||||
delete(new_session);
|
||||
return UNKNOWN_ERROR;
|
||||
}
|
||||
|
||||
sessions_[new_session_id] = new_session;
|
||||
*session_id = new_session_id;
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::CloseSession(CdmSessionId& session_id) {
|
||||
LOGI("CdmEngine::CloseSession");
|
||||
|
||||
CdmSession* cdm_session = sessions_[session_id];
|
||||
|
||||
if (!cdm_session) {
|
||||
LOGE("CdmEngine::CloseSession: session not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
sessions_.erase(session_id);
|
||||
cdm_session->DestroySession();
|
||||
delete cdm_session;
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::GenerateKeyRequest(
|
||||
const CdmSessionId& session_id,
|
||||
bool is_key_system_present,
|
||||
const CdmKeySystem& key_system,
|
||||
const CdmInitData& init_data,
|
||||
const CdmLicenseType license_type,
|
||||
CdmNameValueMap& app_parameters,
|
||||
CdmKeyMessage* key_request) {
|
||||
LOGI("CdmEngine::GenerateKeyRequest");
|
||||
|
||||
CdmSession* session = sessions_[session_id];
|
||||
|
||||
if (!session) {
|
||||
LOGE("CdmEngine::GenerateKeyRequest: session_id not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (is_key_system_present) {
|
||||
// TODO(edwinwong, rfrias): validate key_system has not changed
|
||||
}
|
||||
|
||||
if (init_data.empty()) {
|
||||
LOGE("CdmEngine::GenerateKeyRequest: no init_data provided");
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (!key_request) {
|
||||
LOGE("CdmEngine::GenerateKeyRequest: no key request destination provided");
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
CdmInitData extracted_pssh;
|
||||
if (!ExtractWidevinePssh(init_data, &extracted_pssh)) {
|
||||
key_request->clear();
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
key_request->clear();
|
||||
|
||||
// TODO(edwinwong, rfrias): need to pass in license type and app parameters
|
||||
CdmResponseType sts = session->GenerateKeyRequest(extracted_pssh,
|
||||
key_request);
|
||||
|
||||
if (KEY_MESSAGE != sts) {
|
||||
LOGE("CdmEngine::GenerateKeyRequest: key request generation failed, sts=%d",
|
||||
(int)sts);
|
||||
return sts;
|
||||
}
|
||||
|
||||
// TODO(edwinwong, rfrias): persist init_data, license_type, app_parameters
|
||||
// in session
|
||||
|
||||
return KEY_MESSAGE;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::AddKey(
|
||||
const CdmSessionId& session_id,
|
||||
bool is_key_system_init_data_present,
|
||||
const CdmKeySystem& key_system,
|
||||
const CdmInitData& init_data,
|
||||
const CdmKeyResponse& key_data) {
|
||||
LOGI("CdmEngine::AddKey");
|
||||
|
||||
CdmSession* session = sessions_[session_id];
|
||||
|
||||
if (!session) {
|
||||
LOGE("CdmEngine::AddKey: session_id not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (is_key_system_init_data_present) {
|
||||
// TODO(edwinwong, rfrias): validate key_system has not changed
|
||||
}
|
||||
|
||||
if (is_key_system_init_data_present) {
|
||||
// TODO(edwinwong, rfrias): validate init_data has not changed
|
||||
}
|
||||
|
||||
if (key_data.empty()) {
|
||||
LOGE("CdmEngine::AddKey: no key_data");
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType sts = session->AddKey(key_data);
|
||||
if (KEY_ADDED != sts) {
|
||||
LOGE("CdmEngine::AddKey: keys not added, result = %d", (int)sts);
|
||||
}
|
||||
|
||||
return sts;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::CancelKeyRequest(
|
||||
const CdmSessionId& session_id,
|
||||
bool is_key_system_present,
|
||||
const CdmKeySystem& key_system) {
|
||||
LOGI("CdmEngine::CancelKeyRequest");
|
||||
|
||||
//TODO(gmorgan): Issue: what is semantics of canceling a key request. Should
|
||||
//this call cancel all keys for the session?
|
||||
// TODO(jfore): We should disable the policy timer here if there are no
|
||||
// active sessions. Sessions are currently not being destroyed here. We can
|
||||
// add this logic once the semantics of canceling the key is worked out.
|
||||
|
||||
CdmSession* session = sessions_[session_id];
|
||||
|
||||
if (!session) {
|
||||
LOGE("CdmEngine::CancelKeyRequest: session_id not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (is_key_system_present) {
|
||||
// TODO(edwinwong, rfrias): validate key_system has not changed
|
||||
}
|
||||
|
||||
// TODO(edwinwong, rfrias): unload keys here
|
||||
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::GenerateRenewalRequest(
|
||||
const CdmSessionId& session_id,
|
||||
bool is_key_system_init_data_present,
|
||||
const CdmKeySystem& key_system,
|
||||
const CdmInitData& init_data,
|
||||
CdmKeyMessage* key_request) {
|
||||
LOGI("CdmEngine::GenerateRenewalRequest");
|
||||
|
||||
CdmSession* session = sessions_[session_id];
|
||||
|
||||
if (!session) {
|
||||
LOGE("CdmEngine::GenerateRenewalRequest: session_id not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (is_key_system_init_data_present) {
|
||||
// TODO(edwinwong, rfrias): validate key_system has not changed
|
||||
}
|
||||
|
||||
if (is_key_system_init_data_present) {
|
||||
// TODO(edwinwong, rfrias): validate init_data has not changed
|
||||
}
|
||||
|
||||
if (!key_request) {
|
||||
LOGE("CdmEngine::GenerateRenewalRequest: no key request destination provided");
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
key_request->clear();
|
||||
|
||||
CdmResponseType sts = session->GenerateRenewalRequest(key_request);
|
||||
|
||||
if (KEY_MESSAGE != sts) {
|
||||
LOGE("CdmEngine::GenerateRenewalRequest: key request generation failed, sts=%d",
|
||||
(int)sts);
|
||||
return sts;
|
||||
}
|
||||
|
||||
return KEY_MESSAGE;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::RenewKey(
|
||||
const CdmSessionId& session_id,
|
||||
bool is_key_system_init_data_present,
|
||||
const CdmKeySystem& key_system,
|
||||
const CdmInitData& init_data,
|
||||
const CdmKeyResponse& key_data) {
|
||||
LOGI("CdmEngine::RenewKey");
|
||||
|
||||
CdmSession* session = sessions_[session_id];
|
||||
|
||||
if (!session) {
|
||||
LOGE("CdmEngine::RenewKey: session_id not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
if (is_key_system_init_data_present) {
|
||||
// TODO(edwinwong, rfrias): validate key_system has not changed
|
||||
}
|
||||
|
||||
if (is_key_system_init_data_present) {
|
||||
// TODO(edwinwong, rfrias): validate init_data has not changed
|
||||
}
|
||||
|
||||
if (key_data.empty()) {
|
||||
LOGE("CdmEngine::RenewKey: no key_data");
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType sts = session->RenewKey(key_data);
|
||||
if (KEY_ADDED != sts) {
|
||||
LOGE("CdmEngine::RenewKey: keys not added, sts=%d", (int)sts);
|
||||
return sts;
|
||||
}
|
||||
|
||||
return KEY_ADDED;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::QueryKeyStatus(
|
||||
const CdmSessionId& session_id,
|
||||
CdmNameValueMap* key_info) {
|
||||
// TODO(edwinwong, rfrias): add implementation
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::GetProvisioningRequest(
|
||||
CdmProvisioningRequest* request,
|
||||
std::string* default_url) {
|
||||
// TODO(edwinwong, rfrias): add implementation
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::HandleProvisioningResponse(
|
||||
CdmProvisioningResponse& response) {
|
||||
// TODO(edwinwong, rfrias): add implementation
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::GetSecureStops(
|
||||
CdmSecureStops* secure_stops) {
|
||||
// TODO(edwinwong, rfrias): add implementation
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::ReleaseSecureStops(
|
||||
const CdmSecureStopReleaseMessage& message) {
|
||||
// TODO(edwinwong, rfrias): add implementation
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
CdmResponseType CdmEngine::Decrypt(
|
||||
const CdmSessionId& session_id,
|
||||
bool is_encrypted,
|
||||
const KeyId& key_id,
|
||||
const uint8_t* encrypted_buffer,
|
||||
size_t encrypted_size,
|
||||
const std::vector<uint8_t>& iv,
|
||||
size_t block_offset,
|
||||
void* decrypted_buffer) {
|
||||
CdmSession* session = sessions_[session_id];
|
||||
|
||||
if (!session) {
|
||||
LOGW("CdmEngine::Decrypt: session_id not found = %s", session_id.c_str());
|
||||
return KEY_ERROR;
|
||||
}
|
||||
|
||||
// TODO(edwinwong, rfrias): Need to add implemenation and hook up
|
||||
// decryption though to oem_crypto
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
bool CdmEngine::IsKeyValid(const KeyId& key_id) {
|
||||
for (CdmSessionIter iter = sessions_.begin();
|
||||
iter != sessions_.end(); ++iter) {
|
||||
if (iter->second->IsKeyValid(key_id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CdmEngine::AttachEventListener(
|
||||
CdmSessionId& session_id,
|
||||
WvCdmEventListener* listener) {
|
||||
|
||||
CdmSessionIter iter = sessions_.find(session_id);
|
||||
if (iter == sessions_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return iter->second->AttachEventListener(listener);
|
||||
}
|
||||
|
||||
bool CdmEngine::DetachEventListener(
|
||||
CdmSessionId& session_id,
|
||||
WvCdmEventListener* listener) {
|
||||
|
||||
CdmSessionIter iter = sessions_.find(session_id);
|
||||
if (iter == sessions_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return iter->second->DetachEventListener(listener);
|
||||
}
|
||||
|
||||
bool CdmEngine::ValidateKeySystem(const CdmKeySystem& key_system) {
|
||||
return (key_system.find("widevine") != std::string::npos);
|
||||
}
|
||||
|
||||
bool CdmEngine::CancelSessions() {
|
||||
// TODO(gmorgan) Implement CancelSessions()
|
||||
return true;
|
||||
}
|
||||
|
||||
// Parse a blob of multiple concatenated PSSH atoms to extract the first
|
||||
// widevine pssh
|
||||
// TODO(kqyang): temporary workaround - remove after b/7928472 is resolved
|
||||
bool CdmEngine::ExtractWidevinePssh(
|
||||
const CdmInitData& init_data, CdmInitData* output) {
|
||||
|
||||
BufferReader reader(
|
||||
reinterpret_cast<const uint8_t*>(init_data.data()), init_data.length());
|
||||
|
||||
// TODO(kqyang): Extracted from an actual init_data;
|
||||
// Need to find out where it comes from.
|
||||
static const uint8_t kWidevineSystemId[] = {
|
||||
0xED, 0xEF, 0x8B, 0xA9, 0x79, 0xD6, 0x4A, 0xCE,
|
||||
0xA3, 0xC8, 0x27, 0xDC, 0xD5, 0x1D, 0x21, 0xED,
|
||||
};
|
||||
|
||||
// one PSSH blob consists of:
|
||||
// 4 byte size of the PSSH atom, inclusive
|
||||
// "pssh"
|
||||
// 4 byte flags, value 0
|
||||
// 16 byte system id
|
||||
// 4 byte size of PSSH data, exclusive
|
||||
while (1) {
|
||||
// size of PSSH atom, used for skipping
|
||||
uint32_t size;
|
||||
if (!reader.Read4(&size)) return false;
|
||||
|
||||
// "pssh"
|
||||
std::vector<uint8_t> pssh;
|
||||
if (!reader.ReadVec(&pssh, 4)) return false;
|
||||
if (memcmp(&pssh[0], "pssh", 4)) return false;
|
||||
|
||||
// flags
|
||||
uint32_t flags;
|
||||
if (!reader.Read4(&flags)) return false;
|
||||
if (flags != 0) return false;
|
||||
|
||||
// system id
|
||||
std::vector<uint8_t> system_id;
|
||||
if (!reader.ReadVec(&system_id, sizeof(kWidevineSystemId))) return false;
|
||||
|
||||
if (memcmp(&system_id[0], kWidevineSystemId,
|
||||
sizeof(kWidevineSystemId))) {
|
||||
// skip the remaining contents of the atom,
|
||||
// after size field, atom name, flags and system id
|
||||
if (!reader.SkipBytes(
|
||||
size - 4 - 4 - 4 - sizeof(kWidevineSystemId))) return false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// size of PSSH box
|
||||
uint32_t pssh_length;
|
||||
if (!reader.Read4(&pssh_length)) return false;
|
||||
|
||||
output->clear();
|
||||
if (!reader.ReadString(output, pssh_length)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// we did not find a matching record
|
||||
return false;
|
||||
}
|
||||
|
||||
void CdmEngine::EnablePolicyTimer() {
|
||||
|
||||
if (!policy_timer_.IsRunning())
|
||||
policy_timer_.Start(this, CDM_POLICY_TIMER_DURATION_SECONDS);
|
||||
}
|
||||
|
||||
void CdmEngine::DisablePolicyTimer() {
|
||||
|
||||
if (policy_timer_.IsRunning())
|
||||
policy_timer_.Stop();
|
||||
}
|
||||
|
||||
void CdmEngine::OnTimerEvent() {
|
||||
|
||||
for (CdmSessionIter iter = sessions_.begin();
|
||||
iter != sessions_.end(); ++iter) {
|
||||
iter->second->OnTimerEvent();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace wvcdm
|
||||
144
libwvdrmengine/cdm/core/src/cdm_session.cpp
Normal file
144
libwvdrmengine/cdm/core/src/cdm_session.cpp
Normal file
@@ -0,0 +1,144 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
// Author: jfore@google.com (Jeff Fore), rkuroiwa@google.com (Rintaro Kuroiwa)
|
||||
|
||||
#include "cdm_session.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "crypto_engine.h"
|
||||
#include "log.h"
|
||||
#include "string_conversions.h"
|
||||
#include "clock.h"
|
||||
#include "wv_cdm_constants.h"
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
typedef std::set<WvCdmEventListener*>::iterator CdmEventListenerIter;
|
||||
|
||||
bool CdmSession::Init() {
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
if (!crypto_engine) {
|
||||
LOGE("CdmSession::Init failed to get CryptoEngine instance.");
|
||||
return false;
|
||||
}
|
||||
|
||||
crypto_session_ = crypto_engine->CreateSession(session_id_);
|
||||
if (!crypto_session_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string token;
|
||||
if (!crypto_engine->GetToken(&token)) return false;
|
||||
|
||||
return license_parser_.Init(token, crypto_session_);
|
||||
}
|
||||
|
||||
bool CdmSession::DestroySession() {
|
||||
if (crypto_session_) {
|
||||
delete crypto_session_;
|
||||
crypto_session_ = NULL;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CdmSession::VerifySession(const CdmKeySystem& key_system,
|
||||
const CdmInitData& init_data) {
|
||||
// TODO(gmorgan): Compare key_system and init_data with value received
|
||||
// during session startup - they should be the same.
|
||||
return true;
|
||||
}
|
||||
|
||||
CdmResponseType CdmSession::GenerateKeyRequest(const CdmInitData& init_data,
|
||||
CdmKeyMessage* key_request) {
|
||||
crypto_session_->Open();
|
||||
if(!license_parser_.PrepareKeyRequest(init_data, key_request)) {
|
||||
return KEY_ERROR;
|
||||
} else {
|
||||
return KEY_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
// AddKey() - Accept license response and extract key info.
|
||||
CdmResponseType CdmSession::AddKey(const CdmKeyResponse& key_response) {
|
||||
if (!license_parser_.HandleKeyResponse(key_response)) {
|
||||
return KEY_ERROR;
|
||||
} else {
|
||||
return KEY_ADDED;
|
||||
}
|
||||
}
|
||||
|
||||
// CancelKeyRequest() - Cancel session.
|
||||
CdmResponseType CdmSession::CancelKeyRequest() {
|
||||
// TODO(gmorgan): cancel and clean up session
|
||||
crypto_session_->Close();
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
// Decrypt() - Accept encrypted buffer and return decrypted data.
|
||||
CdmResponseType CdmSession::Decrypt(const uint8_t* encrypted_buffer,
|
||||
size_t encrypted_size,
|
||||
size_t block_offset,
|
||||
const std::string& iv,
|
||||
const KeyId& key_id,
|
||||
uint8_t* decrypted_buffer) {
|
||||
return UNKNOWN_ERROR;
|
||||
}
|
||||
|
||||
// License renewal
|
||||
// GenerateRenewalRequest() - Construct valid renewal request for the current
|
||||
// session keys.
|
||||
CdmResponseType CdmSession::GenerateRenewalRequest(CdmKeyMessage* key_request) {
|
||||
if(!license_parser_.PrepareKeyRenewalRequest(key_request)) {
|
||||
return KEY_ERROR;
|
||||
} else {
|
||||
return KEY_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
// RenewKey() - Accept renewal response and update key info.
|
||||
CdmResponseType CdmSession::RenewKey(const CdmKeyResponse& key_response) {
|
||||
if (!license_parser_.HandleKeyRenewalResponse(key_response)) {
|
||||
return KEY_ERROR;
|
||||
} else {
|
||||
return KEY_ADDED;
|
||||
}
|
||||
}
|
||||
|
||||
bool CdmSession::IsKeyValid(const KeyId& key_id) {
|
||||
// TODO(gmorgan): lookup key and determine if valid.
|
||||
// return (session_keys_.find(key_id) != session_keys_.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
CdmSessionId CdmSession::GenerateSessionId() {
|
||||
static const std::string kSessionPrefix("Session");
|
||||
static int session_num = 1;
|
||||
// TODO(rkuroiwa): Want this to be unique. Probably doing Hash(time+init_data)
|
||||
// to get something that is reasonably unique.
|
||||
return kSessionPrefix + IntToString(++session_num);
|
||||
}
|
||||
|
||||
bool CdmSession::AttachEventListener(WvCdmEventListener* listener) {
|
||||
std::pair<CdmEventListenerIter, bool> result = listeners_.insert(listener);
|
||||
return result.second;
|
||||
}
|
||||
|
||||
bool CdmSession::DetachEventListener(WvCdmEventListener* listener) {
|
||||
return (listeners_.erase(listener) == 1);
|
||||
}
|
||||
|
||||
void CdmSession::OnTimerEvent() {
|
||||
bool event_occurred = false;
|
||||
CdmEventType event;
|
||||
|
||||
policy_engine_.OnTimerEvent(GetCurrentTime(), event_occurred, event);
|
||||
|
||||
if (event_occurred) {
|
||||
for (CdmEventListenerIter iter = listeners_.begin();
|
||||
iter != listeners_.end(); ++iter) {
|
||||
(*iter)->onEvent(session_id(), event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace wvcdm
|
||||
178
libwvdrmengine/cdm/core/src/crypto_engine.cpp
Normal file
178
libwvdrmengine/cdm/core/src/crypto_engine.cpp
Normal file
@@ -0,0 +1,178 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Crypto - wrapper classes for OEMCrypto interface
|
||||
//
|
||||
|
||||
#include "crypto_engine.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "log.h"
|
||||
#include "OEMCryptoCENC.h"
|
||||
#include "wv_cdm_constants.h"
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
CryptoEngine* CryptoEngine::crypto_engine_ = NULL;
|
||||
Lock CryptoEngine::crypto_engine_lock_;
|
||||
|
||||
// wrapper classes for OEMCrypto interface
|
||||
// CryptoEngine -- top-level interface
|
||||
// CryptoSession -- session-specific interface
|
||||
// CryptoKey -- key interface
|
||||
|
||||
// CryptoEngine methods
|
||||
|
||||
CryptoEngine::CryptoEngine() : initialized_(false) {}
|
||||
|
||||
CryptoEngine::~CryptoEngine() {
|
||||
if (initialized_) {
|
||||
Terminate();
|
||||
}
|
||||
|
||||
CryptoSessionMap::iterator i(sessions_.begin());
|
||||
for (; i != sessions_.end(); ++i)
|
||||
delete i->second;
|
||||
sessions_.clear();
|
||||
}
|
||||
|
||||
// get the instance of OEMCrypto Client
|
||||
CryptoEngine* CryptoEngine::GetInstance() {
|
||||
if (NULL == crypto_engine_) {
|
||||
crypto_engine_ = CreateSingleton();
|
||||
}
|
||||
return crypto_engine_;
|
||||
}
|
||||
|
||||
CryptoEngine* CryptoEngine::CreateSingleton() {
|
||||
AutoLock auto_lock(crypto_engine_lock_);
|
||||
if (NULL == crypto_engine_) {
|
||||
crypto_engine_ = new CryptoEngine;
|
||||
}
|
||||
return crypto_engine_;
|
||||
}
|
||||
|
||||
void CryptoEngine::DeleteInstance() {
|
||||
if (NULL != crypto_engine_) {
|
||||
delete crypto_engine_;
|
||||
LOGV("CryptoEngine::DeleteInstance");
|
||||
crypto_engine_ = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
bool CryptoEngine::Init() {
|
||||
LOGV("CryptoEngine::Init: Lock");
|
||||
AutoLock auto_lock(crypto_lock_);
|
||||
if (!initialized_) {
|
||||
OEMCryptoResult result = OEMCrypto_Initialize();
|
||||
initialized_ = (OEMCrypto_SUCCESS == result);
|
||||
}
|
||||
return initialized_;
|
||||
}
|
||||
|
||||
bool CryptoEngine::Terminate() {
|
||||
DestroySessions();
|
||||
LOGV("CryptoEngine::Terminate: Lock");
|
||||
AutoLock auto_lock(crypto_lock_);
|
||||
OEMCryptoResult result = OEMCrypto_Terminate();
|
||||
if (OEMCrypto_SUCCESS == result) {
|
||||
initialized_ = false;
|
||||
}
|
||||
return !initialized_;
|
||||
}
|
||||
|
||||
bool CryptoEngine::ValidateKeybox() {
|
||||
LOGV("CryptoEngine::ValidateKeybox: Lock");
|
||||
AutoLock auto_lock(crypto_lock_);
|
||||
OEMCryptoResult result = OEMCrypto_IsKeyboxValid();
|
||||
return (OEMCrypto_SUCCESS == result);
|
||||
}
|
||||
|
||||
CryptoSession* CryptoEngine::CreateSession(const CdmSessionId& session_id) {
|
||||
LOGV("CryptoEngine::CreateSession: SLock");
|
||||
AutoLock auto_lock(sessions_lock_);
|
||||
if (0 == sessions_.size()) {
|
||||
if (!Init()) {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
CryptoSessionMap::iterator it = sessions_.find(session_id);
|
||||
if (it != sessions_.end()) {
|
||||
LOGE("CryptoEngine::CreateSession : Duplicate session ID.");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
CryptoSession* new_session = new CryptoSession(session_id);
|
||||
if (!new_session) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!new_session->Open()) {
|
||||
delete new_session;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
sessions_[session_id] = new_session;
|
||||
return new_session;
|
||||
}
|
||||
|
||||
CryptoSession* CryptoEngine::FindSessionInternal(
|
||||
const CdmSessionId& session_id) {
|
||||
// must hold sessions_lock_
|
||||
CryptoSessionMap::iterator it = sessions_.find(session_id);
|
||||
if (it != sessions_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
CryptoSession* CryptoEngine::FindSession(const CdmSessionId& session_id) {
|
||||
LOGV("CryptoEngine::FindSession: SLock");
|
||||
AutoLock auto_lock(sessions_lock_);
|
||||
return FindSessionInternal(session_id);
|
||||
}
|
||||
|
||||
bool CryptoEngine::DestroySession(const CdmSessionId& session_id) {
|
||||
LOGV("CryptoEngine::DestroySession: SLock");
|
||||
AutoLock auto_lock(sessions_lock_);
|
||||
if (0 == sessions_.size()) {
|
||||
return false;
|
||||
}
|
||||
CryptoSession* session = FindSessionInternal(session_id);
|
||||
if (session) {
|
||||
delete session;
|
||||
sessions_.erase(session_id);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool CryptoEngine::DestroySessions() {
|
||||
for (CryptoSessionMap::iterator it = sessions_.begin();
|
||||
it != sessions_.end(); ++it) {
|
||||
delete it->second;
|
||||
}
|
||||
sessions_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CryptoEngine::GetToken(std::string* token) {
|
||||
LOGV("CryptoEngine::GetToken: Lock");
|
||||
AutoLock auto_lock(crypto_lock_);
|
||||
if (!token) {
|
||||
LOGE("CryptoEngine::GetToken : No token passed to method.");
|
||||
return false;
|
||||
}
|
||||
uint8_t buf[72];
|
||||
size_t buflen = 72;
|
||||
OEMCryptoResult sts = OEMCrypto_GetKeyData(buf, &buflen);
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
return false;
|
||||
}
|
||||
token->assign((const char*)buf, (size_t)buflen);
|
||||
return true;
|
||||
}
|
||||
|
||||
}; // namespace wvcdm
|
||||
338
libwvdrmengine/cdm/core/src/crypto_session.cpp
Normal file
338
libwvdrmengine/cdm/core/src/crypto_session.cpp
Normal file
@@ -0,0 +1,338 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Crypto - wrapper classes for OEMCrypto interface
|
||||
//
|
||||
|
||||
#include "crypto_session.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "crypto_engine.h"
|
||||
#include "log.h"
|
||||
// TODO(gmorgan,jtinker): decide if OEMCryptoCENC is needed here.
|
||||
#include "OEMCryptoCENC.h"
|
||||
#include "string_conversions.h"
|
||||
#include "wv_cdm_constants.h"
|
||||
|
||||
namespace {
|
||||
// Encode unsigned integer into a big endian formatted string
|
||||
std::string EncodeUint32(unsigned int u) {
|
||||
std::string s;
|
||||
s.append(1, (u >> 24) & 0xFF);
|
||||
s.append(1, (u >> 16) & 0xFF);
|
||||
s.append(1, (u >> 8) & 0xFF);
|
||||
s.append(1, (u >> 0) & 0xFF);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
// wrapper classes for OEMCrypto interface
|
||||
// CryptoEngine -- top-level interface
|
||||
// CryptoSession -- session-specific interface
|
||||
// CryptoKey -- key interface
|
||||
|
||||
// CryptoSession methods
|
||||
|
||||
CryptoSession::CryptoSession() : valid_(false), open_(false) {}
|
||||
|
||||
CryptoSession::CryptoSession(const std::string& sname) : valid_(true),
|
||||
open_(false), cdm_session_id_(sname) {}
|
||||
|
||||
CryptoSession::~CryptoSession() {
|
||||
if (open_) {
|
||||
Close();
|
||||
}
|
||||
LOGV("CryptoSession::dtor: SLock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
crypto_engine->sessions_.erase(cdm_session_id_);
|
||||
if (0 == crypto_engine->sessions_.size()) {
|
||||
crypto_engine->DeleteInstance();
|
||||
}
|
||||
|
||||
CryptoKeyMap::iterator i(keys_.begin());
|
||||
for (; i != keys_.end(); ++i)
|
||||
delete i->second;
|
||||
keys_.clear();
|
||||
}
|
||||
|
||||
bool CryptoSession::Open() {
|
||||
LOGV("CryptoSession::Open: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
OEMCrypto_SESSION sid;
|
||||
OEMCryptoResult sts;
|
||||
if (open_)
|
||||
return false;
|
||||
sts = OEMCrypto_OpenSession(&sid);
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
open_ = false;
|
||||
} else {
|
||||
oec_session_id_ = static_cast<CryptoSessionId>(sid);
|
||||
LOGV("OpenSession: id= %ld", (uint32_t) oec_session_id_);
|
||||
open_ = true;
|
||||
}
|
||||
return open_;
|
||||
}
|
||||
|
||||
void CryptoSession::Close() {
|
||||
LOGV("CryptoSession::Close: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
LOGV("CloseSession: id=%ld open=%s", (uint32_t) oec_session_id_, open_? "true" : "false") ;
|
||||
if (open_) {
|
||||
OEMCryptoResult sts = OEMCrypto_CloseSession(oec_session_id_);
|
||||
if (OEMCrypto_SUCCESS == sts) {
|
||||
open_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CryptoSession::GenerateRequestId(std::string& req_id_str) {
|
||||
LOGV("CryptoSession::GenerateRequestId: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
// TODO(gmorgan): Get unique ID from OEMCrypto
|
||||
req_id_str.assign("987654321");
|
||||
}
|
||||
|
||||
bool CryptoSession::PrepareRequest(const std::string& message,
|
||||
std::string* signature) {
|
||||
LOGV("CryptoSession::PrepareRequest: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
|
||||
if (!signature) {
|
||||
LOGE("CryptoSession::PrepareRequest : No output destination provided.");
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t signature_buf[32];
|
||||
size_t length = 32;
|
||||
OEMCryptoResult sts;
|
||||
|
||||
std::string mac_deriv_message;
|
||||
std::string enc_deriv_message;
|
||||
GenerateMacContext(message, &mac_deriv_message);
|
||||
GenerateEncryptContext(message, &enc_deriv_message);
|
||||
|
||||
LOGV("GenerateDerivedKeys: id=%ld", (uint32_t) oec_session_id_);
|
||||
sts = OEMCrypto_GenerateDerivedKeys(
|
||||
oec_session_id_,
|
||||
reinterpret_cast<const uint8_t*>(mac_deriv_message.data()),
|
||||
mac_deriv_message.size(),
|
||||
reinterpret_cast<const uint8_t*>(enc_deriv_message.data()),
|
||||
enc_deriv_message.size());
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LOGV("GenerateSignature: id=%ld", (uint32_t) oec_session_id_);
|
||||
sts = OEMCrypto_GenerateSignature(
|
||||
oec_session_id_,
|
||||
reinterpret_cast<const uint8_t*>(message.data()),
|
||||
message.size(),
|
||||
signature_buf,
|
||||
&length);
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
return false;
|
||||
}
|
||||
|
||||
signature->assign(reinterpret_cast<const char*>(signature_buf), length);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CryptoSession::PrepareRenewalRequest(const std::string& message,
|
||||
std::string* signature) {
|
||||
LOGV("CryptoSession::PrepareRenewalRequest: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
uint8_t signature_buf[32];
|
||||
size_t length = 32;
|
||||
|
||||
OEMCryptoResult sts = OEMCrypto_GenerateSignature(
|
||||
oec_session_id_, reinterpret_cast<const uint8_t*>(message.data()),
|
||||
message.size(), signature_buf, &length);
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
return false;
|
||||
}
|
||||
|
||||
signature->assign(reinterpret_cast<const char*>(signature_buf), length);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void CryptoSession::GenerateMacContext(const std::string& input_context,
|
||||
std::string* deriv_context) {
|
||||
if (!deriv_context) {
|
||||
LOGE("CryptoSession::GenerateMacContext : No output destination provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string kSigningKeyLabel = "AUTHENTICATION";
|
||||
const size_t kSigningKeySizeBits = MAC_KEY_SIZE * 8;
|
||||
|
||||
deriv_context->assign(kSigningKeyLabel);
|
||||
deriv_context->append(1, '\0');
|
||||
deriv_context->append(input_context);
|
||||
deriv_context->append(EncodeUint32(kSigningKeySizeBits));
|
||||
}
|
||||
|
||||
void CryptoSession::GenerateEncryptContext(const std::string& input_context,
|
||||
std::string* deriv_context) {
|
||||
if (!deriv_context) {
|
||||
LOGE("CryptoSession::GenerateEncryptContext : No output destination provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string kEncryptionKeyLabel = "ENCRYPTION";
|
||||
const size_t kEncryptionKeySizeBits = KEY_SIZE * 8;
|
||||
|
||||
deriv_context->assign(kEncryptionKeyLabel);
|
||||
deriv_context->append(1, '\0');
|
||||
deriv_context->append(input_context);
|
||||
deriv_context->append(EncodeUint32(kEncryptionKeySizeBits));
|
||||
}
|
||||
|
||||
size_t CryptoSession::GetOffset(std::string message, std::string field) {
|
||||
size_t pos = message.find(field);
|
||||
if (pos == std::string::npos) {
|
||||
LOGE("CryptoSession::GetOffset : Cannot find offset for %s", field.c_str());
|
||||
pos = 0;
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
bool CryptoSession::LoadKeys(const std::string& message,
|
||||
const std::string& signature,
|
||||
const std::string& mac_key_iv,
|
||||
const std::string& mac_key,
|
||||
int num_keys,
|
||||
const CryptoKey* key_array) {
|
||||
LOGV("CryptoSession::LoadKeys: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
|
||||
const uint8_t* msg = reinterpret_cast<const uint8_t*>(message.data());
|
||||
const uint8_t* enc_mac_key = NULL;
|
||||
const uint8_t* enc_mac_key_iv = NULL;
|
||||
if (mac_key.size() >= MAC_KEY_SIZE && mac_key_iv.size() >= KEY_IV_SIZE) {
|
||||
enc_mac_key = msg + GetOffset(message, mac_key);
|
||||
enc_mac_key_iv = msg + GetOffset(message, mac_key_iv);
|
||||
}
|
||||
OEMCrypto_KeyObject load_key_array[num_keys];
|
||||
for (int i=0; i<num_keys; ++i) {
|
||||
const CryptoKey* ki = &key_array[i];
|
||||
OEMCrypto_KeyObject* ko = &load_key_array[i];
|
||||
ko->key_id = msg + GetOffset(message, ki->key_id());
|
||||
ko->key_id_length = ki->key_id().length();
|
||||
ko->key_data_iv = msg + GetOffset(message, ki->key_data_iv());
|
||||
ko->key_data = msg + GetOffset(message, ki->key_data());
|
||||
if (ki->HasKeyControl()) {
|
||||
ko->key_control_iv = msg + GetOffset(message, ki->key_control_iv());
|
||||
ko->key_control = msg + GetOffset(message, ki->key_control());
|
||||
}
|
||||
else {
|
||||
LOGE("For key %d: XXX key has no control block. size=%d", i, ki->key_control().size());
|
||||
ko->key_control_iv = NULL;
|
||||
ko->key_control = NULL;
|
||||
}
|
||||
}
|
||||
LOGV("LoadKeys: id=%ld", (uint32_t) oec_session_id_);
|
||||
return (OEMCrypto_SUCCESS == OEMCrypto_LoadKeys(
|
||||
oec_session_id_, msg, message.size(),
|
||||
reinterpret_cast<const uint8_t*>(signature.data()),
|
||||
signature.size(), enc_mac_key_iv, enc_mac_key,
|
||||
num_keys, load_key_array));
|
||||
}
|
||||
|
||||
bool CryptoSession::RefreshKeys(const std::string& message,
|
||||
const std::string& signature,
|
||||
int num_keys,
|
||||
const CryptoKey* key_array) {
|
||||
LOGV("CryptoSession::RefreshKeys: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
|
||||
const uint8_t* msg = reinterpret_cast<const uint8_t*>(message.data());
|
||||
OEMCrypto_KeyRefreshObject load_key_array[num_keys];
|
||||
for (int i=0; i<num_keys; ++i) {
|
||||
const CryptoKey* ki = &key_array[i];
|
||||
OEMCrypto_KeyRefreshObject* ko = &load_key_array[i];
|
||||
if (ki->key_id().empty()) {
|
||||
ko->key_id = NULL;
|
||||
} else {
|
||||
ko->key_id = msg + GetOffset(message, ki->key_id());
|
||||
}
|
||||
if (ki->HasKeyControl()) {
|
||||
if (ki->key_control_iv().empty()) {
|
||||
ko->key_control_iv = NULL;
|
||||
} else {
|
||||
ko->key_control_iv = msg + GetOffset(message, ki->key_control_iv());
|
||||
}
|
||||
ko->key_control = msg + GetOffset(message, ki->key_control());
|
||||
}
|
||||
else {
|
||||
ko->key_control_iv = NULL;
|
||||
ko->key_control = NULL;
|
||||
}
|
||||
}
|
||||
LOGV("RefreshKeys: id=%ld", static_cast<uint32_t>(oec_session_id_));
|
||||
return (OEMCrypto_SUCCESS == OEMCrypto_RefreshKeys(
|
||||
oec_session_id_, msg, message.size(),
|
||||
reinterpret_cast<const uint8_t*>(signature.data()),
|
||||
signature.size(),
|
||||
num_keys, load_key_array));
|
||||
}
|
||||
|
||||
bool CryptoSession::SelectKey(const std::string& key_id) {
|
||||
LOGV("CryptoSession::SelectKey: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
const uint8_t* key_id_string =
|
||||
reinterpret_cast<const uint8_t*>(key_id.data());
|
||||
|
||||
LOGV("SelectKey: id=%ld", static_cast<uint32_t>(oec_session_id_));
|
||||
OEMCryptoResult sts = OEMCrypto_SelectKey(oec_session_id_, key_id_string,
|
||||
key_id.size());
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CryptoSession::Decrypt(const InputDescriptor input,
|
||||
const OutputDescriptor output) {
|
||||
LOGV("CryptoSession::Decrypt: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
// TODO(gmorgan): handle inputs and outputs to decrypt call
|
||||
const uint8_t* data_addr = NULL;
|
||||
uint32_t data_length = 0;
|
||||
bool is_encrypted = false;
|
||||
uint8_t* iv = NULL;
|
||||
uint32_t offset = 0;
|
||||
const OEMCrypto_DestBufferDesc* out_buffer = NULL;
|
||||
OEMCryptoResult sts = OEMCrypto_DecryptCTR(oec_session_id_, data_addr,
|
||||
data_length, is_encrypted, iv,
|
||||
offset, out_buffer);
|
||||
if (OEMCrypto_SUCCESS != sts) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CryptoSession::GenerateNonce(uint32_t* nonce) {
|
||||
if (!nonce) {
|
||||
LOGE("input parameter is null");
|
||||
return false;
|
||||
}
|
||||
|
||||
LOGV("CryptoSession::GenerateNonce: Lock");
|
||||
CryptoEngine* crypto_engine = CryptoEngine::GetInstance();
|
||||
AutoLock auto_lock(crypto_engine->crypto_lock_);
|
||||
return(OEMCrypto_SUCCESS == OEMCrypto_GenerateNonce(oec_session_id_, nonce));
|
||||
}
|
||||
}; // namespace wvcdm
|
||||
298
libwvdrmengine/cdm/core/src/license.cpp
Normal file
298
libwvdrmengine/cdm/core/src/license.cpp
Normal file
@@ -0,0 +1,298 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
|
||||
#include "license.h"
|
||||
|
||||
#include "crypto_session.h"
|
||||
#include "log.h"
|
||||
#include "string_conversions.h"
|
||||
#include "wv_cdm_constants.h"
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
// Protobuf generated classes.
|
||||
using video_widevine_server::sdk::LicenseRequest;
|
||||
using video_widevine_server::sdk::LicenseRequest_ClientIdentification;
|
||||
using video_widevine_server::sdk::LicenseRequest_ClientIdentification_NameValue;
|
||||
using video_widevine_server::sdk::LicenseRequest_ContentIdentification;
|
||||
using video_widevine_server::sdk::LicenseRequest_ContentIdentification_CENC;
|
||||
using video_widevine_server::sdk::License;
|
||||
using video_widevine_server::sdk::License_KeyContainer;
|
||||
using video_widevine_server::sdk::SignedMessage;
|
||||
using video_widevine_server::sdk::STREAMING;
|
||||
using video_widevine_server::sdk::LicenseRequest_ContentIdentification_ExistingLicense;
|
||||
|
||||
CdmLicense::CdmLicense(): session_(NULL) {}
|
||||
|
||||
CdmLicense::~CdmLicense() {}
|
||||
|
||||
bool CdmLicense::Init(const std::string& token, CryptoSession* session) {
|
||||
if (token.size() == 0)
|
||||
return false;
|
||||
if (session == NULL || !session->IsValid() || !session->IsOpen())
|
||||
return false;
|
||||
token_ = token;
|
||||
session_ = session;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CdmLicense::PrepareKeyRequest(const CdmInitData& init_data,
|
||||
CdmKeyMessage* signed_request) {
|
||||
if (!session_ ||
|
||||
token_.empty()) {
|
||||
return false;
|
||||
}
|
||||
if (init_data.empty()) {
|
||||
LOGE("CdmLicense::PrepareKeyRequest : No init data provided;");
|
||||
return false;
|
||||
}
|
||||
if (!signed_request) {
|
||||
LOGE("CdmLicense::PrepareKeyRequest : No signed request provided.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO(gmorgan): Request ID owned by session?
|
||||
std::string request_id;
|
||||
session_->GenerateRequestId(request_id);
|
||||
|
||||
LicenseRequest license_request;
|
||||
LicenseRequest_ClientIdentification* client_id =
|
||||
license_request.mutable_client_id();
|
||||
|
||||
client_id->set_type(LicenseRequest_ClientIdentification::KEYBOX);
|
||||
client_id->set_token(token_);
|
||||
|
||||
// Content Identification may be a cenc_id, a webm_id or a license_id
|
||||
LicenseRequest_ContentIdentification* content_id =
|
||||
license_request.mutable_content_id();
|
||||
|
||||
LicenseRequest_ContentIdentification_CENC* cenc_content_id =
|
||||
content_id->mutable_cenc_id();
|
||||
cenc_content_id->add_pssh(init_data);
|
||||
cenc_content_id->set_license_type(STREAMING);
|
||||
cenc_content_id->set_request_id(request_id);
|
||||
|
||||
// TODO(jfore): The time field will be updated once the cdm wrapper
|
||||
// has been updated to pass us in the time.
|
||||
license_request.set_request_time(0);
|
||||
|
||||
license_request.set_type(LicenseRequest::NEW);
|
||||
|
||||
// Get/set the nonce. This value will be reflected in the Key Control Block
|
||||
// of the license response.
|
||||
uint32_t nonce;
|
||||
if (!session_->GenerateNonce(&nonce)) {
|
||||
return false;
|
||||
}
|
||||
license_request.set_key_control_nonce(UintToString(nonce));
|
||||
LOGD("PrepareKeyRequest: nonce=%u", nonce);
|
||||
|
||||
// License request is complete. Serialize it.
|
||||
std::string serialized_license_req;
|
||||
license_request.SerializeToString(&serialized_license_req);
|
||||
|
||||
// Derive signing and encryption keys and construct signature.
|
||||
std::string license_request_signature;
|
||||
if (!session_->PrepareRequest(serialized_license_req,
|
||||
&license_request_signature)) {
|
||||
signed_request->clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (license_request_signature.empty()) {
|
||||
signed_request->clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Put serialize license request and signature together
|
||||
SignedMessage signed_message;
|
||||
signed_message.set_type(SignedMessage::LICENSE_REQUEST);
|
||||
signed_message.set_signature(license_request_signature);
|
||||
signed_message.set_msg(serialized_license_req);
|
||||
|
||||
signed_message.SerializeToString(signed_request);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CdmLicense::PrepareKeyRenewalRequest(CdmKeyMessage* signed_request) {
|
||||
if (!session_) {
|
||||
return false;
|
||||
}
|
||||
if (!signed_request) {
|
||||
LOGE("CdmLicense::PrepareKeyRenewalRequest : No signed request provided.");
|
||||
return false;
|
||||
}
|
||||
|
||||
LicenseRequest license_request;
|
||||
license_request.set_type(LicenseRequest::RENEWAL);
|
||||
|
||||
LicenseRequest_ContentIdentification_ExistingLicense* current_license =
|
||||
license_request.mutable_content_id()->mutable_license();
|
||||
current_license->mutable_license_id()->CopyFrom(license_id_);
|
||||
|
||||
// Get/set the nonce. This value will be reflected in the Key Control Block
|
||||
// of the license response.
|
||||
uint32_t nonce;
|
||||
if (!session_->GenerateNonce(&nonce)) {
|
||||
return false;
|
||||
}
|
||||
license_request.set_key_control_nonce(UintToString(nonce));
|
||||
LOGD("PrepareKeyRenewalRequest: nonce=%u", nonce);
|
||||
|
||||
// License request is complete. Serialize it.
|
||||
std::string serialized_license_req;
|
||||
license_request.SerializeToString(&serialized_license_req);
|
||||
|
||||
// Construct signature.
|
||||
std::string license_request_signature;
|
||||
if (!session_->PrepareRenewalRequest(serialized_license_req,
|
||||
&license_request_signature))
|
||||
return false;
|
||||
|
||||
if (license_request_signature.empty()) return false;
|
||||
|
||||
// Put serialize license request and signature together
|
||||
SignedMessage signed_message;
|
||||
signed_message.set_type(SignedMessage::LICENSE_REQUEST);
|
||||
signed_message.set_signature(license_request_signature);
|
||||
signed_message.set_msg(serialized_license_req);
|
||||
|
||||
signed_message.SerializeToString(signed_request);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CdmLicense::HandleKeyResponse(const CdmKeyResponse& license_response) {
|
||||
if (!session_) {
|
||||
return false;
|
||||
}
|
||||
if (license_response.empty()) {
|
||||
LOGE("CdmLicense::HandleKeyResponse : Empty license response.");
|
||||
return false;
|
||||
}
|
||||
|
||||
SignedMessage signed_response;
|
||||
if (!signed_response.ParseFromString(license_response))
|
||||
return false;
|
||||
|
||||
if (!signed_response.has_signature())
|
||||
return false;
|
||||
|
||||
License license;
|
||||
if (!license.ParseFromString(signed_response.msg()))
|
||||
return false;
|
||||
|
||||
// Extract mac key
|
||||
std::string mac_key_iv;
|
||||
std::string mac_key;
|
||||
if (license.policy().can_renew())
|
||||
{
|
||||
for (int i = 0; i < license.key_size(); ++i) {
|
||||
if (license.key(i).type() == License_KeyContainer::SIGNING) {
|
||||
mac_key_iv.assign(license.key(i).iv());
|
||||
|
||||
// Strip off PKCS#5 padding
|
||||
mac_key.assign(license.key(i).key().data(), MAC_KEY_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
if (mac_key_iv.size() != KEY_IV_SIZE ||
|
||||
mac_key.size() != MAC_KEY_SIZE)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// License Id should not be empty for renewable license
|
||||
if (!license.has_id()) return false;
|
||||
|
||||
license_id_.CopyFrom(license.id());
|
||||
}
|
||||
|
||||
CryptoKey* key_array = new CryptoKey[license.key_size()];
|
||||
if (key_array == NULL) return false;
|
||||
|
||||
// Extract content key(s)
|
||||
int num_keys = 0;
|
||||
for (int i = 0; i < license.key_size(); ++i) {
|
||||
// TODO(kqyang): Key ID size is not fixed in spec, but conventionally we
|
||||
// always use 16 bytes key id. We'll need to update oemcrypto to support
|
||||
// variable size key id.
|
||||
if (license.key(i).id().size() == KEY_ID_SIZE &&
|
||||
license.key(i).key().size() == KEY_SIZE + KEY_PAD_SIZE &&
|
||||
license.key(i).type() == License_KeyContainer::CONTENT) {
|
||||
|
||||
key_array[num_keys].set_key_id(license.key(i).id());
|
||||
|
||||
// Strip off PKCS#5 padding
|
||||
key_array[num_keys].set_key_data(
|
||||
license.key(i).key().substr(0, KEY_SIZE));
|
||||
key_array[num_keys].set_key_data_iv(license.key(i).iv());
|
||||
if (license.key(i).has_key_control()) {
|
||||
key_array[num_keys].set_key_control(
|
||||
license.key(i).key_control().struct_());
|
||||
key_array[num_keys].set_key_control_iv(
|
||||
license.key(i).key_control().iv());
|
||||
}
|
||||
num_keys++;
|
||||
}
|
||||
}
|
||||
|
||||
if (num_keys == 0) return false;
|
||||
|
||||
// TODO(kqyang): move protocol buffer related stuff in policy
|
||||
// engine to this file.
|
||||
// policy_engine_.SetLicense(license);
|
||||
|
||||
bool status = session_->LoadKeys(signed_response.msg(),
|
||||
signed_response.signature(),
|
||||
mac_key_iv,
|
||||
mac_key,
|
||||
num_keys,
|
||||
key_array);
|
||||
delete[] key_array;
|
||||
return status;
|
||||
}
|
||||
|
||||
bool CdmLicense::HandleKeyRenewalResponse(
|
||||
const CdmKeyResponse& license_response) {
|
||||
if (!session_) {
|
||||
return false;
|
||||
}
|
||||
if (license_response.empty()) {
|
||||
LOGE("CdmLicense::HandleKeyRenewalResponse : Empty license response.");
|
||||
return false;
|
||||
}
|
||||
|
||||
SignedMessage signed_response;
|
||||
if (!signed_response.ParseFromString(license_response))
|
||||
return false;
|
||||
|
||||
if (!signed_response.has_signature())
|
||||
return false;
|
||||
|
||||
// TODO(jfore): refresh the keys in oemcrypto
|
||||
|
||||
License license;
|
||||
if (!license.ParseFromString(signed_response.msg()))
|
||||
return false;
|
||||
|
||||
if (!license.has_id()) return false;
|
||||
|
||||
if (license.id().version() > license_id_.version()) {
|
||||
//This is the normal case.
|
||||
license_id_.CopyFrom(license.id());
|
||||
|
||||
// TODO(kqyang): should we move protocol buffer related stuff in policy
|
||||
// engine to this file instead?
|
||||
// policy_engine_.UpdateLicense(license);
|
||||
} else {
|
||||
// This isn't supposed to happen.
|
||||
// TODO(jfore): Handle wrap? We can miss responses and that should be
|
||||
// considered normal until retries are exhausted.
|
||||
// policy_.set_can_play(false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace wvcdm
|
||||
224
libwvdrmengine/cdm/core/src/license_protocol.proto
Normal file
224
libwvdrmengine/cdm/core/src/license_protocol.proto
Normal file
@@ -0,0 +1,224 @@
|
||||
syntax = "proto2";
|
||||
|
||||
package video_widevine_server.sdk;
|
||||
|
||||
option optimize_for = LITE_RUNTIME;
|
||||
|
||||
enum LicenseType {
|
||||
STREAMING = 1;
|
||||
OFFLINE = 2;
|
||||
}
|
||||
|
||||
// LicenseIdentification is propagated from LicenseRequest to License,
|
||||
// incrementing version with each iteration.
|
||||
message LicenseIdentification {
|
||||
optional bytes request_id = 1;
|
||||
optional bytes session_id = 2;
|
||||
optional bytes purchase_id = 3;
|
||||
optional LicenseType type = 4;
|
||||
optional int32 version = 5;
|
||||
}
|
||||
|
||||
message License {
|
||||
message Policy {
|
||||
// Indicates that playback of the content is allowed.
|
||||
optional bool can_play = 1 [default = false];
|
||||
|
||||
// Indicates that the license may be persisted to non-volatile
|
||||
// storage for offline use.
|
||||
optional bool can_persist = 2 [default = false];
|
||||
|
||||
// Indicates that renewal of this license is allowed.
|
||||
optional bool can_renew = 3 [default = false];
|
||||
|
||||
// For the |*duration*| fields, playback must halt when
|
||||
// license_start_time (seconds since the epoch (UTC)) +
|
||||
// license_duration_seconds is exceeded. A value of 0
|
||||
// indicates that there is no limit to the duration.
|
||||
|
||||
// Indicates the rental window.
|
||||
optional int64 rental_duration_seconds = 4 [default = 0];
|
||||
|
||||
// Indicates the viewing window, once playback has begun.
|
||||
optional int64 playback_duration_seconds = 5 [default = 0];
|
||||
|
||||
// Indicates the time window for this specific license.
|
||||
optional int64 license_duration_seconds = 6 [default = 0];
|
||||
|
||||
// The |renewal*| fields only apply if |can_renew| is true.
|
||||
|
||||
// The window of time, in which playback is allowed to continue while
|
||||
// renewal is attempted, yet unsuccessful due to backend problems with
|
||||
// the license server.
|
||||
optional int64 renewal_recovery_duration_seconds = 7 [default = 0];
|
||||
|
||||
// All renewal requests for this license shall be directed to the
|
||||
// specified URL.
|
||||
optional string renewal_server_url = 8;
|
||||
|
||||
// How many seconds after license_start_time, before renewal is first
|
||||
// attempted.
|
||||
optional int64 renewal_delay_seconds = 9 [default = 0];
|
||||
|
||||
// Specifies the delay in seconds between subsequent license
|
||||
// renewal requests, in case of failure.
|
||||
optional int64 renewal_retry_interval_seconds = 10 [default = 0];
|
||||
|
||||
// Indicates that the license shall be sent for renewal when usage is
|
||||
// started.
|
||||
optional bool renew_with_usage = 11 [default = false];
|
||||
}
|
||||
|
||||
message KeyContainer {
|
||||
enum KeyType {
|
||||
// Exactly one key of this type must appear.
|
||||
SIGNING = 1;
|
||||
CONTENT = 2;
|
||||
}
|
||||
|
||||
// The SecurityLevel enumeration allows the server to communicate the level
|
||||
// of robustness required by the client, in order to use the key.
|
||||
enum SecurityLevel {
|
||||
// Software-based whitebox crypto is required.
|
||||
SW_SECURE_CRYPTO = 1;
|
||||
|
||||
// Software crypto and an obfuscated decoder is required.
|
||||
SW_SECURE_DECODE = 2;
|
||||
|
||||
// The key material and crypto operations must be performed within a
|
||||
// hardware backed trusted execution environment.
|
||||
HW_SECURE_CRYPTO = 3;
|
||||
|
||||
// The crypto and decoding of content must be performed within a hardware
|
||||
// backed trusted execution environment.
|
||||
HW_SECURE_DECODE = 4;
|
||||
|
||||
// The crypto, decoding and all handling of the media (compressed and
|
||||
// uncompressed) must be handled within a hardware backed trusted
|
||||
// execution environment.
|
||||
HW_SECURE_ALL = 5;
|
||||
}
|
||||
|
||||
message KeyControl {
|
||||
// |key_control| is documented here:
|
||||
// https://docs.google.com/a/google.com/document/d/17eDxzzGpPc2qSm7zW68_5ensuxbHErYCvD3IxSKETRo/edit#
|
||||
// If present, the key control must be communicated to the secure
|
||||
// environment prior to any usage.
|
||||
optional bytes struct = 1;
|
||||
optional bytes iv = 2;
|
||||
}
|
||||
|
||||
message OutputProtection {
|
||||
// Indicates whether HDCP is required on digital outputs, and which
|
||||
// version should be used.
|
||||
enum HDCP {
|
||||
HDCP_NONE = 0;
|
||||
HDCP_V1 = 1;
|
||||
HDCP_V2 = 2;
|
||||
}
|
||||
optional HDCP hdcp = 1 [default = HDCP_NONE];
|
||||
|
||||
// Indicate the CGMS setting to be inserted on analog output.
|
||||
enum CGMS {
|
||||
CGMS_NONE = 42;
|
||||
COPY_FREE = 0;
|
||||
COPY_ONCE = 2;
|
||||
COPY_NEVER = 3;
|
||||
}
|
||||
optional CGMS cgms_flags = 2 [default = CGMS_NONE];
|
||||
}
|
||||
optional bytes id = 1;
|
||||
optional bytes iv = 2;
|
||||
optional bytes key = 3;
|
||||
optional KeyType type = 4;
|
||||
optional SecurityLevel level = 5 [default = SW_SECURE_CRYPTO];
|
||||
optional OutputProtection required_protection = 6;
|
||||
optional OutputProtection requested_protection = 7;
|
||||
optional KeyControl key_control = 8;
|
||||
}
|
||||
|
||||
optional LicenseIdentification id = 1;
|
||||
optional Policy policy = 2;
|
||||
repeated KeyContainer key = 3;
|
||||
optional int64 license_start_time = 4;
|
||||
}
|
||||
|
||||
message LicenseRequest {
|
||||
message ClientIdentification {
|
||||
enum TokenType {
|
||||
KEYBOX = 0;
|
||||
}
|
||||
|
||||
message NameValue {
|
||||
optional string name = 1;
|
||||
optional string value = 2;
|
||||
}
|
||||
|
||||
optional TokenType type = 1;
|
||||
optional bytes token = 2;
|
||||
repeated NameValue client_info = 3;
|
||||
}
|
||||
|
||||
message ContentIdentification {
|
||||
message CENC {
|
||||
repeated bytes pssh = 1;
|
||||
optional LicenseType license_type = 2;
|
||||
optional bytes request_id = 3; // Opaque, client-specified.
|
||||
}
|
||||
|
||||
message WebM {
|
||||
optional bytes header = 1;
|
||||
optional LicenseType license_type = 2;
|
||||
optional bytes request_id = 3; // Opaque, client-specified.
|
||||
}
|
||||
|
||||
message ExistingLicense {
|
||||
optional LicenseIdentification license_id = 1;
|
||||
optional int64 seconds_since_started = 2;
|
||||
}
|
||||
|
||||
// Exactly one of these must be present.
|
||||
optional CENC cenc_id = 1;
|
||||
optional WebM webm_id = 2;
|
||||
optional ExistingLicense license = 3;
|
||||
}
|
||||
|
||||
enum RequestType {
|
||||
NEW = 1;
|
||||
RENEWAL = 2;
|
||||
RELEASE = 3;
|
||||
}
|
||||
|
||||
optional ClientIdentification client_id = 1;
|
||||
optional ContentIdentification content_id = 2;
|
||||
optional RequestType type = 3;
|
||||
optional int64 request_time = 4;
|
||||
optional bytes key_control_nonce = 5;
|
||||
}
|
||||
|
||||
message SignedMessage {
|
||||
enum MessageType {
|
||||
LICENSE_REQUEST = 1;
|
||||
LICENSE = 2;
|
||||
}
|
||||
|
||||
optional MessageType type = 1;
|
||||
optional bytes msg = 2;
|
||||
optional bytes signature = 3;
|
||||
}
|
||||
|
||||
// This message is used to pass optional data on initial license issuance.
|
||||
message SessionInit {
|
||||
optional string session_id = 1;
|
||||
optional string purchase_id = 2;
|
||||
optional string master_signing_key = 3;
|
||||
optional string signing_key = 4;
|
||||
optional int64 license_start_time = 5;
|
||||
}
|
||||
|
||||
// This message is used by the server to preserve and restore session state.
|
||||
message SessionState {
|
||||
optional LicenseIdentification license_id = 1;
|
||||
optional bytes signing_key = 2;
|
||||
optional uint32 keybox_system_id = 3;
|
||||
}
|
||||
211
libwvdrmengine/cdm/core/src/policy_engine.cpp
Normal file
211
libwvdrmengine/cdm/core/src/policy_engine.cpp
Normal file
@@ -0,0 +1,211 @@
|
||||
// Copyright 2013 Google Inc. All Rights Reserved.
|
||||
|
||||
#include "policy_engine.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "log.h"
|
||||
#include "string_conversions.h"
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
PolicyEngine::PolicyEngine() :
|
||||
license_state_(kLicenseStateInitial),
|
||||
license_start_time_(0),
|
||||
next_renewal_time_(0),
|
||||
policy_max_duration_seconds_(0) {
|
||||
}
|
||||
|
||||
PolicyEngine::~PolicyEngine() {
|
||||
}
|
||||
|
||||
void PolicyEngine::OnTimerEvent(int64_t current_time, bool event_occured, CdmEventType& event) {
|
||||
event_occured = false;
|
||||
|
||||
// License expiration trumps all.
|
||||
if (IsLicenseDurationExpired(current_time) &&
|
||||
license_state_ != kLicenseStateExpired) {
|
||||
license_state_ = kLicenseStateExpired;
|
||||
event = LICENSE_EXPIRED_EVENT;
|
||||
event_occured = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Test to determine if renewal should be attempted.
|
||||
switch (license_state_) {
|
||||
case kLicenseStateCanPlay: {
|
||||
if (IsRenewalDelayExpired(current_time)) {
|
||||
license_state_ = kLicenseStateNeedRenewal;
|
||||
UpdateRenewalRequest(current_time);
|
||||
event = LICENSE_RENEWAL_NEEDED_EVENT;
|
||||
event_occured = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
case kLicenseStateNeedRenewal: {
|
||||
UpdateRenewalRequest(current_time);
|
||||
event = LICENSE_RENEWAL_NEEDED_EVENT;
|
||||
event_occured = true;
|
||||
return;
|
||||
}
|
||||
|
||||
case kLicenseStateWaitingLicenseUpdate: {
|
||||
if (IsRenewalRetryIntervalExpired(current_time)) {
|
||||
UpdateRenewalRequest(current_time);
|
||||
event = LICENSE_RENEWAL_NEEDED_EVENT;
|
||||
event_occured = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
case kLicenseStateInitial:
|
||||
case kLicenseStateExpired: {
|
||||
return;
|
||||
}
|
||||
|
||||
default: {
|
||||
license_state_ = kLicenseStateCannotPlay;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Fix up differences between Eureka and other platforms' use cases.
|
||||
// Eureka does not get calls to decrypt. license usage begins
|
||||
// when we receive the initial license. renew_with_usage will cause renewal to
|
||||
// occur on the first call to OnTimeEvent after PolicyEngine::SetLicense is
|
||||
// called.
|
||||
void PolicyEngine::SetLicense(
|
||||
const video_widevine_server::sdk::License& license) {
|
||||
license_id_.Clear();
|
||||
license_id_.CopyFrom(license.id());
|
||||
policy_.Clear();
|
||||
UpdateLicense(license);
|
||||
}
|
||||
|
||||
void PolicyEngine::UpdateLicense(
|
||||
const video_widevine_server::sdk::License& license) {
|
||||
if (!license.has_policy() || kLicenseStateExpired == license_state_)
|
||||
return;
|
||||
|
||||
policy_.MergeFrom(license.policy());
|
||||
policy_max_duration_seconds_ = 0;
|
||||
|
||||
// Calculate policy_max_duration_seconds_. policy_max_duration_seconds_
|
||||
// will be set to the minimum of the following policies :
|
||||
// rental_duration_seconds, playback_duration_seconds, and
|
||||
// license_duration_seconds. The value is used to determine
|
||||
// when the license expires.
|
||||
if (policy_.has_rental_duration_seconds())
|
||||
policy_max_duration_seconds_ = policy_.rental_duration_seconds();
|
||||
|
||||
if ((policy_.has_playback_duration_seconds() &&
|
||||
(policy_.playback_duration_seconds() < policy_max_duration_seconds_)) ||
|
||||
!policy_max_duration_seconds_) {
|
||||
policy_max_duration_seconds_ = policy_.playback_duration_seconds();
|
||||
}
|
||||
|
||||
if ((policy_.has_license_duration_seconds() &&
|
||||
(policy_.license_duration_seconds() < policy_max_duration_seconds_)) ||
|
||||
!policy_max_duration_seconds_) {
|
||||
policy_max_duration_seconds_ = policy_.license_duration_seconds();
|
||||
}
|
||||
|
||||
switch (license_state_) {
|
||||
case kLicenseStateInitial: {
|
||||
// Process initial license.
|
||||
license_start_time_ = license.license_start_time();
|
||||
if (policy_.can_play()) {
|
||||
license_state_ =
|
||||
policy_.renew_with_usage() ?
|
||||
kLicenseStateNeedRenewal : kLicenseStateCanPlay;
|
||||
} else {
|
||||
license_state_ = kLicenseStateExpired;
|
||||
}
|
||||
next_renewal_time_ = license_start_time_
|
||||
+ policy_.renewal_delay_seconds();
|
||||
}
|
||||
break;
|
||||
|
||||
case kLicenseStateExpired:
|
||||
// Ignore policy updates.
|
||||
return;
|
||||
|
||||
default: {
|
||||
// Process license renewal.
|
||||
if (license.id().version() > license_id_.version()) {
|
||||
// This is the normal case.
|
||||
policy_.MergeFrom(license.policy());
|
||||
license_id_.CopyFrom(license.id());
|
||||
} else {
|
||||
// This isn't supposed to happen.
|
||||
// TODO(jfore): Handle wrap? We can miss responses and that should be
|
||||
// considered normal until retries are exhausted.
|
||||
policy_.set_can_play(false);
|
||||
}
|
||||
|
||||
if (license.has_license_start_time()) {
|
||||
// license start has been updated. Transition back to the
|
||||
// normal kLicenseStateCanPlay state if playback is allowed by
|
||||
// the updated license.
|
||||
license_start_time_ = license.license_start_time();
|
||||
next_renewal_time_ = license_start_time_
|
||||
+ policy_.renewal_delay_seconds();
|
||||
license_state_ =
|
||||
policy_.can_play() ? kLicenseStateCanPlay : kLicenseStateExpired;
|
||||
} else {
|
||||
// license start was not updated. Continue sending renewel requests
|
||||
// at the specified retry rate. To perform this we transition directly
|
||||
// to kLicenseStateWaitingLicenseUpdate. While in this state
|
||||
// IsRenewalRetryIntervalExpired will always return false if retries are
|
||||
// not allowed. Note that next_renewal_time_ was updated when this
|
||||
// renewal was requested.
|
||||
license_state_ =
|
||||
policy_.can_play() ?
|
||||
kLicenseStateWaitingLicenseUpdate : kLicenseStateExpired;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PolicyEngine::UpdateRenewalRequest(int64_t current_time) {
|
||||
license_state_ = kLicenseStateWaitingLicenseUpdate;
|
||||
next_renewal_time_ = current_time + policy_.renewal_retry_interval_seconds();
|
||||
}
|
||||
|
||||
// For the policy time fields checked in the following methods, a value of 0
|
||||
// indicates that there is no limit to the duration. These methods
|
||||
// will always return false if the value is 0.
|
||||
bool PolicyEngine::IsLicenseDurationExpired(int64_t current_time) {
|
||||
return policy_max_duration_seconds_ &&
|
||||
license_start_time_ + policy_max_duration_seconds_ <=
|
||||
current_time;
|
||||
}
|
||||
|
||||
bool PolicyEngine::IsRenewalDelayExpired(int64_t current_time) {
|
||||
return (policy_.renewal_delay_seconds() > 0) &&
|
||||
license_start_time_ + policy_.renewal_delay_seconds() <=
|
||||
current_time;
|
||||
}
|
||||
|
||||
// TODO(jfore): there is some gray around how this should be
|
||||
// implemented. It currently is not.
|
||||
bool PolicyEngine::IsRenewalRecoveryDurationExpired(
|
||||
int64_t current_time) {
|
||||
return (policy_.renewal_recovery_duration_seconds() > 0) &&
|
||||
license_start_time_ + policy_.renewal_recovery_duration_seconds() <=
|
||||
current_time;
|
||||
}
|
||||
|
||||
bool PolicyEngine::IsRenewalRetryIntervalExpired(
|
||||
int64_t current_time) {
|
||||
return (policy_.renewal_retry_interval_seconds() > 0) &&
|
||||
next_renewal_time_ <= current_time;
|
||||
}
|
||||
|
||||
} // wvcdm
|
||||
|
||||
211
libwvdrmengine/cdm/core/src/string_conversions.cpp
Normal file
211
libwvdrmengine/cdm/core/src/string_conversions.cpp
Normal file
@@ -0,0 +1,211 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
|
||||
#include "string_conversions.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <iostream>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
|
||||
#include "log.h"
|
||||
|
||||
namespace {
|
||||
// Helper for Base64SafeDecode()
|
||||
char B64ToBin(char inch) {
|
||||
if (inch >= 'A' && inch <= 'Z') return inch - 'A';
|
||||
if (inch >= 'a' && inch <= 'z') return inch - 'a' + 26;
|
||||
if (inch >= '0' && inch <= '9') return inch - '0' + 52;
|
||||
if (inch == '-') return 62;
|
||||
// if (inch == '_')
|
||||
return 63;
|
||||
}
|
||||
}
|
||||
|
||||
namespace wvcdm {
|
||||
|
||||
static bool CharToDigit(char ch, unsigned char* digit) {
|
||||
if (ch >= '0' && ch <= '9') {
|
||||
*digit = ch - '0';
|
||||
} else {
|
||||
ch = tolower(ch);
|
||||
if ((ch >= 'a') && (ch <= 'f')) {
|
||||
*digit = ch - 'a' + 10;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// converts an ascii hex string(2 bytes per digit) into a decimal byte string
|
||||
std::vector<uint8_t> a2b_hex(const std::string& byte) {
|
||||
std::vector<uint8_t> array;
|
||||
unsigned int count = byte.size();
|
||||
if (count == 0 || (count % 2) != 0) {
|
||||
LOGE("Invalid input size %u for string %s", count, byte.c_str());
|
||||
return array;
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i < count / 2; ++i) {
|
||||
unsigned char msb = 0; // most significant 4 bits
|
||||
unsigned char lsb = 0; // least significant 4 bits
|
||||
if (!CharToDigit(byte[i * 2], &msb) ||
|
||||
!CharToDigit(byte[i * 2 + 1], &lsb)) {
|
||||
LOGE("Invalid hex value %c%c at index %d", byte[i*2], byte[i*2+1], i);
|
||||
return array;
|
||||
}
|
||||
array.push_back((msb << 4) | lsb);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
std::string a2bs_hex(const std::string& byte) {
|
||||
std::vector<uint8_t> array = a2b_hex(byte);
|
||||
return std::string(array.begin(), array.end());
|
||||
}
|
||||
|
||||
std::string b2a_hex(const std::vector<uint8_t>& byte) {
|
||||
return HexEncode(&byte[0], byte.size());
|
||||
}
|
||||
|
||||
std::string b2a_hex(const std::string& byte) {
|
||||
return HexEncode(reinterpret_cast<const uint8_t *>(byte.data()),
|
||||
byte.length());
|
||||
}
|
||||
|
||||
// Filename-friendly base64 encoding (RFC4648).
|
||||
// This is the encoding required by GooglePlay for certain
|
||||
// license server transactions. It is also used for logging
|
||||
// certain strings.
|
||||
std::string Base64SafeEncode(const std::vector<uint8_t>& bin_input) {
|
||||
static const char kBase64Chars[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"abcdefghijklmnopqrstuvwxyz"
|
||||
"0123456789-_";
|
||||
if (bin_input.empty()) {
|
||||
return std::string();
|
||||
}
|
||||
int in_size = bin_input.size();
|
||||
int rup = ((in_size % 3) != 0) ? 1 : 0;
|
||||
int out_size = ((in_size * 4) / 3) + rup;
|
||||
std::string b64_output(out_size, '\0');
|
||||
int in_index = 0;
|
||||
int out_index = 0;
|
||||
unsigned long buffer;
|
||||
unsigned char out_cc;
|
||||
static const unsigned long kInMask = 0xff;
|
||||
static const unsigned long kOutMask = 0x3f;
|
||||
|
||||
while (in_index < in_size) {
|
||||
// up to 3 bytes (0..255) in
|
||||
buffer = (bin_input.at(in_index) & kInMask);
|
||||
buffer <<= 8;
|
||||
buffer |= (++in_index >= in_size) ? 0 : (bin_input.at(in_index) & kInMask);
|
||||
buffer <<= 8;
|
||||
buffer |= (++in_index >= in_size) ? 0 : (bin_input.at(in_index) & kInMask);
|
||||
++in_index;
|
||||
// up to 4 bytes (0..63) out
|
||||
out_cc = (buffer >> 18) & kOutMask;
|
||||
b64_output.at(out_index) = kBase64Chars[out_cc];
|
||||
if (++out_index >= out_size)
|
||||
break;
|
||||
out_cc = (buffer >> 12) & kOutMask;
|
||||
b64_output.at(out_index) = kBase64Chars[out_cc];
|
||||
if (++out_index >= out_size)
|
||||
break;
|
||||
out_cc = (buffer >> 6) & kOutMask;
|
||||
b64_output.at(out_index) = kBase64Chars[out_cc];
|
||||
if (++out_index >= out_size)
|
||||
break;
|
||||
out_cc = buffer & kOutMask;
|
||||
b64_output.at(out_index) = kBase64Chars[out_cc];
|
||||
++out_index;
|
||||
}
|
||||
return b64_output;
|
||||
}
|
||||
|
||||
// Decode for Filename-friendly base64 encoding (RFC4648).
|
||||
// This is the encoding required by GooglePlay for certain
|
||||
// license server transactions. It is also used for logging
|
||||
// certain strings.
|
||||
std::vector<uint8_t> Base64SafeDecode(const std::string& b64_input) {
|
||||
if (b64_input.empty()) {
|
||||
return std::vector<uint8_t>();
|
||||
}
|
||||
int in_size = b64_input.size();
|
||||
// out_size should be an integral number of bytes, assuming correct encode
|
||||
int out_size = ((in_size * 3) / 4);
|
||||
std::vector<uint8_t> bin_output(out_size, '\0');
|
||||
int in_index = 0;
|
||||
int out_index = 0;
|
||||
unsigned long buffer;
|
||||
unsigned char out_cc;
|
||||
static const unsigned long kOutMask = 0xff;
|
||||
|
||||
while (in_index < in_size) {
|
||||
// up to 4 bytes (0..63) in
|
||||
buffer = B64ToBin(b64_input.at(in_index));
|
||||
buffer <<= 6;
|
||||
buffer |= (++in_index >= in_size) ? 0 : B64ToBin(b64_input.at(in_index));
|
||||
buffer <<= 6;
|
||||
buffer |= (++in_index >= in_size) ? 0 : B64ToBin(b64_input.at(in_index));
|
||||
buffer <<= 6;
|
||||
buffer |= (++in_index >= in_size) ? 0 : B64ToBin(b64_input.at(in_index));
|
||||
++in_index;
|
||||
// up to 3 bytes (0..255) out
|
||||
out_cc = (buffer >> 16) & kOutMask;
|
||||
bin_output.at(out_index) = out_cc;
|
||||
if (++out_index >= out_size)
|
||||
break;
|
||||
out_cc = (buffer >> 8) & kOutMask;
|
||||
bin_output.at(out_index) = out_cc;
|
||||
if (++out_index >= out_size)
|
||||
break;
|
||||
out_cc = buffer & kOutMask;
|
||||
bin_output.at(out_index) = out_cc;
|
||||
++out_index;
|
||||
}
|
||||
return bin_output;
|
||||
}
|
||||
|
||||
std::string HexEncode(const uint8_t* in_buffer, unsigned int size) {
|
||||
static const char kHexChars[] = "0123456789ABCDEF";
|
||||
|
||||
// Each input byte creates two output hex characters.
|
||||
std::string out_buffer(size * 2, '\0');
|
||||
|
||||
for (unsigned int i = 0; i < size; ++i) {
|
||||
char byte = in_buffer[i];
|
||||
out_buffer[(i << 1)] = kHexChars[(byte >> 4) & 0xf];
|
||||
out_buffer[(i << 1) + 1] = kHexChars[byte & 0xf];
|
||||
}
|
||||
return out_buffer;
|
||||
}
|
||||
|
||||
std::string IntToString(int value) {
|
||||
// log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
|
||||
// So round up to allocate 3 output characters per byte, plus 1 for '-'.
|
||||
const int kOutputBufSize = 3 * sizeof(int) + 1;
|
||||
char buffer[kOutputBufSize];
|
||||
memset(buffer, 0, kOutputBufSize);
|
||||
snprintf(buffer, kOutputBufSize, "%d", value);
|
||||
|
||||
std::string out_string(buffer, sizeof(buffer));
|
||||
return out_string;
|
||||
}
|
||||
|
||||
std::string UintToString(unsigned int value) {
|
||||
// log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
|
||||
// So round up to allocate 3 output characters per byte.
|
||||
const int kOutputBufSize = 3 * sizeof(unsigned int);
|
||||
char buffer[kOutputBufSize];
|
||||
memset(buffer, 0, kOutputBufSize);
|
||||
snprintf(buffer, kOutputBufSize, "%u", value);
|
||||
|
||||
std::string out_string(buffer, sizeof(buffer));
|
||||
return out_string;
|
||||
}
|
||||
|
||||
}; // namespace wvcdm
|
||||
Reference in New Issue
Block a user