-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathopencdmsessionadapter.cpp
More file actions
515 lines (456 loc) · 15.7 KB
/
Copy pathopencdmsessionadapter.cpp
File metadata and controls
515 lines (456 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2020 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file opencdmsessionadapter.cpp
* @brief Handles operation with OCDM session to handle DRM License data
*/
#include "opencdmsessionadapter.h"
#include "DrmHelper.h"
#include "PlayerUtils.h"
#include "ProcessHandler.h"
#include "PlayerExternalsInterface.h"
#include <assert.h>
#include <iostream>
#include <sstream>
#include <string>
#include <errno.h>
#include <string.h>
#include <vector>
#include <sys/utsname.h>
#include <unistd.h>
#include <sys/syscall.h>
#include "PlayerLogManager.h"
#include <sys/time.h>
#include <set>
#define LICENSE_RENEWAL_MESSAGE_TYPE "1"
/**
* @fn toPlayerKeyStatus
* @brief Convert OCDM KeyStatus to PlayerKeyStatus.
* @param ocdmStatus The KeyStatus from OCDM.
* @return The corresponding PlayerKeyStatus.
*/
static PlayerKeyStatus toPlayerKeyStatus(KeyStatus ocdmStatus) {
switch (ocdmStatus) {
case Usable: return PLAYER_KEY_USABLE;
case Expired: return PLAYER_KEY_EXPIRED;
case Released: return PLAYER_KEY_RELEASED;
case OutputRestricted: return PLAYER_KEY_OUTPUT_RESTRICTED;
case OutputRestrictedHDCP22: return PLAYER_KEY_OUTPUT_RESTRICTED_HDCP22;
case OutputDownscaled: return PLAYER_KEY_OUTPUT_DOWNSCALED;
case StatusPending: return PLAYER_KEY_STATUS_PENDING;
case HWError: return PLAYER_KEY_HW_ERROR;
case InternalError: default: return PLAYER_KEY_INTERNAL_ERROR;
}
}
/**
* @fn ShouldNotifyKeyStatus
* @brief Determine if a given KeyStatus should trigger a key status notification to the player.
* @param status The KeyStatus to evaluate.
* @return true if the status should trigger a notification, false otherwise.
*/
bool ShouldNotifyKeyStatus(KeyStatus status)
{
switch (status)
{
case OutputRestricted:
case Usable:
return true;
default:
return false;
}
}
/**
* @fn OCDMSessionAdapter
* @brief OCDMSessionAdapter constructor
*/
OCDMSessionAdapter::OCDMSessionAdapter(DrmHelperPtr drmHelper, DrmCallbacks *callbacks) :
DrmSession(drmHelper->ocdmSystemId()),
m_eKeyState(KEY_INIT),
m_pOpenCDMSystem(NULL),
m_pOpenCDMSession(NULL),
m_pOutputProtection(NULL),
decryptMutex(),
m_sessionID(),
m_challenge(),
timeBeforeCallback(0),
m_challengeReady(),
m_challengeSize(0),
m_keyStatus(InternalError),
m_sessionKeyStatus(Usable),
m_keyStateIndeterminate(false),
m_keyStatusReady(),
m_OCDMSessionCallbacks(),
m_destUrl(),
m_drmHelper(drmHelper),
m_drmCallbacks(callbacks),
m_keyStatusWait(),
m_keyId(),
m_keyStored(),
m_usableKeys(),
m_usableKeysMutex()
{
MW_LOG_WARN("OCDMSessionAdapter :: enter ");
MW_LOG_WARN("OCDMSessionAdapter :: key process timeout is %d", drmHelper->keyProcessTimeout());
initDRMSystem();
// Get output protection pointer
m_pOutputProtection = PlayerExternalsInterface::GetPlayerExternalsInterfaceInstance();
MW_LOG_WARN("OCDMSessionAdapter :: exit ");
}
void OCDMSessionAdapter::initDRMSystem()
{
std::lock_guard<std::mutex> guard(decryptMutex);
MW_LOG_WARN("initDRMSystem :: enter ");
if (m_pOpenCDMSystem == nullptr) {
#ifdef USE_THUNDER_OCDM_API_0_2
m_pOpenCDMSystem = opencdm_create_system(m_keySystem.c_str());
#else
m_pOpenCDMSystem = opencdm_create_system();
#endif
if (m_pOpenCDMSystem == nullptr) {
MW_LOG_ERR("opencdm_create_system() FAILED");
}
}
MW_LOG_WARN("initDRMSystem :: exit ");
}
OCDMSessionAdapter::~OCDMSessionAdapter()
{
MW_LOG_WARN("[HHH]OCDMSessionAdapter destructor called! keySystem %s", m_keySystem.c_str());
clearDecryptContext();
if (m_pOpenCDMSystem) {
#ifdef USE_THUNDER_OCDM_API_0_2
opencdm_destruct_system(m_pOpenCDMSystem);
#endif
m_pOpenCDMSystem = NULL;
}
}
void OCDMSessionAdapter::generateDRMSession(const uint8_t *f_pbInitData,
uint32_t f_cbInitData, std::string &customData)
{
MW_LOG_INFO("at %p, with %p, %p", this , m_pOpenCDMSystem, m_pOpenCDMSession);
std::lock_guard<std::mutex> guard(decryptMutex);
if (m_pOpenCDMSystem == nullptr)
{
MW_LOG_WARN("OpenCDM system not present, unable to generate DRM session");
m_eKeyState = KEY_ERROR;
}
else
{
memset(&m_OCDMSessionCallbacks, 0, sizeof(m_OCDMSessionCallbacks));
timeBeforeCallback = GetCurrentTimeMS();
m_OCDMSessionCallbacks.process_challenge_callback = [](OpenCDMSession* session, void* userData, const char destUrl[], const uint8_t challenge[], const uint16_t challengeSize) {
OCDMSessionAdapter* userSession = reinterpret_cast<OCDMSessionAdapter*>(userData);
userSession->timeBeforeCallback = ((GetCurrentTimeMS())-(userSession->timeBeforeCallback));
MW_LOG_WARN( "Duration for process_challenge_callback %lld",(userSession->timeBeforeCallback));
userSession->processOCDMChallenge(destUrl, challenge, challengeSize);
};
m_OCDMSessionCallbacks.key_update_callback = [](OpenCDMSession* session, void* userData, const uint8_t key[], const uint8_t keySize) {
OCDMSessionAdapter* userSession = reinterpret_cast<OCDMSessionAdapter*>(userData);
userSession->keyUpdateOCDM(key, keySize);
};
m_OCDMSessionCallbacks.error_message_callback = [](OpenCDMSession* session, void* userData, const char message[]) {
};
m_OCDMSessionCallbacks.keys_updated_callback = [](const OpenCDMSession* session, void* userData) {
OCDMSessionAdapter* userSession = reinterpret_cast<OCDMSessionAdapter*>(userData);
userSession->keysUpdatedOCDM();
};
const unsigned char *customDataMessage = customData.empty() ? nullptr:reinterpret_cast<const unsigned char *>(customData.c_str()) ;
const uint16_t customDataMessageLength = customData.length();
MW_LOG_INFO("data length : %d: ", customDataMessageLength);
#ifdef USE_THUNDER_OCDM_API_0_2
OpenCDMError ocdmRet = opencdm_construct_session(m_pOpenCDMSystem, LicenseType::Temporary, "cenc",
#else
OpenCDMError ocdmRet = opencdm_construct_session(m_pOpenCDMSystem, m_keySystem.c_str(), LicenseType::Temporary, "cenc",
#endif
const_cast<unsigned char*>(f_pbInitData), f_cbInitData,
customDataMessage, customDataMessageLength,
&m_OCDMSessionCallbacks,
static_cast<void*>(this),
&m_pOpenCDMSession);
if (ocdmRet != ERROR_NONE)
{
MW_LOG_ERR("Error constructing OCDM session. OCDM err=0x%x", ocdmRet);
m_eKeyState = KEY_ERROR_SESSION_CREATE_FAILED;
}
}
}
void OCDMSessionAdapter::processOCDMChallenge(const char destUrl[], const uint8_t challenge[], const uint16_t challengeSize) {
MW_LOG_INFO("at %p, with %p, %p", this , m_pOpenCDMSystem, m_pOpenCDMSession);
const std::string challengeData(reinterpret_cast<const char *>(challenge), challengeSize);
const std::set<std::string> individualisationTypes = {"individualization-request", "3"};
const std::string delimiter(":Type:");
const size_t delimiterPos = challengeData.find(delimiter);
const std::string messageType = challengeData.substr(0, delimiterPos);
// Check if this message should be forwarded using a DRM callback.
// Example message: individualization-request:Type:(payload)
if ((delimiterPos != std::string::npos) && (individualisationTypes.count(messageType) > 0))
{
MW_LOG_WARN("processOCDMChallenge received message with type=%s", messageType.c_str());
if (m_drmCallbacks)
{
m_drmCallbacks->Individualization(challengeData.substr(delimiterPos + delimiter.length()));
}
}
else
{
// Assuming this is a standard challenge callback
m_challenge = challengeData;
MW_LOG_WARN("processOCDMChallenge challenge = %s", m_challenge.c_str());
m_destUrl.assign(destUrl);
MW_LOG_WARN("processOCDMChallenge destUrl = %s (default value used as drm server)", m_destUrl.c_str());
m_challengeReady.signal();
}
if(messageType == LICENSE_RENEWAL_MESSAGE_TYPE)
{
if (m_drmCallbacks)
m_drmCallbacks->LicenseRenewal(m_drmHelper,static_cast<DrmSession*> (this));
}
}
void OCDMSessionAdapter::keyUpdateOCDM(const uint8_t key[], const uint8_t keySize) {
MW_LOG_INFO("at %p, with %p, %p", this , m_pOpenCDMSystem, m_pOpenCDMSession);
// Validate input parameters
if (key != nullptr && keySize > 0)
{
// Convert key to keyId - common for both branches
std::vector<uint8_t> keyData = RawKeyToKeyId(key, keySize);
if (m_pOpenCDMSession)
{
m_keyStatus = opencdm_session_status(m_pOpenCDMSession, key, keySize);
MW_LOG_INFO("Key status from OCDM: %d", m_keyStatus);
m_keyStateIndeterminate = false;
if (m_keyStatus != Usable)
{
m_sessionKeyStatus = m_keyStatus;
}
}
else
{
m_keyStored.clear();
m_keyStored.assign(key, key + keySize);
m_keyStateIndeterminate = true;
}
// Update usable keys list (common for both branches)
{
std::lock_guard<std::mutex> lock(m_usableKeysMutex);
// Check if this key already exists to avoid duplicates
if (std::find(m_usableKeys.begin(), m_usableKeys.end(), keyData) == m_usableKeys.end())
{
m_usableKeys.push_back(keyData);
}
}
}
}
void OCDMSessionAdapter::keysUpdatedOCDM() {
MW_LOG_INFO("at %p, with %p, %p", this , m_pOpenCDMSystem, m_pOpenCDMSession);
m_keyStatusReady.signal();
const KeyStatus notifyStatus = m_sessionKeyStatus;
m_sessionKeyStatus = Usable; // reset for next burst
if (m_drmCallbacks && (ShouldNotifyKeyStatus(notifyStatus) == true))
{
MW_LOG_INFO("keysUpdatedOCDM notifying key status %d", notifyStatus);
m_drmCallbacks->NotifyKeyStatus(toPlayerKeyStatus(notifyStatus));
}
else
{
MW_LOG_INFO("Key status %d does not trigger a notification to the player", notifyStatus);
}
}
DrmData * OCDMSessionAdapter::generateKeyRequest(string& destinationURL, uint32_t timeout)
{
MW_LOG_INFO("at %p, with %p, %p", this , m_pOpenCDMSystem, m_pOpenCDMSession);
DrmData * result = NULL;
m_eKeyState = KEY_ERROR;
if (m_challengeReady.wait(timeout) == true) {
if (m_challenge.empty() != true) {
std::string delimiter (":Type:");
std::string requestType (m_challenge.substr(0, m_challenge.find(delimiter)));
if ( (requestType.size() != 0) && (requestType.size() != m_challenge.size()) ) {
(void) m_challenge.erase(0, m_challenge.find(delimiter) + delimiter.length());
}
result = new DrmData(m_challenge.c_str(), m_challenge.length());
destinationURL.assign((m_destUrl.c_str()));
MW_LOG_WARN("destinationURL is %s (default value used as drm server)", destinationURL.c_str());
m_eKeyState = KEY_PENDING;
}
else {
MW_LOG_WARN("Empty keyRequest");
}
} else {
MW_LOG_WARN("Timed out waiting for keyRequest");
}
return result;
}
int OCDMSessionAdapter::processDRMKey(DrmData* key, uint32_t timeout)
{
MW_LOG_INFO("at %p, with %p, %p", this , m_pOpenCDMSystem, m_pOpenCDMSession);
int retValue = -1;
const uint8_t* keyMessage = NULL;
uint16_t keyMessageLength = 0;
OpenCDMError status = OpenCDMError::ERROR_NONE;
if (key)
{
keyMessage = (const uint8_t *)key->getData().c_str();
keyMessageLength = key->getDataLength();
}
if (keyMessage)
{
MW_LOG_INFO("Calling opencdm_session_update, key length=%u", keyMessageLength);
status = opencdm_session_update(m_pOpenCDMSession, keyMessage, keyMessageLength);
}
else
{
// If no key data has been provided then this suggests the key acquisition
// will be performed by the DRM implementation itself. Hence there is no
// need to call opencdm_session_update
MW_LOG_INFO("NULL key data provided, assuming external key acquisition");
}
if (status == OpenCDMError::ERROR_NONE) {
if (m_keyStatusReady.wait(timeout) == true) {
MW_LOG_WARN("Key Status updated");
}
// The key could be signalled ready before the session is even created, so we need to check we didn't miss it
if (m_keyStateIndeterminate) {
m_keyStatus = opencdm_session_status(m_pOpenCDMSession, m_keyStored.data(), m_keyStored.size());
m_keyStateIndeterminate = false;
MW_LOG_WARN("Key arrived early, new state is %d", m_keyStatus);
}
#ifdef USE_THUNDER_OCDM_API_0_2
if (m_keyStatus == Usable) {
#else
if (m_keyStatus == KeyStatus::Usable) {
#endif
MW_LOG_WARN("processKey: Key Usable!");
m_eKeyState = KEY_READY;
retValue = 0;
}
#ifdef USE_THUNDER_OCDM_API_0_2
else if(m_keyStatus == HWError)
#else
else if(m_keyStatus == KeyStatus::HWError)
#endif
{
// SAGE Hang .. Need to restart the wpecdmi process and then self kill player to recover
MW_LOG_WARN("processKey: Update() returned HWError.Restarting process...");
ProcessHandler processHandler;
// In Release another process handles opencdm which needs to be restarts .In Sprint this process is not available.
// So check if process exists before killing it .
if (processHandler.KillProcess("WPEFramework")) /** Current OCDM process **/
{
MW_LOG_WARN("OCDM HWError reported.. Killed the process WPEFramework for recovery..");
}
else
{
if(processHandler.KillProcess("WPEcdmi")) /** Backword compatibility **/
{
MW_LOG_WARN("OCDM HWError reported.. Killed the process WPEcdmi for recovery..");
}
}
// wait for 5sec for all the logs to be flushed
sleep(5);
// Now kill self
processHandler.SelfKill();
}
else {
#ifdef USE_THUNDER_OCDM_API_0_2
if(m_keyStatus == OutputRestricted)
#else
if(m_keyStatus == KeyStatus::OutputRestricted)
#endif
{
MW_LOG_WARN("processKey: Update() Output restricted keystatus: %d", (int) m_keyStatus);
retValue = HDCP_OUTPUT_PROTECTION_FAILURE;
}
#ifdef USE_THUNDER_OCDM_API_0_2
else if(m_keyStatus == OutputRestrictedHDCP22)
#else
else if(m_keyStatus == KeyStatus::OutputRestrictedHDCP22)
#endif
{
MW_LOG_WARN("processKey: Update() Output Compliance error keystatus: %d\n", (int) m_keyStatus);
retValue = HDCP_COMPLIANCE_CHECK_FAILURE;
}
else
{
MW_LOG_WARN("processKey: Update() returned keystatus: %d\n", (int) m_keyStatus);
retValue = (int) m_keyStatus;
}
m_eKeyState = KEY_ERROR;
}
}
m_keyStatusWait.signal();
return retValue;
}
bool OCDMSessionAdapter::waitForState(KeyState state, const uint32_t timeout)
{
if (m_eKeyState == state) {
return true;
}
if (!m_keyStatusWait.wait(timeout)) {
return false;
}
return m_eKeyState == state;
}
KeyState OCDMSessionAdapter::getState()
{
return m_eKeyState;
}
void OCDMSessionAdapter:: clearDecryptContext()
{
MW_LOG_WARN("[HHH] clearDecryptContext.");
std::lock_guard<std::mutex> guard(decryptMutex);
if (m_pOpenCDMSession) {
opencdm_session_close(m_pOpenCDMSession);
opencdm_destruct_session(m_pOpenCDMSession);
m_pOpenCDMSession = NULL;
}
// Clear usable keys when clearing the session
{
std::lock_guard<std::mutex> keyLock(m_usableKeysMutex);
m_usableKeys.clear();
}
m_sessionKeyStatus = Usable;
m_eKeyState = KEY_INIT;
}
void OCDMSessionAdapter::setKeyId(const std::vector<uint8_t>& keyId)
{
m_keyId = keyId;
}
bool OCDMSessionAdapter::verifyOutputProtection()
{
if (m_drmHelper->isHdcp22Required() && m_pOutputProtection->IsSourceUHD())
{
// Source material is UHD
if (!m_pOutputProtection->isHDCPConnection2_2())
{
// UHD and not HDCP 2.2
MW_LOG_WARN("UHD source but not HDCP 2.2. FAILING decrypt");
return false;
}
}
return true;
}
/**
* @fn getUsableKeys
* @brief Get the list of usable key IDs from the DRM session
* @retval Reference to vector of usable key IDs
*/
const std::vector<std::vector<uint8_t>>& OCDMSessionAdapter::getUsableKeys() const
{
std::lock_guard<std::mutex> lock(m_usableKeysMutex);
return m_usableKeys;
}