1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/cdm/proxy_decryptor.h"
10 #include "base/callback_helpers.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_util.h"
14 #include "media/base/cdm_callback_promise.h"
15 #include "media/base/cdm_config.h"
16 #include "media/base/cdm_factory.h"
17 #include "media/base/cdm_key_information.h"
18 #include "media/base/key_systems.h"
19 #include "media/base/media_permission.h"
20 #include "media/cdm/json_web_key.h"
21 #include "media/cdm/key_system_names.h"
25 // Special system code to signal a closed persistent session in a SessionError()
26 // call. This is needed because there is no SessionClosed() call in the prefixed
28 const int kSessionClosedSystemCode
= 29127;
30 ProxyDecryptor::PendingGenerateKeyRequestData::PendingGenerateKeyRequestData(
31 EmeInitDataType init_data_type
,
32 const std::vector
<uint8
>& init_data
)
33 : init_data_type(init_data_type
), init_data(init_data
) {
36 ProxyDecryptor::PendingGenerateKeyRequestData::
37 ~PendingGenerateKeyRequestData() {
40 ProxyDecryptor::ProxyDecryptor(MediaPermission
* media_permission
,
41 const KeyAddedCB
& key_added_cb
,
42 const KeyErrorCB
& key_error_cb
,
43 const KeyMessageCB
& key_message_cb
)
44 : is_creating_cdm_(false),
45 media_permission_(media_permission
),
46 key_added_cb_(key_added_cb
),
47 key_error_cb_(key_error_cb
),
48 key_message_cb_(key_message_cb
),
50 weak_ptr_factory_(this) {
51 DCHECK(media_permission
);
52 DCHECK(!key_added_cb_
.is_null());
53 DCHECK(!key_error_cb_
.is_null());
54 DCHECK(!key_message_cb_
.is_null());
57 ProxyDecryptor::~ProxyDecryptor() {
58 // Destroy the decryptor explicitly before destroying the plugin.
62 void ProxyDecryptor::CreateCdm(CdmFactory
* cdm_factory
,
63 const std::string
& key_system
,
64 const GURL
& security_origin
,
65 const CdmContextReadyCB
& cdm_context_ready_cb
) {
66 DVLOG(1) << __FUNCTION__
<< ": key_system = " << key_system
;
67 DCHECK(!is_creating_cdm_
);
70 // TODO(sandersd): Trigger permissions check here and use it to determine
71 // distinctive identifier support, instead of always requiring the
72 // permission. http://crbug.com/455271
74 cdm_config
.allow_distinctive_identifier
= true;
75 cdm_config
.allow_persistent_state
= true;
77 is_creating_cdm_
= true;
79 base::WeakPtr
<ProxyDecryptor
> weak_this
= weak_ptr_factory_
.GetWeakPtr();
81 key_system
, security_origin
, cdm_config
,
82 base::Bind(&ProxyDecryptor::OnSessionMessage
, weak_this
),
83 base::Bind(&ProxyDecryptor::OnSessionClosed
, weak_this
),
84 base::Bind(&ProxyDecryptor::OnLegacySessionError
, weak_this
),
85 base::Bind(&ProxyDecryptor::OnSessionKeysChange
, weak_this
),
86 base::Bind(&ProxyDecryptor::OnSessionExpirationUpdate
, weak_this
),
87 base::Bind(&ProxyDecryptor::OnCdmCreated
, weak_this
, key_system
,
88 security_origin
, cdm_context_ready_cb
));
91 void ProxyDecryptor::OnCdmCreated(const std::string
& key_system
,
92 const GURL
& security_origin
,
93 const CdmContextReadyCB
& cdm_context_ready_cb
,
94 scoped_ptr
<MediaKeys
> cdm
,
95 const std::string
& /* error_message */) {
96 is_creating_cdm_
= false;
99 cdm_context_ready_cb
.Run(nullptr);
101 key_system_
= key_system
;
102 security_origin_
= security_origin
;
103 is_clear_key_
= IsClearKey(key_system
) || IsExternalClearKey(key_system
);
104 media_keys_
= cdm
.Pass();
106 cdm_context_ready_cb
.Run(media_keys_
->GetCdmContext());
109 for (const auto& request
: pending_requests_
)
110 GenerateKeyRequestInternal(request
->init_data_type
, request
->init_data
);
112 pending_requests_
.clear();
115 void ProxyDecryptor::GenerateKeyRequest(EmeInitDataType init_data_type
,
116 const uint8
* init_data
,
117 int init_data_length
) {
118 std::vector
<uint8
> init_data_vector(init_data
, init_data
+ init_data_length
);
120 if (is_creating_cdm_
) {
121 pending_requests_
.push_back(
122 new PendingGenerateKeyRequestData(init_data_type
, init_data_vector
));
126 GenerateKeyRequestInternal(init_data_type
, init_data_vector
);
129 // Returns true if |data| is prefixed with |header| and has data after the
131 bool HasHeader(const std::vector
<uint8
>& data
, const std::string
& header
) {
132 return data
.size() > header
.size() &&
133 std::equal(header
.begin(), header
.end(), data
.begin());
136 // Removes the first |length| items from |data|.
137 void StripHeader(std::vector
<uint8
>& data
, size_t length
) {
138 data
.erase(data
.begin(), data
.begin() + length
);
141 void ProxyDecryptor::GenerateKeyRequestInternal(
142 EmeInitDataType init_data_type
,
143 const std::vector
<uint8
>& init_data
) {
144 DVLOG(1) << __FUNCTION__
;
145 DCHECK(!is_creating_cdm_
);
148 OnLegacySessionError(std::string(), MediaKeys::NOT_SUPPORTED_ERROR
, 0,
149 "CDM creation failed.");
153 const char kPrefixedApiPersistentSessionHeader
[] = "PERSISTENT|";
154 const char kPrefixedApiLoadSessionHeader
[] = "LOAD_SESSION|";
156 SessionCreationType session_creation_type
= TemporarySession
;
157 std::vector
<uint8
> stripped_init_data
= init_data
;
158 if (HasHeader(init_data
, kPrefixedApiLoadSessionHeader
)) {
159 session_creation_type
= LoadSession
;
160 StripHeader(stripped_init_data
, strlen(kPrefixedApiLoadSessionHeader
));
161 } else if (HasHeader(init_data
, kPrefixedApiPersistentSessionHeader
)) {
162 session_creation_type
= PersistentSession
;
163 StripHeader(stripped_init_data
,
164 strlen(kPrefixedApiPersistentSessionHeader
));
167 scoped_ptr
<NewSessionCdmPromise
> promise(new CdmCallbackPromise
<std::string
>(
168 base::Bind(&ProxyDecryptor::SetSessionId
, weak_ptr_factory_
.GetWeakPtr(),
169 session_creation_type
),
170 base::Bind(&ProxyDecryptor::OnLegacySessionError
,
171 weak_ptr_factory_
.GetWeakPtr(),
172 std::string()))); // No session id until created.
174 if (session_creation_type
== LoadSession
) {
175 media_keys_
->LoadSession(
176 MediaKeys::PERSISTENT_LICENSE_SESSION
,
178 reinterpret_cast<const char*>(vector_as_array(&stripped_init_data
)),
179 stripped_init_data
.size()),
184 MediaKeys::SessionType session_type
=
185 session_creation_type
== PersistentSession
186 ? MediaKeys::PERSISTENT_LICENSE_SESSION
187 : MediaKeys::TEMPORARY_SESSION
;
189 // No permission required when AesDecryptor is used or when the key system is
190 // external clear key.
191 DCHECK(!key_system_
.empty());
192 if (CanUseAesDecryptor(key_system_
) || IsExternalClearKey(key_system_
)) {
193 OnPermissionStatus(session_type
, init_data_type
, stripped_init_data
,
194 promise
.Pass(), true /* granted */);
198 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
199 media_permission_
->RequestPermission(
200 MediaPermission::PROTECTED_MEDIA_IDENTIFIER
, security_origin_
,
201 base::Bind(&ProxyDecryptor::OnPermissionStatus
,
202 weak_ptr_factory_
.GetWeakPtr(), session_type
, init_data_type
,
203 stripped_init_data
, base::Passed(&promise
)));
205 OnPermissionStatus(session_type
, init_data_type
, stripped_init_data
,
206 promise
.Pass(), true /* granted */);
210 void ProxyDecryptor::OnPermissionStatus(
211 MediaKeys::SessionType session_type
,
212 EmeInitDataType init_data_type
,
213 const std::vector
<uint8
>& init_data
,
214 scoped_ptr
<NewSessionCdmPromise
> promise
,
216 // ProxyDecryptor is only used by Prefixed EME, where RequestPermission() is
217 // only for triggering the permission UI. Later CheckPermission() will be
218 // called (e.g. in PlatformVerificationFlow on ChromeOS; in BrowserCdmManager
219 // on Android) and the permission status will be evaluated then.
220 DVLOG_IF(1, !granted
) << "Permission request rejected.";
222 media_keys_
->CreateSessionAndGenerateRequest(session_type
, init_data_type
,
223 init_data
, promise
.Pass());
226 void ProxyDecryptor::AddKey(const uint8
* key
,
228 const uint8
* init_data
,
229 int init_data_length
,
230 const std::string
& session_id
) {
231 DVLOG(1) << "AddKey()";
234 OnLegacySessionError(std::string(), MediaKeys::INVALID_STATE_ERROR
, 0,
235 "CDM is not available.");
239 // In the prefixed API, the session parameter provided to addKey() is
240 // optional, so use the single existing session if it exists.
241 std::string
new_session_id(session_id
);
242 if (new_session_id
.empty()) {
243 if (active_sessions_
.size() == 1) {
244 base::hash_map
<std::string
, bool>::iterator it
= active_sessions_
.begin();
245 new_session_id
= it
->first
;
247 OnLegacySessionError(std::string(), MediaKeys::NOT_SUPPORTED_ERROR
, 0,
248 "SessionId not specified.");
253 scoped_ptr
<SimpleCdmPromise
> promise(new CdmCallbackPromise
<>(
254 base::Bind(&ProxyDecryptor::GenerateKeyAdded
,
255 weak_ptr_factory_
.GetWeakPtr(), session_id
),
256 base::Bind(&ProxyDecryptor::OnLegacySessionError
,
257 weak_ptr_factory_
.GetWeakPtr(), session_id
)));
259 // EME WD spec only supports a single array passed to the CDM. For
260 // Clear Key using v0.1b, both arrays are used (|init_data| is key_id).
261 // Since the EME WD spec supports the key as a JSON Web Key,
262 // convert the 2 arrays to a JWK and pass it as the single array.
264 // Decryptor doesn't support empty key ID (see http://crbug.com/123265).
265 // So ensure a non-empty value is passed.
267 static const uint8 kDummyInitData
[1] = {0};
268 init_data
= kDummyInitData
;
269 init_data_length
= arraysize(kDummyInitData
);
273 GenerateJWKSet(key
, key_length
, init_data
, init_data_length
);
274 DCHECK(!jwk
.empty());
275 media_keys_
->UpdateSession(new_session_id
,
276 std::vector
<uint8_t>(jwk
.begin(), jwk
.end()),
281 media_keys_
->UpdateSession(new_session_id
,
282 std::vector
<uint8_t>(key
, key
+ key_length
),
286 void ProxyDecryptor::CancelKeyRequest(const std::string
& session_id
) {
287 DVLOG(1) << "CancelKeyRequest()";
290 OnLegacySessionError(std::string(), MediaKeys::INVALID_STATE_ERROR
, 0,
291 "CDM is not available.");
295 scoped_ptr
<SimpleCdmPromise
> promise(new CdmCallbackPromise
<>(
296 base::Bind(&ProxyDecryptor::OnSessionClosed
,
297 weak_ptr_factory_
.GetWeakPtr(), session_id
),
298 base::Bind(&ProxyDecryptor::OnLegacySessionError
,
299 weak_ptr_factory_
.GetWeakPtr(), session_id
)));
300 media_keys_
->RemoveSession(session_id
, promise
.Pass());
303 void ProxyDecryptor::OnSessionMessage(const std::string
& session_id
,
304 MediaKeys::MessageType message_type
,
305 const std::vector
<uint8
>& message
,
306 const GURL
& legacy_destination_url
) {
307 // Assumes that OnSessionCreated() has been called before this.
309 // For ClearKey, convert the message from JSON into just passing the key
310 // as the message. If unable to extract the key, return the message unchanged.
312 std::vector
<uint8
> key
;
313 if (ExtractFirstKeyIdFromLicenseRequest(message
, &key
)) {
314 key_message_cb_
.Run(session_id
, key
, legacy_destination_url
);
319 key_message_cb_
.Run(session_id
, message
, legacy_destination_url
);
322 void ProxyDecryptor::OnSessionKeysChange(const std::string
& session_id
,
323 bool has_additional_usable_key
,
324 CdmKeysInfo keys_info
) {
325 // EME v0.1b doesn't support this event.
328 void ProxyDecryptor::OnSessionExpirationUpdate(
329 const std::string
& session_id
,
330 const base::Time
& new_expiry_time
) {
331 // EME v0.1b doesn't support this event.
334 void ProxyDecryptor::GenerateKeyAdded(const std::string
& session_id
) {
335 // EME WD doesn't support this event, but it is needed for EME v0.1b.
336 key_added_cb_
.Run(session_id
);
339 void ProxyDecryptor::OnSessionClosed(const std::string
& session_id
) {
340 base::hash_map
<std::string
, bool>::iterator it
=
341 active_sessions_
.find(session_id
);
343 // Latest EME spec separates closing a session ("allows an application to
344 // indicate that it no longer needs the session") and actually closing the
345 // session (done by the CDM at any point "such as in response to a close()
346 // call, when the session is no longer needed, or when system resources are
347 // lost.") Thus the CDM may cause 2 close() events -- one to resolve the
348 // close() promise, and a second to actually close the session. Prefixed EME
349 // only expects 1 close event, so drop the second (and subsequent) events.
350 // However, this means we can't tell if the CDM is generating spurious close()
352 if (it
== active_sessions_
.end())
356 OnLegacySessionError(session_id
, MediaKeys::NOT_SUPPORTED_ERROR
,
357 kSessionClosedSystemCode
,
358 "Do not close persistent sessions.");
360 active_sessions_
.erase(it
);
363 void ProxyDecryptor::OnLegacySessionError(const std::string
& session_id
,
364 MediaKeys::Exception exception_code
,
366 const std::string
& error_message
) {
367 // Convert |error_name| back to MediaKeys::KeyError if possible. Prefixed
368 // EME has different error message, so all the specific error events will
370 MediaKeys::KeyError error_code
;
371 switch (exception_code
) {
372 case MediaKeys::CLIENT_ERROR
:
373 error_code
= MediaKeys::kClientError
;
375 case MediaKeys::OUTPUT_ERROR
:
376 error_code
= MediaKeys::kOutputError
;
379 // This will include all other CDM4 errors and any error generated
381 error_code
= MediaKeys::kUnknownError
;
384 key_error_cb_
.Run(session_id
, error_code
, system_code
);
387 void ProxyDecryptor::SetSessionId(SessionCreationType session_type
,
388 const std::string
& session_id
) {
389 // Loaded sessions are considered persistent.
391 session_type
== PersistentSession
|| session_type
== LoadSession
;
392 active_sessions_
.insert(std::make_pair(session_id
, is_persistent
));
394 // For LoadSession(), generate the KeyAdded event.
395 if (session_type
== LoadSession
)
396 GenerateKeyAdded(session_id
);