Line data Source code
1 : /*
2 : * If not stated otherwise in this file or this component's LICENSE file the
3 : * following copyright and licenses apply:
4 : *
5 : * Copyright 2022 Sky UK
6 : *
7 : * Licensed under the Apache License, Version 2.0 (the "License");
8 : * you may not use this file except in compliance with the License.
9 : * You may obtain a copy of the License at
10 : *
11 : * http://www.apache.org/licenses/LICENSE-2.0
12 : *
13 : * Unless required by applicable law or agreed to in writing, software
14 : * distributed under the License is distributed on an "AS IS" BASIS,
15 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 : * See the License for the specific language governing permissions and
17 : * limitations under the License.
18 : */
19 :
20 : #include <stdexcept>
21 : #include <utility>
22 :
23 : #include "MediaKeySession.h"
24 : #include "MediaKeysCommon.h"
25 : #include "RialtoServerLogging.h"
26 :
27 : namespace firebolt::rialto::server
28 : {
29 2 : std::shared_ptr<IMediaKeySessionFactory> IMediaKeySessionFactory::createFactory()
30 : {
31 2 : std::shared_ptr<IMediaKeySessionFactory> factory;
32 :
33 : try
34 : {
35 2 : factory = std::make_shared<MediaKeySessionFactory>();
36 : }
37 0 : catch (const std::exception &e)
38 : {
39 0 : RIALTO_SERVER_LOG_ERROR("Failed to create the media key session factory, reason: %s", e.what());
40 : }
41 :
42 2 : return factory;
43 : }
44 :
45 : std::unique_ptr<IMediaKeySession>
46 1 : MediaKeySessionFactory::createMediaKeySession(const std::string &keySystem, int32_t keySessionId,
47 : const firebolt::rialto::wrappers::IOcdmSystem &ocdmSystem,
48 : KeySessionType sessionType, std::weak_ptr<IMediaKeysClient> client) const
49 : {
50 1 : std::unique_ptr<IMediaKeySession> mediaKeys;
51 : try
52 : {
53 2 : mediaKeys = std::make_unique<server::MediaKeySession>(keySystem, keySessionId, ocdmSystem, sessionType, client,
54 3 : server::IMainThreadFactory::createFactory());
55 : }
56 0 : catch (const std::exception &e)
57 : {
58 0 : RIALTO_SERVER_LOG_ERROR("Failed to create the media key session, reason: %s", e.what());
59 : }
60 :
61 1 : return mediaKeys;
62 : }
63 :
64 56 : MediaKeySession::MediaKeySession(const std::string &keySystem, int32_t keySessionId,
65 : const firebolt::rialto::wrappers::IOcdmSystem &ocdmSystem, KeySessionType sessionType,
66 : std::weak_ptr<IMediaKeysClient> client,
67 56 : const std::shared_ptr<IMainThreadFactory> &mainThreadFactory)
68 56 : : m_kKeySystem(keySystem), m_kKeySessionId(keySessionId), m_kSessionType(sessionType), m_mediaKeysClient(client),
69 56 : m_isSessionConstructed(false), m_isSessionClosed(false), m_licenseRequested(false), m_ongoingOcdmOperation(false),
70 168 : m_ocdmError(false), m_decryptErrorLogged(false)
71 : {
72 56 : RIALTO_SERVER_LOG_DEBUG("entry:");
73 :
74 56 : m_mainThread = mainThreadFactory->getMainThread();
75 56 : if (!m_mainThread)
76 : {
77 1 : throw std::runtime_error("Failed to get the main thread");
78 : }
79 55 : m_mainThreadClientId = m_mainThread->registerClient();
80 :
81 55 : m_ocdmSession = ocdmSystem.createSession(this);
82 55 : if (!m_ocdmSession)
83 : {
84 1 : throw std::runtime_error("Ocdm session could not be created");
85 : }
86 54 : RIALTO_SERVER_LOG_MIL("New OCDM session created");
87 72 : }
88 :
89 162 : MediaKeySession::~MediaKeySession()
90 : {
91 54 : RIALTO_SERVER_LOG_DEBUG("entry:");
92 :
93 54 : if (m_isSessionConstructed)
94 : {
95 19 : if (!m_isSessionClosed)
96 : {
97 16 : if (MediaKeyErrorStatus::OK != closeKeySession())
98 : {
99 0 : RIALTO_SERVER_LOG_ERROR("Failed to close the key session");
100 : }
101 : }
102 19 : if (MediaKeyErrorStatus::OK != m_ocdmSession->destructSession())
103 : {
104 0 : RIALTO_SERVER_LOG_ERROR("Failed to destruct the key session");
105 : }
106 : }
107 :
108 54 : m_mainThread->unregisterClient(m_mainThreadClientId);
109 108 : }
110 :
111 19 : MediaKeyErrorStatus MediaKeySession::generateRequest(InitDataType initDataType, const std::vector<uint8_t> &initData,
112 : const LimitedDurationLicense &ldlState)
113 : {
114 19 : RIALTO_SERVER_LOG_DEBUG("entry:");
115 19 : if (LimitedDurationLicense::NOT_SPECIFIED != ldlState)
116 : {
117 12 : m_extendedInterfaceInUse = true;
118 : }
119 : else
120 : {
121 : // Set the request flag for the onLicenseRequest callback
122 7 : m_licenseRequested = true;
123 : }
124 :
125 19 : auto status = MediaKeyErrorStatus::OK;
126 :
127 : // Only construct session if it hasnt previously been constructed
128 19 : if (!m_isSessionConstructed)
129 : {
130 17 : initOcdmErrorChecking();
131 :
132 17 : status = m_ocdmSession->constructSession(m_kSessionType, initDataType, &initData[0], initData.size());
133 17 : if (MediaKeyErrorStatus::OK != status)
134 : {
135 1 : RIALTO_SERVER_LOG_ERROR("Failed to construct the key session");
136 1 : m_licenseRequested = false;
137 : }
138 : else
139 : {
140 16 : m_isSessionConstructed = true;
141 16 : if (!m_queuedDrmHeader.empty())
142 : {
143 0 : RIALTO_SERVER_LOG_DEBUG("Setting queued drm header after session construction");
144 0 : setDrmHeader(m_queuedDrmHeader);
145 0 : m_queuedDrmHeader.clear();
146 : }
147 : }
148 :
149 17 : if ((checkForOcdmErrors("generateRequest")) && (MediaKeyErrorStatus::OK == status))
150 : {
151 1 : status = MediaKeyErrorStatus::FAIL;
152 : }
153 : }
154 :
155 19 : if (m_isSessionConstructed && m_extendedInterfaceInUse)
156 : {
157 : // Ocdm-playready does not notify onProcessChallenge when complete.
158 : // Fetch the challenge manually.
159 12 : getChallenge(ldlState);
160 : }
161 :
162 19 : return status;
163 : }
164 :
165 12 : void MediaKeySession::getChallenge(const LimitedDurationLicense &ldlState)
166 : {
167 12 : RIALTO_SERVER_LOG_DEBUG("entry:");
168 12 : auto task = [&]()
169 : {
170 12 : const bool kIsLdl{LimitedDurationLicense::ENABLED == ldlState};
171 12 : uint32_t challengeSize = 0;
172 12 : MediaKeyErrorStatus status = m_ocdmSession->getChallengeData(kIsLdl, nullptr, &challengeSize);
173 12 : if (challengeSize == 0)
174 : {
175 1 : RIALTO_SERVER_LOG_ERROR("Failed to get the challenge data size, no onLicenseRequest will be generated");
176 2 : return;
177 : }
178 11 : std::vector<uint8_t> challenge(challengeSize, 0x00);
179 11 : status = m_ocdmSession->getChallengeData(kIsLdl, &challenge[0], &challengeSize);
180 11 : if (MediaKeyErrorStatus::OK != status)
181 : {
182 1 : RIALTO_SERVER_LOG_ERROR("Failed to get the challenge data, no onLicenseRequest will be generated");
183 1 : return;
184 : }
185 :
186 10 : std::string url;
187 10 : m_licenseRequested = true;
188 10 : onProcessChallenge(url.c_str(), &challenge[0], challengeSize);
189 11 : };
190 12 : m_mainThread->enqueueTask(m_mainThreadClientId, task);
191 : }
192 :
193 4 : MediaKeyErrorStatus MediaKeySession::loadSession(const std::string &cdmKeySessionId)
194 : {
195 4 : initOcdmErrorChecking();
196 :
197 4 : if (!m_isSessionConstructed && m_kSessionType == KeySessionType::PERSISTENT_LICENCE && !cdmKeySessionId.empty())
198 : {
199 4 : std::vector<uint8_t> cdmData(cdmKeySessionId.begin(), cdmKeySessionId.end());
200 8 : MediaKeyErrorStatus status = m_ocdmSession->constructSession(m_kSessionType, InitDataType::UNKNOWN, nullptr, 0,
201 4 : &cdmData[0], cdmData.size());
202 4 : if (MediaKeyErrorStatus::OK != status)
203 : {
204 1 : RIALTO_SERVER_LOG_ERROR("Failed to restore persistent license");
205 1 : return status;
206 : }
207 3 : m_isSessionConstructed = true;
208 4 : }
209 :
210 3 : MediaKeyErrorStatus status = m_ocdmSession->load();
211 3 : if (MediaKeyErrorStatus::OK != status)
212 : {
213 1 : RIALTO_SERVER_LOG_ERROR("Failed to load the key session");
214 : }
215 :
216 3 : if ((checkForOcdmErrors("loadSession")) && (MediaKeyErrorStatus::OK == status))
217 : {
218 1 : status = MediaKeyErrorStatus::FAIL;
219 : }
220 :
221 3 : return status;
222 : }
223 :
224 5 : MediaKeyErrorStatus MediaKeySession::updateSession(const std::vector<uint8_t> &responseData)
225 : {
226 5 : initOcdmErrorChecking();
227 :
228 : MediaKeyErrorStatus status;
229 5 : if (m_extendedInterfaceInUse)
230 : {
231 2 : status = m_ocdmSession->storeLicenseData(&responseData[0], responseData.size());
232 2 : if (MediaKeyErrorStatus::OK != status)
233 : {
234 1 : RIALTO_SERVER_LOG_ERROR("Failed to store the license data for the key session");
235 : }
236 : }
237 : else
238 : {
239 3 : status = m_ocdmSession->update(&responseData[0], responseData.size());
240 3 : if (MediaKeyErrorStatus::OK != status)
241 : {
242 1 : RIALTO_SERVER_LOG_ERROR("Failed to update the key session");
243 : }
244 : }
245 :
246 5 : if ((checkForOcdmErrors("updateSession")) && (MediaKeyErrorStatus::OK == status))
247 : {
248 1 : status = MediaKeyErrorStatus::FAIL;
249 : }
250 :
251 5 : return status;
252 : }
253 :
254 10 : MediaKeyErrorStatus MediaKeySession::decrypt(GstBuffer *encrypted, GstCaps *caps)
255 : {
256 10 : constexpr uint32_t kHdcpOutputProtectionFailure{4427};
257 :
258 10 : initOcdmErrorChecking();
259 :
260 10 : MediaKeyErrorStatus status = m_ocdmSession->decryptBuffer(encrypted, caps);
261 10 : if (MediaKeyErrorStatus::OUTPUT_RESTRICTED == status)
262 : {
263 1 : RIALTO_SERVER_LOG_WARN("Decrypt failed due to HDCP output protection");
264 : }
265 9 : else if (MediaKeyErrorStatus::OK != status)
266 : {
267 6 : uint32_t lastDrmError{0};
268 6 : m_ocdmSession->getLastDrmError(lastDrmError);
269 6 : if (lastDrmError == kHdcpOutputProtectionFailure)
270 : {
271 1 : RIALTO_SERVER_LOG_WARN("Decrypt failed due to HDCP output protection (DRM error %u)", lastDrmError);
272 1 : status = MediaKeyErrorStatus::OUTPUT_RESTRICTED;
273 : }
274 :
275 : // Log decrypt failures once and re-enable logging only after a successful decrypt.
276 6 : if ((MediaKeyErrorStatus::OUTPUT_RESTRICTED != status) && !m_decryptErrorLogged)
277 : {
278 4 : RIALTO_SERVER_LOG_ERROR("Failed to decrypt buffer");
279 4 : m_decryptErrorLogged = true;
280 : }
281 : }
282 : else
283 : {
284 3 : m_decryptErrorLogged = false;
285 : }
286 :
287 10 : if ((checkForOcdmErrors("decrypt")) && (MediaKeyErrorStatus::OK == status))
288 : {
289 1 : status = MediaKeyErrorStatus::FAIL;
290 : }
291 :
292 10 : return status;
293 : }
294 :
295 22 : MediaKeyErrorStatus MediaKeySession::closeKeySession()
296 : {
297 22 : initOcdmErrorChecking();
298 :
299 : MediaKeyErrorStatus status;
300 22 : if (m_extendedInterfaceInUse)
301 : {
302 12 : if (MediaKeyErrorStatus::OK != m_ocdmSession->cancelChallengeData())
303 : {
304 1 : RIALTO_SERVER_LOG_WARN("Failed to cancel the challenge data for the key session");
305 : }
306 :
307 12 : if (MediaKeyErrorStatus::OK != m_ocdmSession->cleanDecryptContext())
308 : {
309 1 : RIALTO_SERVER_LOG_WARN("Failed to clean the decrypt context for the key session");
310 : }
311 12 : status = MediaKeyErrorStatus::OK;
312 12 : RIALTO_SERVER_LOG_MIL("OCDM session closed");
313 : }
314 : else
315 : {
316 10 : status = m_ocdmSession->close();
317 10 : if (MediaKeyErrorStatus::OK != status)
318 : {
319 1 : RIALTO_SERVER_LOG_ERROR("Failed to Close the key session");
320 : }
321 : }
322 22 : m_isSessionClosed = (MediaKeyErrorStatus::OK == status);
323 :
324 22 : if ((checkForOcdmErrors("closeKeySession")) && (MediaKeyErrorStatus::OK == status))
325 : {
326 1 : status = MediaKeyErrorStatus::FAIL;
327 : }
328 :
329 22 : return status;
330 : }
331 :
332 3 : MediaKeyErrorStatus MediaKeySession::removeKeySession()
333 : {
334 3 : initOcdmErrorChecking();
335 :
336 3 : MediaKeyErrorStatus status = m_ocdmSession->remove();
337 3 : if (MediaKeyErrorStatus::OK != status)
338 : {
339 1 : RIALTO_SERVER_LOG_ERROR("Failed to remove the key session");
340 : }
341 :
342 3 : if ((checkForOcdmErrors("removeKeySession")) && (MediaKeyErrorStatus::OK == status))
343 : {
344 1 : status = MediaKeyErrorStatus::FAIL;
345 : }
346 :
347 3 : return status;
348 : }
349 :
350 3 : MediaKeyErrorStatus MediaKeySession::getCdmKeySessionId(std::string &cdmKeySessionId)
351 : {
352 3 : initOcdmErrorChecking();
353 :
354 3 : MediaKeyErrorStatus status = m_ocdmSession->getCdmKeySessionId(cdmKeySessionId);
355 3 : if (MediaKeyErrorStatus::OK != status)
356 : {
357 1 : RIALTO_SERVER_LOG_ERROR("Failed to get cdm key session id");
358 : }
359 :
360 3 : if ((checkForOcdmErrors("getCdmKeySessionId")) && (MediaKeyErrorStatus::OK == status))
361 : {
362 1 : status = MediaKeyErrorStatus::FAIL;
363 : }
364 :
365 3 : return status;
366 : }
367 :
368 2 : bool MediaKeySession::containsKey(const std::vector<uint8_t> &keyId)
369 : {
370 2 : uint32_t result = m_ocdmSession->hasKeyId(keyId.data(), keyId.size());
371 :
372 2 : return static_cast<bool>(result);
373 : }
374 :
375 3 : MediaKeyErrorStatus MediaKeySession::setDrmHeader(const std::vector<uint8_t> &requestData)
376 : {
377 3 : initOcdmErrorChecking();
378 :
379 3 : if (!m_isSessionConstructed)
380 : {
381 0 : RIALTO_SERVER_LOG_INFO("Session not yet constructed, queueing drm header to be set after construction");
382 0 : m_extendedInterfaceInUse = true;
383 0 : m_queuedDrmHeader = requestData;
384 0 : return MediaKeyErrorStatus::OK;
385 : }
386 :
387 3 : MediaKeyErrorStatus status = m_ocdmSession->setDrmHeader(requestData.data(), requestData.size());
388 3 : if (MediaKeyErrorStatus::OK != status)
389 : {
390 1 : RIALTO_SERVER_LOG_ERROR("Failed to set drm header");
391 : }
392 :
393 3 : if ((checkForOcdmErrors("setDrmHeader")) && (MediaKeyErrorStatus::OK == status))
394 : {
395 1 : status = MediaKeyErrorStatus::FAIL;
396 : }
397 :
398 3 : return status;
399 : }
400 :
401 3 : MediaKeyErrorStatus MediaKeySession::getLastDrmError(uint32_t &errorCode)
402 : {
403 3 : initOcdmErrorChecking();
404 :
405 3 : MediaKeyErrorStatus status = m_ocdmSession->getLastDrmError(errorCode);
406 3 : if (MediaKeyErrorStatus::OK != status)
407 : {
408 1 : RIALTO_SERVER_LOG_ERROR("Failed to get last drm error");
409 : }
410 :
411 3 : if ((checkForOcdmErrors("getLastDrmError")) && (MediaKeyErrorStatus::OK == status))
412 : {
413 1 : status = MediaKeyErrorStatus::FAIL;
414 : }
415 :
416 3 : return status;
417 : }
418 :
419 7 : MediaKeyErrorStatus MediaKeySession::selectKeyId(const std::vector<uint8_t> &keyId)
420 : {
421 7 : if (m_selectedKeyId == keyId)
422 : {
423 1 : return MediaKeyErrorStatus::OK;
424 : }
425 :
426 6 : initOcdmErrorChecking();
427 :
428 6 : m_extendedInterfaceInUse = true;
429 6 : MediaKeyErrorStatus status = m_ocdmSession->selectKeyId(keyId.size(), keyId.data());
430 6 : if (MediaKeyErrorStatus::OK == status)
431 : {
432 4 : RIALTO_SERVER_LOG_INFO("New keyId selected successfully");
433 4 : m_selectedKeyId = keyId;
434 : }
435 :
436 6 : if ((checkForOcdmErrors("selectKeyId")) && (MediaKeyErrorStatus::OK == status))
437 : {
438 1 : status = MediaKeyErrorStatus::FAIL;
439 : }
440 :
441 6 : return status;
442 : }
443 :
444 12 : void MediaKeySession::onProcessChallenge(const char url[], const uint8_t challenge[], const uint16_t challengeLength)
445 : {
446 12 : std::string urlStr = url;
447 24 : std::vector<unsigned char> challengeVec = std::vector<unsigned char>{challenge, challenge + challengeLength};
448 12 : auto task = [&, urlStr = std::move(urlStr), challengeVec = std::move(challengeVec)]()
449 : {
450 12 : std::shared_ptr<IMediaKeysClient> client = m_mediaKeysClient.lock();
451 12 : if (client)
452 : {
453 12 : if (m_licenseRequested)
454 : {
455 11 : client->onLicenseRequest(m_kKeySessionId, challengeVec, urlStr);
456 11 : m_licenseRequested = false;
457 : }
458 : else
459 : {
460 1 : client->onLicenseRenewal(m_kKeySessionId, challengeVec);
461 : }
462 : }
463 24 : };
464 12 : m_mainThread->enqueueTask(m_mainThreadClientId, task);
465 : }
466 :
467 3 : void MediaKeySession::onKeyUpdated(const uint8_t keyId[], const uint8_t keyIdLength)
468 : {
469 6 : std::vector<unsigned char> keyIdVec = std::vector<unsigned char>{keyId, keyId + keyIdLength};
470 3 : auto task = [&, keyIdVec = std::move(keyIdVec)]()
471 : {
472 3 : std::shared_ptr<IMediaKeysClient> client = m_mediaKeysClient.lock();
473 3 : if (client)
474 : {
475 3 : KeyStatus status = m_ocdmSession->getStatus(&keyIdVec[0], keyIdVec.size());
476 3 : m_updatedKeyStatuses.push_back(std::make_pair(keyIdVec, status));
477 : }
478 6 : };
479 3 : m_mainThread->enqueueTask(m_mainThreadClientId, task);
480 : }
481 :
482 1 : void MediaKeySession::onAllKeysUpdated()
483 : {
484 1 : auto task = [&]()
485 : {
486 1 : std::shared_ptr<IMediaKeysClient> client = m_mediaKeysClient.lock();
487 1 : if (client)
488 : {
489 1 : client->onKeyStatusesChanged(m_kKeySessionId, m_updatedKeyStatuses);
490 1 : m_updatedKeyStatuses.clear();
491 : }
492 1 : };
493 1 : m_mainThread->enqueueTask(m_mainThreadClientId, task);
494 : }
495 :
496 10 : void MediaKeySession::onError(const char message[])
497 : {
498 10 : RIALTO_SERVER_LOG_ERROR("Ocdm returned error: %s", message);
499 :
500 10 : std::lock_guard<std::mutex> lock(m_ocdmErrorMutex);
501 10 : if (!m_ongoingOcdmOperation)
502 : {
503 0 : RIALTO_SERVER_LOG_WARN("Received an asycronous OCDM error, ignoring");
504 : }
505 : else
506 : {
507 10 : m_ocdmError = true;
508 : }
509 : }
510 :
511 76 : void MediaKeySession::initOcdmErrorChecking()
512 : {
513 76 : std::lock_guard<std::mutex> lock(m_ocdmErrorMutex);
514 76 : m_ongoingOcdmOperation = true;
515 76 : m_ocdmError = false;
516 : }
517 :
518 75 : bool MediaKeySession::checkForOcdmErrors(const char *operationStr)
519 : {
520 75 : bool error = false;
521 :
522 75 : std::lock_guard<std::mutex> lock(m_ocdmErrorMutex);
523 75 : if (m_ocdmError)
524 : {
525 10 : RIALTO_SERVER_LOG_ERROR("MediaKeySession received an onError callback, operation '%s' failed", operationStr);
526 10 : error = true;
527 : }
528 75 : m_ongoingOcdmOperation = false;
529 :
530 75 : return error;
531 : }
532 :
533 : }; // namespace firebolt::rialto::server
|