1/*
2 * Copyright (C) 2016 Metrological Group B.V.
3 * Copyright (C) 2016 Igalia S.L.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include "config.h"
30#include "MediaKeySession.h"
31
32#if ENABLE(ENCRYPTED_MEDIA)
33
34#include "CDM.h"
35#include "CDMInstance.h"
36#include "Document.h"
37#include "EventNames.h"
38#include "Logging.h"
39#include "MediaKeyMessageEvent.h"
40#include "MediaKeyMessageType.h"
41#include "MediaKeyStatusMap.h"
42#include "MediaKeys.h"
43#include "NotImplemented.h"
44#include "Page.h"
45#include "SecurityOrigin.h"
46#include "SecurityOriginData.h"
47#include "Settings.h"
48#include "SharedBuffer.h"
49#include <wtf/IsoMallocInlines.h>
50
51namespace WebCore {
52
53WTF_MAKE_ISO_ALLOCATED_IMPL(MediaKeySession);
54
55Ref<MediaKeySession> MediaKeySession::create(ScriptExecutionContext& context, WeakPtr<MediaKeys>&& keys, MediaKeySessionType sessionType, bool useDistinctiveIdentifier, Ref<CDM>&& implementation, Ref<CDMInstanceSession>&& instanceSession)
56{
57 auto session = adoptRef(*new MediaKeySession(context, WTFMove(keys), sessionType, useDistinctiveIdentifier, WTFMove(implementation), WTFMove(instanceSession)));
58 session->suspendIfNeeded();
59 return session;
60}
61
62MediaKeySession::MediaKeySession(ScriptExecutionContext& context, WeakPtr<MediaKeys>&& keys, MediaKeySessionType sessionType, bool useDistinctiveIdentifier, Ref<CDM>&& implementation, Ref<CDMInstanceSession>&& instanceSession)
63 : ActiveDOMObject(&context)
64 , m_keys(WTFMove(keys))
65 , m_expiration(std::numeric_limits<double>::quiet_NaN())
66 , m_keyStatuses(MediaKeyStatusMap::create(*this))
67 , m_useDistinctiveIdentifier(useDistinctiveIdentifier)
68 , m_sessionType(sessionType)
69 , m_implementation(WTFMove(implementation))
70 , m_instanceSession(WTFMove(instanceSession))
71 , m_eventQueue(*this)
72{
73 // https://w3c.github.io/encrypted-media/#dom-mediakeys-createsession
74 // W3C Editor's Draft 09 November 2016
75 // createSession(), ctd.
76
77 LOG(EME, "EME - new session created");
78
79 // 3.1. Let the sessionId attribute be the empty string.
80 // 3.2. Let the expiration attribute be NaN.
81 // 3.3. Let the closed attribute be a new promise.
82 // 3.4. Let key status be a new empty MediaKeyStatusMap object, and initialize it as follows:
83 // 3.4.1. Let the size attribute be 0.
84 // 3.5. Let the session type value be sessionType.
85 // 3.6. Let the uninitialized value be true.
86 // 3.7. Let the callable value be false.
87 // 3.8. Let the use distinctive identifier value be this object's use distinctive identifier value.
88 // 3.9. Let the cdm implementation value be this object's cdm implementation.
89 // 3.10. Let the cdm instance value be this object's cdm instance.
90
91 UNUSED_PARAM(m_callable);
92 UNUSED_PARAM(m_sessionType);
93 UNUSED_PARAM(m_useDistinctiveIdentifier);
94 UNUSED_PARAM(m_closed);
95 UNUSED_PARAM(m_uninitialized);
96
97 m_instanceSession->setClient(m_cdmInstanceSessionClientWeakPtrFactory.createWeakPtr(*this));
98}
99
100MediaKeySession::~MediaKeySession()
101{
102 m_keyStatuses->detachSession();
103 m_instanceSession->clearClient();
104}
105
106const String& MediaKeySession::sessionId() const
107{
108 return m_sessionId;
109}
110
111double MediaKeySession::expiration() const
112{
113 return m_expiration;
114}
115
116Ref<MediaKeyStatusMap> MediaKeySession::keyStatuses() const
117{
118 return m_keyStatuses.copyRef();
119}
120
121void MediaKeySession::generateRequest(const AtomicString& initDataType, const BufferSource& initData, Ref<DeferredPromise>&& promise)
122{
123 // https://w3c.github.io/encrypted-media/#dom-mediakeysession-generaterequest
124 // W3C Editor's Draft 09 November 2016
125
126 // When this method is invoked, the user agent must run the following steps:
127 // 1. If this object is closed, return a promise rejected with an InvalidStateError.
128 // 2. If this object's uninitialized value is false, return a promise rejected with an InvalidStateError.
129 LOG(EME, "EME - generate request");
130
131 if (m_closed || !m_uninitialized) {
132 promise->reject(InvalidStateError);
133 return;
134 }
135
136 // 3. Let this object's uninitialized value be false.
137 m_uninitialized = false;
138
139 // 4. If initDataType is the empty string, return a promise rejected with a newly created TypeError.
140 // 5. If initData is an empty array, return a promise rejected with a newly created TypeError.
141 if (initDataType.isEmpty() || !initData.length()) {
142 promise->reject(TypeError);
143 return;
144 }
145
146 // 6. If the Key System implementation represented by this object's cdm implementation value does not support
147 // initDataType as an Initialization Data Type, return a promise rejected with a NotSupportedError. String
148 // comparison is case-sensitive.
149 if (!m_implementation->supportsInitDataType(initDataType)) {
150 promise->reject(NotSupportedError);
151 return;
152 }
153
154 // 7. Let init data be a copy of the contents of the initData parameter.
155 // 8. Let session type be this object's session type.
156 // 9. Let promise be a new promise.
157 // 10. Run the following steps in parallel:
158 m_taskQueue.enqueueTask([this, initData = SharedBuffer::create(initData.data(), initData.length()), initDataType, promise = WTFMove(promise)] () mutable {
159 // 10.1. If the init data is not valid for initDataType, reject promise with a newly created TypeError.
160 // 10.2. Let sanitized init data be a validated and sanitized version of init data.
161 RefPtr<SharedBuffer> sanitizedInitData = m_implementation->sanitizeInitData(initDataType, initData);
162
163 // 10.3. If the preceding step failed, reject promise with a newly created TypeError.
164 if (!sanitizedInitData) {
165 promise->reject(TypeError);
166 return;
167 }
168
169 // 10.4. If sanitized init data is empty, reject promise with a NotSupportedError.
170 if (sanitizedInitData->isEmpty()) {
171 promise->reject(NotSupportedError);
172 return;
173 }
174
175 // 10.5. Let session id be the empty string.
176 // 10.6. Let message be null.
177 // 10.7. Let message type be null.
178 // 10.8. Let cdm be the CDM instance represented by this object's cdm instance value.
179 // 10.9. Use the cdm to execute the following steps:
180 // 10.9.1. If the sanitized init data is not supported by the cdm, reject promise with a NotSupportedError.
181 if (!m_implementation->supportsInitData(initDataType, *sanitizedInitData)) {
182 promise->reject(NotSupportedError);
183 return;
184 }
185
186 // 10.9.2 Follow the steps for the value of session type from the following list:
187 // ↳ "temporary"
188 // Let requested license type be a temporary non-persistable license.
189 // ↳ "persistent-license"
190 // Let requested license type be a persistable license.
191 // ↳ "persistent-usage-record"
192 // 1. Initialize this object's record of key usage as follows.
193 // Set the list of key IDs known to the session to an empty list.
194 // Set the first decrypt time to null.
195 // Set the latest decrypt time to null.
196 // 2. Let requested license type be a non-persistable license that will
197 // persist a record of key usage.
198
199 if (m_sessionType == MediaKeySessionType::PersistentUsageRecord) {
200 m_recordOfKeyUsage.clear();
201 m_firstDecryptTime = 0;
202 m_latestDecryptTime = 0;
203 }
204
205 LOG(EME, "EME - request license from CDM implementation");
206 m_instanceSession->requestLicense(m_sessionType, initDataType, sanitizedInitData.releaseNonNull(), [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] (Ref<SharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstanceSession::SuccessValue succeeded) mutable {
207 if (!weakThis)
208 return;
209
210 // 10.9.3. Let session id be a unique Session ID string.
211
212 MediaKeyMessageType messageType;
213 if (!needsIndividualization) {
214 // 10.9.4. If a license request for the requested license type can be generated based on the sanitized init data:
215 // 10.9.4.1. Let message be a license request for the requested license type generated based on the sanitized init data interpreted per initDataType.
216 // 10.9.4.2. Let message type be "license-request".
217 messageType = MediaKeyMessageType::LicenseRequest;
218 } else {
219 // 10.9.5. Otherwise:
220 // 10.9.5.1. Let message be the request that needs to be processed before a license request request for the requested license
221 // type can be generated based on the sanitized init data.
222 // 10.9.5.2. Let message type reflect the type of message, either "license-request" or "individualization-request".
223 messageType = MediaKeyMessageType::IndividualizationRequest;
224 }
225
226 // 10.10. Queue a task to run the following steps:
227 m_taskQueue.enqueueTask([this, promise = WTFMove(promise), message = WTFMove(message), messageType, sessionId, succeeded] () mutable {
228 // 10.10.1. If any of the preceding steps failed, reject promise with a new DOMException whose name is the appropriate error name.
229 if (succeeded == CDMInstanceSession::SuccessValue::Failed) {
230 promise->reject(NotSupportedError);
231 return;
232 }
233 // 10.10.2. Set the sessionId attribute to session id.
234 m_sessionId = sessionId;
235
236 // 10.9.3. Let this object's callable value be true.
237 m_callable = true;
238
239 // 10.9.3. Run the Queue a "message" Event algorithm on the session, providing message type and message.
240 enqueueMessage(messageType, message);
241
242 // 10.9.3. Resolve promise.
243 promise->resolve();
244 });
245 });
246 });
247
248 // 11. Return promise.
249}
250
251void MediaKeySession::load(const String& sessionId, Ref<DeferredPromise>&& promise)
252{
253 // https://w3c.github.io/encrypted-media/#dom-mediakeysession-load
254 // W3C Editor's Draft 09 November 2016
255
256 // 1. If this object is closed, return a promise rejected with an InvalidStateError.
257 // 2. If this object's uninitialized value is false, return a promise rejected with an InvalidStateError.
258 if (m_closed || !m_uninitialized) {
259 promise->reject(InvalidStateError);
260 return;
261 }
262
263 // 3. Let this object's uninitialized value be false.
264 m_uninitialized = false;
265
266 // 4. If sessionId is the empty string, return a promise rejected with a newly created TypeError.
267 // 5. If the result of running the Is persistent session type? algorithm on this object's session type is false, return a promise rejected with a newly created TypeError.
268 if (sessionId.isEmpty() || m_sessionType == MediaKeySessionType::Temporary) {
269 promise->reject(TypeError);
270 return;
271 }
272
273 // 6. Let origin be the origin of this object's Document.
274 // This is retrieved in the following task.
275
276 // 7. Let promise be a new promise.
277 // 8. Run the following steps in parallel:
278 m_taskQueue.enqueueTask([this, sessionId, promise = WTFMove(promise)] () mutable {
279 // 8.1. Let sanitized session ID be a validated and/or sanitized version of sessionId.
280 // 8.2. If the preceding step failed, or if sanitized session ID is empty, reject promise with a newly created TypeError.
281 Optional<String> sanitizedSessionId = m_implementation->sanitizeSessionId(sessionId);
282 if (!sanitizedSessionId || sanitizedSessionId->isEmpty()) {
283 promise->reject(TypeError);
284 return;
285 }
286
287 // 8.3. If there is a MediaKeySession object that is not closed in this object's Document whose sessionId attribute is sanitized session ID, reject promise with a QuotaExceededError.
288 // FIXME: This needs a global MediaKeySession tracker.
289
290 String origin;
291 if (auto* document = downcast<Document>(scriptExecutionContext()))
292 origin = document->securityOrigin().toString();
293
294 // 8.4. Let expiration time be NaN.
295 // 8.5. Let message be null.
296 // 8.6. Let message type be null.
297 // 8.7. Let cdm be the CDM instance represented by this object's cdm instance value.
298 // 8.8. Use the cdm to execute the following steps:
299 m_instanceSession->loadSession(m_sessionType, *sanitizedSessionId, origin, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise), sanitizedSessionId = *sanitizedSessionId] (Optional<CDMInstanceSession::KeyStatusVector>&& knownKeys, Optional<double>&& expiration, Optional<CDMInstanceSession::Message>&& message, CDMInstanceSession::SuccessValue succeeded, CDMInstanceSession::SessionLoadFailure failure) mutable {
300 // 8.8.1. If there is no data stored for the sanitized session ID in the origin, resolve promise with false and abort these steps.
301 // 8.8.2. If the stored session's session type is not the same as the current MediaKeySession session type, reject promise with a newly created TypeError.
302 // 8.8.3. Let session data be the data stored for the sanitized session ID in the origin. This must not include data from other origin(s) or that is not associated with an origin.
303 // 8.8.4. If there is a MediaKeySession object that is not closed in any Document and that represents the session data, reject promise with a QuotaExceededError.
304 // 8.8.5. Load the session data.
305 // 8.8.6. If the session data indicates an expiration time for the session, let expiration time be the expiration time in milliseconds since 01 January 1970 UTC.
306 // 8.8.7. If the CDM needs to send a message:
307 // 8.8.7.1. Let message be a message generated by the CDM based on the session data.
308 // 8.8.7.2. Let message type be the appropriate MediaKeyMessageType for the message.
309 // NOTE: Steps 8.8.1. through 8.8.7. should be implemented in CDMInstance.
310
311 if (succeeded == CDMInstanceSession::SuccessValue::Failed) {
312 switch (failure) {
313 case CDMInstanceSession::SessionLoadFailure::NoSessionData:
314 promise->resolve<IDLBoolean>(false);
315 return;
316 case CDMInstanceSession::SessionLoadFailure::MismatchedSessionType:
317 promise->reject(TypeError);
318 return;
319 case CDMInstanceSession::SessionLoadFailure::QuotaExceeded:
320 promise->reject(QuotaExceededError);
321 return;
322 case CDMInstanceSession::SessionLoadFailure::None:
323 case CDMInstanceSession::SessionLoadFailure::Other:
324 // In any other case, the session load failure will cause a rejection in the following task.
325 break;
326 }
327 }
328
329 // 8.9. Queue a task to run the following steps:
330 m_taskQueue.enqueueTask([this, knownKeys = WTFMove(knownKeys), expiration = WTFMove(expiration), message = WTFMove(message), sanitizedSessionId, succeeded, promise = WTFMove(promise)] () mutable {
331 // 8.9.1. If any of the preceding steps failed, reject promise with a the appropriate error name.
332 if (succeeded == CDMInstanceSession::SuccessValue::Failed) {
333 promise->reject(NotSupportedError);
334 return;
335 }
336
337 // 8.9.2. Set the sessionId attribute to sanitized session ID.
338 // 8.9.3. Let this object's callable value be true.
339 m_sessionId = sanitizedSessionId;
340 m_callable = true;
341
342 // 8.9.4. If the loaded session contains information about any keys (there are known keys), run the Update Key Statuses algorithm on the session, providing each key's key ID along with the appropriate MediaKeyStatus.
343 if (knownKeys)
344 updateKeyStatuses(WTFMove(*knownKeys));
345
346 // 8.9.5. Run the Update Expiration algorithm on the session, providing expiration time.
347 // This must be run, and NaN is the default value if the CDM instance doesn't provide one.
348 updateExpiration(expiration.valueOr(std::numeric_limits<double>::quiet_NaN()));
349
350 // 8.9.6. If message is not null, run the Queue a "message" Event algorithm on the session, providing message type and message.
351 if (message)
352 enqueueMessage(message->first, WTFMove(message->second));
353
354 // 8.9.7. Resolve promise with true.
355 promise->resolve<IDLBoolean>(true);
356 });
357 });
358 });
359
360 // 9. Return promise.
361}
362
363void MediaKeySession::update(const BufferSource& response, Ref<DeferredPromise>&& promise)
364{
365 // https://w3c.github.io/encrypted-media/#dom-mediakeysession-update
366 // W3C Editor's Draft 09 November 2016
367
368 // When this method is invoked, the user agent must run the following steps:
369 // 1. If this object is closed, return a promise rejected with an InvalidStateError.
370 // 2. If this object's callable value is false, return a promise rejected with an InvalidStateError.
371 LOG(EME, "EME - update session for %s", m_sessionId.utf8().data());
372
373 if (m_closed || !m_callable) {
374 promise->reject(InvalidStateError);
375 return;
376 }
377
378 // 3. If response is an empty array, return a promise rejected with a newly created TypeError.
379 if (!response.length()) {
380 promise->reject(TypeError);
381 return;
382 }
383
384 // 4. Let response copy be a copy of the contents of the response parameter.
385 // 5. Let promise be a new promise.
386 // 6. Run the following steps in parallel:
387 m_taskQueue.enqueueTask([this, response = SharedBuffer::create(response.data(), response.length()), promise = WTFMove(promise)] () mutable {
388 // 6.1. Let sanitized response be a validated and/or sanitized version of response copy.
389 RefPtr<SharedBuffer> sanitizedResponse = m_implementation->sanitizeResponse(response);
390
391 // 6.2. If the preceding step failed, or if sanitized response is empty, reject promise with a newly created TypeError.
392 if (!sanitizedResponse || sanitizedResponse->isEmpty()) {
393 promise->reject(TypeError);
394 return;
395 }
396
397 // 6.3. Let message be null.
398 // 6.4. Let message type be null.
399 // 6.5. Let session closed be false.
400 // 6.6. Let cdm be the CDM instance represented by this object's cdm instance value.
401 // 6.7. Use the cdm to execute the following steps:
402 m_instanceSession->updateLicense(m_sessionId, m_sessionType, *sanitizedResponse, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] (bool sessionWasClosed, Optional<CDMInstanceSession::KeyStatusVector>&& changedKeys, Optional<double>&& changedExpiration, Optional<CDMInstanceSession::Message>&& message, CDMInstanceSession::SuccessValue succeeded) mutable {
403 if (!weakThis)
404 return;
405
406 // 6.7.1. If the format of sanitized response is invalid in any way, reject promise with a newly created TypeError.
407 // 6.7.2. Process sanitized response, following the stipulation for the first matching condition from the following list:
408 // ↳ If sanitized response contains a license or key(s)
409 // Process sanitized response, following the stipulation for the first matching condition from the following list:
410 // ↳ If sessionType is "temporary" and sanitized response does not specify that session data, including any license, key(s), or similar session data it contains, should be stored
411 // Process sanitized response, not storing any session data.
412 // ↳ If sessionType is "persistent-license" and sanitized response contains a persistable license
413 // Process sanitized response, storing the license/key(s) and related session data contained in sanitized response. Such data must be stored such that only the origin of this object's Document can access it.
414 // ↳ If sessionType is "persistent-usage-record" and sanitized response contains a non-persistable license
415 // Run the following steps:
416 // 6.7.2.3.1. Process sanitized response, not storing any session data.
417 // 6.7.2.3.2. If processing sanitized response results in the addition of keys to the set of known keys, add the key IDs of these keys to this object's record of key usage.
418 // ↳ Otherwise
419 // Reject promise with a newly created TypeError.
420 // ↳ If sanitized response contains a record of license destruction acknowledgement and sessionType is "persistent-license"
421 // Run the following steps:
422 // 6.7.2.1. Close the key session and clear all stored session data associated with this object, including the sessionId and record of license destruction.
423 // 6.7.2.2. Set session closed to true.
424 // ↳ Otherwise
425 // Process sanitized response, not storing any session data.
426 // NOTE: Steps 6.7.1. and 6.7.2. should be implemented in CDMInstance.
427
428 if (succeeded == CDMInstanceSession::SuccessValue::Failed) {
429 LOG(EME, "EME - failed to update CDM license for %s", m_sessionId.utf8().data());
430 promise->reject(TypeError);
431 return;
432 }
433
434 // 6.7.3. If a message needs to be sent to the server, execute the following steps:
435 // 6.7.3.1. Let message be that message.
436 // 6.7.3.2. Let message type be the appropriate MediaKeyMessageType for the message.
437 // 6.8. Queue a task to run the following steps:
438 m_taskQueue.enqueueTask([this, sessionWasClosed, changedKeys = WTFMove(changedKeys), changedExpiration = WTFMove(changedExpiration), message = WTFMove(message), promise = WTFMove(promise)] () mutable {
439 LOG(EME, "EME - updating CDM license succeeded for session %s, sending a message to the license server", m_sessionId.utf8().data());
440 // 6.8.1.
441 if (sessionWasClosed) {
442 // ↳ If session closed is true:
443 // Run the Session Closed algorithm on this object.
444 sessionClosed();
445 } else {
446 // ↳ Otherwise:
447 // Run the following steps:
448 // 6.8.1.1. If the set of keys known to the CDM for this object changed or the status of any key(s) changed, run the Update Key Statuses
449 // algorithm on the session, providing each known key's key ID along with the appropriate MediaKeyStatus. Should additional
450 // processing be necessary to determine with certainty the status of a key, use "status-pending". Once the additional processing
451 // for one or more keys has completed, run the Update Key Statuses algorithm again with the actual status(es).
452 if (changedKeys)
453 updateKeyStatuses(WTFMove(*changedKeys));
454
455 // 6.8.1.2. If the expiration time for the session changed, run the Update Expiration algorithm on the session, providing the new expiration time.
456 if (changedExpiration)
457 updateExpiration(*changedExpiration);
458
459 // 6.8.1.3. If any of the preceding steps failed, reject promise with a new DOMException whose name is the appropriate error name.
460 // FIXME: At this point the implementations of preceding steps can't fail.
461
462 // 6.8.1.4. If message is not null, run the Queue a "message" Event algorithm on the session, providing message type and message.
463 if (message) {
464 MediaKeyMessageType messageType;
465 switch (message->first) {
466 case CDMInstanceSession::MessageType::LicenseRequest:
467 messageType = MediaKeyMessageType::LicenseRequest;
468 break;
469 case CDMInstanceSession::MessageType::LicenseRenewal:
470 messageType = MediaKeyMessageType::LicenseRenewal;
471 break;
472 case CDMInstanceSession::MessageType::LicenseRelease:
473 messageType = MediaKeyMessageType::LicenseRelease;
474 break;
475 case CDMInstanceSession::MessageType::IndividualizationRequest:
476 messageType = MediaKeyMessageType::IndividualizationRequest;
477 break;
478 }
479
480 enqueueMessage(messageType, WTFMove(message->second));
481 }
482 }
483
484 // 6.8.2. Resolve promise.
485 promise->resolve();
486 });
487 });
488 });
489
490 // 7. Return promise.
491}
492
493void MediaKeySession::close(Ref<DeferredPromise>&& promise)
494{
495 // https://w3c.github.io/encrypted-media/#dom-mediakeysession-close
496 // W3C Editor's Draft 09 November 2016
497
498 // 1. Let session be the associated MediaKeySession object.
499 // 2. If session is closed, return a resolved promise.
500 LOG(EME, "EME - closing session %s", m_sessionId.utf8().data());
501
502 if (m_closed) {
503 promise->resolve();
504 return;
505 }
506
507 // 3. If session's callable value is false, return a promise rejected with an InvalidStateError.
508 if (!m_callable) {
509 promise->reject(InvalidStateError);
510 return;
511 }
512
513 // 4. Let promise be a new promise.
514 // 5. Run the following steps in parallel:
515 m_taskQueue.enqueueTask([this, promise = WTFMove(promise)] () mutable {
516 // 5.1. Let cdm be the CDM instance represented by session's cdm instance value.
517 // 5.2. Use cdm to close the key session associated with session.
518 LOG(EME, "EME - closing CDM session %s", m_sessionId.utf8().data());
519 m_instanceSession->closeSession(m_sessionId, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] () mutable {
520 if (!weakThis)
521 return;
522
523 // 5.3. Queue a task to run the following steps:
524 m_taskQueue.enqueueTask([this, promise = WTFMove(promise)] () mutable {
525 // 5.3.1. Run the Session Closed algorithm on the session.
526 sessionClosed();
527
528 // 5.3.2. Resolve promise.
529 promise->resolve();
530 });
531 });
532 });
533
534 // 6. Return promise.
535}
536
537void MediaKeySession::remove(Ref<DeferredPromise>&& promise)
538{
539 // https://w3c.github.io/encrypted-media/#dom-mediakeysession-remove
540 // W3C Editor's Draft 09 November 2016
541
542 // 1. If this object is closed, return a promise rejected with an InvalidStateError.
543 // 2. If this object's callable value is false, return a promise rejected with an InvalidStateError.
544 LOG(EME, "EME - removing session %s", m_sessionId.utf8().data());
545
546 if (m_closed || !m_callable) {
547 promise->reject(InvalidStateError);
548 return;
549 }
550
551 // 3. Let promise be a new promise.
552 // 4. Run the following steps in parallel:
553 m_taskQueue.enqueueTask([this, promise = WTFMove(promise)] () mutable {
554 // 4.1. Let cdm be the CDM instance represented by this object's cdm instance value.
555 // 4.2. Let message be null.
556 // 4.3. Let message type be null.
557
558 // 4.4. Use the cdm to execute the following steps:
559 m_instanceSession->removeSessionData(m_sessionId, m_sessionType, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] (CDMInstanceSession::KeyStatusVector&& keys, Optional<Ref<SharedBuffer>>&& message, CDMInstanceSession::SuccessValue succeeded) mutable {
560 if (!weakThis)
561 return;
562
563 // 4.4.1. If any license(s) and/or key(s) are associated with the session:
564 // 4.4.1.1. Destroy the license(s) and/or key(s) associated with the session.
565 // 4.4.1.2. Follow the steps for the value of this object's session type from the following list:
566 // ↳ "temporary"
567 // 4.4.1.2.1.1 Continue with the following steps.
568 // ↳ "persistent-license"
569 // 4.4.1.2.2.1. Let record of license destruction be a record of license destruction for the license represented by this object.
570 // 4.4.1.2.2.2. Store the record of license destruction.
571 // 4.4.1.2.2.3. Let message be a message containing or reflecting the record of license destruction.
572 // ↳ "persistent-usage-record"
573 // 4.4.1.2.3.1. Store this object's record of key usage.
574 // 4.4.1.2.3.2. Let message be a message containing or reflecting this object's record of key usage.
575 // NOTE: Step 4.4.1. should be implemented in CDMInstance.
576
577 // 4.5. Queue a task to run the following steps:
578 m_taskQueue.enqueueTask([this, keys = WTFMove(keys), message = WTFMove(message), succeeded, promise = WTFMove(promise)] () mutable {
579 // 4.5.1. Run the Update Key Statuses algorithm on the session, providing all key ID(s) in the session along with the "released" MediaKeyStatus value for each.
580 updateKeyStatuses(WTFMove(keys));
581
582 // 4.5.2. Run the Update Expiration algorithm on the session, providing NaN.
583 updateExpiration(std::numeric_limits<double>::quiet_NaN());
584
585 // 4.5.3. If any of the preceding steps failed, reject promise with a new DOMException whose name is the appropriate error name.
586 if (succeeded == CDMInstanceSession::SuccessValue::Failed) {
587 promise->reject(NotSupportedError);
588 return;
589 }
590
591 // 4.5.4. Let message type be "license-release".
592 // 4.5.5. If message is not null, run the Queue a "message" Event algorithm on the session, providing message type and message.
593 if (message)
594 enqueueMessage(MediaKeyMessageType::LicenseRelease, *message);
595
596 // 4.5.6. Resolve promise.
597 promise->resolve();
598 });
599 });
600 });
601
602 // 5. Return promise.
603}
604
605void MediaKeySession::enqueueMessage(MediaKeyMessageType messageType, const SharedBuffer& message)
606{
607 // 6.4.1 Queue a "message" Event
608 // https://w3c.github.io/encrypted-media/#queue-message
609 // W3C Editor's Draft 09 November 2016
610
611 // The following steps are run:
612 // 1. Let the session be the specified MediaKeySession object.
613 // 2. Queue a task to create an event named message that does not bubble and is not cancellable using the MediaKeyMessageEvent
614 // interface with its type attribute set to message and its isTrusted attribute initialized to true, and dispatch it at the
615 // session.
616 auto messageEvent = MediaKeyMessageEvent::create(eventNames().messageEvent, {messageType, message.tryCreateArrayBuffer()}, Event::IsTrusted::Yes);
617 m_eventQueue.enqueueEvent(WTFMove(messageEvent));
618}
619
620void MediaKeySession::updateKeyStatuses(CDMInstanceSession::KeyStatusVector&& inputStatuses)
621{
622 // https://w3c.github.io/encrypted-media/#update-key-statuses
623 // W3C Editor's Draft 09 November 2016
624
625 // 1. Let the session be the associated MediaKeySession object.
626 // 2. Let the input statuses be the sequence of pairs key ID and associated MediaKeyStatus pairs.
627 // 3. Let the statuses be session's keyStatuses attribute.
628 // 4. Run the following steps to replace the contents of statuses:
629 // 4.1. Empty statuses.
630 // 4.2. For each pair in input statuses.
631 // 4.2.1. Let pair be the pair.
632 // 4.2.2. Insert an entry for pair's key ID into statuses with the value of pair's MediaKeyStatus value.
633
634 static auto toMediaKeyStatus = [] (CDMInstanceSession::KeyStatus status) -> MediaKeyStatus {
635 switch (status) {
636 case CDMInstanceSession::KeyStatus::Usable:
637 return MediaKeyStatus::Usable;
638 case CDMInstanceSession::KeyStatus::Expired:
639 return MediaKeyStatus::Expired;
640 case CDMInstanceSession::KeyStatus::Released:
641 return MediaKeyStatus::Released;
642 case CDMInstanceSession::KeyStatus::OutputRestricted:
643 return MediaKeyStatus::OutputRestricted;
644 case CDMInstanceSession::KeyStatus::OutputDownscaled:
645 return MediaKeyStatus::OutputDownscaled;
646 case CDMInstanceSession::KeyStatus::StatusPending:
647 return MediaKeyStatus::StatusPending;
648 case CDMInstanceSession::KeyStatus::InternalError:
649 return MediaKeyStatus::InternalError;
650 };
651
652 ASSERT_NOT_REACHED();
653 return MediaKeyStatus::InternalError;
654 };
655
656 m_statuses.clear();
657 m_statuses.reserveCapacity(inputStatuses.size());
658 for (auto& status : inputStatuses)
659 m_statuses.uncheckedAppend({ WTFMove(status.first), toMediaKeyStatus(status.second) });
660
661 // 5. Queue a task to fire a simple event named keystatuseschange at the session.
662 m_eventQueue.enqueueEvent(Event::create(eventNames().keystatuseschangeEvent, Event::CanBubble::No, Event::IsCancelable::No));
663
664 // 6. Queue a task to run the Attempt to Resume Playback If Necessary algorithm on each of the media element(s) whose mediaKeys attribute is the MediaKeys object that created the session.
665 m_taskQueue.enqueueTask(
666 [this] () mutable {
667 if (m_keys)
668 m_keys->attemptToResumePlaybackOnClients();
669 });
670}
671
672void MediaKeySession::sendMessage(CDMMessageType messageType, Ref<SharedBuffer>&& message)
673{
674 enqueueMessage(messageType, message);
675}
676
677void MediaKeySession::sessionIdChanged(const String& sessionId)
678{
679 m_sessionId = sessionId;
680}
681
682void MediaKeySession::updateExpiration(double)
683{
684 notImplemented();
685}
686
687void MediaKeySession::sessionClosed()
688{
689 // https://w3c.github.io/encrypted-media/#session-closed
690 // W3C Editor's Draft 09 November 2016
691 LOG(EME, "EME - session %s was closed", m_sessionId.utf8().data());
692
693 // 1. Let session be the associated MediaKeySession object.
694 // 2. If session's session type is "persistent-usage-record", execute the following steps in parallel:
695 if (m_sessionType == MediaKeySessionType::PersistentUsageRecord) {
696 // 2.1. Let cdm be the CDM instance represented by session's cdm instance value.
697 // 2.2. Use cdm to store session's record of key usage, if it exists.
698 m_instanceSession->storeRecordOfKeyUsage(m_sessionId);
699 }
700
701 // 3. Run the Update Key Statuses algorithm on the session, providing an empty sequence.
702 updateKeyStatuses({ });
703
704 // 4. Run the Update Expiration algorithm on the session, providing NaN.
705 updateExpiration(std::numeric_limits<double>::quiet_NaN());
706
707 // Let's consider the session closed before any promise on the 'closed' attribute is resolved.
708 m_closed = true;
709
710 // 5. Let promise be the closed attribute of the session.
711 // 6. Resolve promise.
712 m_closedPromise.resolve();
713}
714
715String MediaKeySession::mediaKeysStorageDirectory() const
716{
717 auto* document = downcast<Document>(scriptExecutionContext());
718 if (!document)
719 return emptyString();
720
721 auto* page = document->page();
722 if (!page || page->usesEphemeralSession())
723 return emptyString();
724
725 auto storageDirectory = document->settings().mediaKeysStorageDirectory();
726 if (storageDirectory.isEmpty())
727 return emptyString();
728
729 return FileSystem::pathByAppendingComponent(storageDirectory, document->securityOrigin().data().databaseIdentifier());
730}
731
732bool MediaKeySession::hasPendingActivity() const
733{
734 notImplemented();
735 return false;
736}
737
738const char* MediaKeySession::activeDOMObjectName() const
739{
740 notImplemented();
741 return "MediaKeySession";
742}
743
744bool MediaKeySession::canSuspendForDocumentSuspension() const
745{
746 notImplemented();
747 return false;
748}
749
750void MediaKeySession::stop()
751{
752 notImplemented();
753}
754
755} // namespace WebCore
756
757#endif
758