[Android] Open up API in jni bridge to fetch images from tab
[chromium-blink-merge.git] / media / cdm / aes_decryptor.cc
blob1c9171c4eb810b78de1d72c63095f6ea24e40706
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/aes_decryptor.h"
7 #include <list>
8 #include <vector>
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "crypto/encryptor.h"
14 #include "crypto/symmetric_key.h"
15 #include "media/base/audio_decoder_config.h"
16 #include "media/base/cdm_key_information.h"
17 #include "media/base/cdm_promise.h"
18 #include "media/base/decoder_buffer.h"
19 #include "media/base/decrypt_config.h"
20 #include "media/base/video_decoder_config.h"
21 #include "media/base/video_frame.h"
22 #include "media/cdm/json_web_key.h"
24 namespace media {
26 // Keeps track of the session IDs and DecryptionKeys. The keys are ordered by
27 // insertion time (last insertion is first). It takes ownership of the
28 // DecryptionKeys.
29 class AesDecryptor::SessionIdDecryptionKeyMap {
30 // Use a std::list to actually hold the data. Insertion is always done
31 // at the front, so the "latest" decryption key is always the first one
32 // in the list.
33 typedef std::list<std::pair<std::string, DecryptionKey*> > KeyList;
35 public:
36 SessionIdDecryptionKeyMap() {}
37 ~SessionIdDecryptionKeyMap() { STLDeleteValues(&key_list_); }
39 // Replaces value if |session_id| is already present, or adds it if not.
40 // This |decryption_key| becomes the latest until another insertion or
41 // |session_id| is erased.
42 void Insert(const std::string& session_id,
43 scoped_ptr<DecryptionKey> decryption_key);
45 // Deletes the entry for |session_id| if present.
46 void Erase(const std::string& session_id);
48 // Returns whether the list is empty
49 bool Empty() const { return key_list_.empty(); }
51 // Returns the last inserted DecryptionKey.
52 DecryptionKey* LatestDecryptionKey() {
53 DCHECK(!key_list_.empty());
54 return key_list_.begin()->second;
57 bool Contains(const std::string& session_id) {
58 return Find(session_id) != key_list_.end();
61 private:
62 // Searches the list for an element with |session_id|.
63 KeyList::iterator Find(const std::string& session_id);
65 // Deletes the entry pointed to by |position|.
66 void Erase(KeyList::iterator position);
68 KeyList key_list_;
70 DISALLOW_COPY_AND_ASSIGN(SessionIdDecryptionKeyMap);
73 void AesDecryptor::SessionIdDecryptionKeyMap::Insert(
74 const std::string& session_id,
75 scoped_ptr<DecryptionKey> decryption_key) {
76 KeyList::iterator it = Find(session_id);
77 if (it != key_list_.end())
78 Erase(it);
79 DecryptionKey* raw_ptr = decryption_key.release();
80 key_list_.push_front(std::make_pair(session_id, raw_ptr));
83 void AesDecryptor::SessionIdDecryptionKeyMap::Erase(
84 const std::string& session_id) {
85 KeyList::iterator it = Find(session_id);
86 if (it == key_list_.end())
87 return;
88 Erase(it);
91 AesDecryptor::SessionIdDecryptionKeyMap::KeyList::iterator
92 AesDecryptor::SessionIdDecryptionKeyMap::Find(const std::string& session_id) {
93 for (KeyList::iterator it = key_list_.begin(); it != key_list_.end(); ++it) {
94 if (it->first == session_id)
95 return it;
97 return key_list_.end();
100 void AesDecryptor::SessionIdDecryptionKeyMap::Erase(
101 KeyList::iterator position) {
102 DCHECK(position->second);
103 delete position->second;
104 key_list_.erase(position);
107 uint32 AesDecryptor::next_session_id_ = 1;
109 enum ClearBytesBufferSel {
110 kSrcContainsClearBytes,
111 kDstContainsClearBytes
114 static void CopySubsamples(const std::vector<SubsampleEntry>& subsamples,
115 const ClearBytesBufferSel sel,
116 const uint8* src,
117 uint8* dst) {
118 for (size_t i = 0; i < subsamples.size(); i++) {
119 const SubsampleEntry& subsample = subsamples[i];
120 if (sel == kSrcContainsClearBytes) {
121 src += subsample.clear_bytes;
122 } else {
123 dst += subsample.clear_bytes;
125 memcpy(dst, src, subsample.cypher_bytes);
126 src += subsample.cypher_bytes;
127 dst += subsample.cypher_bytes;
131 // Decrypts |input| using |key|. Returns a DecoderBuffer with the decrypted
132 // data if decryption succeeded or NULL if decryption failed.
133 static scoped_refptr<DecoderBuffer> DecryptData(const DecoderBuffer& input,
134 crypto::SymmetricKey* key) {
135 CHECK(input.data_size());
136 CHECK(input.decrypt_config());
137 CHECK(key);
139 crypto::Encryptor encryptor;
140 if (!encryptor.Init(key, crypto::Encryptor::CTR, "")) {
141 DVLOG(1) << "Could not initialize decryptor.";
142 return NULL;
145 DCHECK_EQ(input.decrypt_config()->iv().size(),
146 static_cast<size_t>(DecryptConfig::kDecryptionKeySize));
147 if (!encryptor.SetCounter(input.decrypt_config()->iv())) {
148 DVLOG(1) << "Could not set counter block.";
149 return NULL;
152 const char* sample = reinterpret_cast<const char*>(input.data());
153 size_t sample_size = static_cast<size_t>(input.data_size());
155 DCHECK_GT(sample_size, 0U) << "No sample data to be decrypted.";
156 if (sample_size == 0)
157 return NULL;
159 if (input.decrypt_config()->subsamples().empty()) {
160 std::string decrypted_text;
161 base::StringPiece encrypted_text(sample, sample_size);
162 if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) {
163 DVLOG(1) << "Could not decrypt data.";
164 return NULL;
167 // TODO(xhwang): Find a way to avoid this data copy.
168 return DecoderBuffer::CopyFrom(
169 reinterpret_cast<const uint8*>(decrypted_text.data()),
170 decrypted_text.size());
173 const std::vector<SubsampleEntry>& subsamples =
174 input.decrypt_config()->subsamples();
176 size_t total_clear_size = 0;
177 size_t total_encrypted_size = 0;
178 for (size_t i = 0; i < subsamples.size(); i++) {
179 total_clear_size += subsamples[i].clear_bytes;
180 total_encrypted_size += subsamples[i].cypher_bytes;
181 // Check for overflow. This check is valid because *_size is unsigned.
182 DCHECK(total_clear_size >= subsamples[i].clear_bytes);
183 if (total_encrypted_size < subsamples[i].cypher_bytes)
184 return NULL;
186 size_t total_size = total_clear_size + total_encrypted_size;
187 if (total_size < total_clear_size || total_size != sample_size) {
188 DVLOG(1) << "Subsample sizes do not equal input size";
189 return NULL;
192 // No need to decrypt if there is no encrypted data.
193 if (total_encrypted_size <= 0) {
194 return DecoderBuffer::CopyFrom(reinterpret_cast<const uint8*>(sample),
195 sample_size);
198 // The encrypted portions of all subsamples must form a contiguous block,
199 // such that an encrypted subsample that ends away from a block boundary is
200 // immediately followed by the start of the next encrypted subsample. We
201 // copy all encrypted subsamples to a contiguous buffer, decrypt them, then
202 // copy the decrypted bytes over the encrypted bytes in the output.
203 // TODO(strobe): attempt to reduce number of memory copies
204 scoped_ptr<uint8[]> encrypted_bytes(new uint8[total_encrypted_size]);
205 CopySubsamples(subsamples, kSrcContainsClearBytes,
206 reinterpret_cast<const uint8*>(sample), encrypted_bytes.get());
208 base::StringPiece encrypted_text(
209 reinterpret_cast<const char*>(encrypted_bytes.get()),
210 total_encrypted_size);
211 std::string decrypted_text;
212 if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) {
213 DVLOG(1) << "Could not decrypt data.";
214 return NULL;
216 DCHECK_EQ(decrypted_text.size(), encrypted_text.size());
218 scoped_refptr<DecoderBuffer> output = DecoderBuffer::CopyFrom(
219 reinterpret_cast<const uint8*>(sample), sample_size);
220 CopySubsamples(subsamples, kDstContainsClearBytes,
221 reinterpret_cast<const uint8*>(decrypted_text.data()),
222 output->writable_data());
223 return output;
226 AesDecryptor::AesDecryptor(const SessionMessageCB& session_message_cb,
227 const SessionClosedCB& session_closed_cb,
228 const SessionKeysChangeCB& session_keys_change_cb)
229 : session_message_cb_(session_message_cb),
230 session_closed_cb_(session_closed_cb),
231 session_keys_change_cb_(session_keys_change_cb) {
232 DCHECK(!session_message_cb_.is_null());
233 DCHECK(!session_closed_cb_.is_null());
234 DCHECK(!session_keys_change_cb_.is_null());
237 AesDecryptor::~AesDecryptor() {
238 key_map_.clear();
241 void AesDecryptor::SetServerCertificate(const uint8* certificate_data,
242 int certificate_data_length,
243 scoped_ptr<SimpleCdmPromise> promise) {
244 promise->reject(
245 NOT_SUPPORTED_ERROR, 0, "SetServerCertificate() is not supported.");
248 void AesDecryptor::CreateSessionAndGenerateRequest(
249 SessionType session_type,
250 const std::string& init_data_type,
251 const uint8* init_data,
252 int init_data_length,
253 scoped_ptr<NewSessionCdmPromise> promise) {
254 std::string session_id(base::UintToString(next_session_id_++));
255 valid_sessions_.insert(session_id);
257 // For now, the AesDecryptor does not care about |init_data_type| or
258 // |session_type|; just resolve the promise and then fire a message event
259 // using the |init_data| as the key ID in the license request.
260 // TODO(jrummell): Validate |init_data_type| and |session_type|.
261 std::vector<uint8> message;
262 if (init_data && init_data_length)
263 CreateLicenseRequest(init_data, init_data_length, session_type, &message);
265 promise->resolve(session_id);
267 // No URL needed for license requests.
268 session_message_cb_.Run(session_id, LICENSE_REQUEST, message,
269 GURL::EmptyGURL());
272 void AesDecryptor::LoadSession(SessionType session_type,
273 const std::string& session_id,
274 scoped_ptr<NewSessionCdmPromise> promise) {
275 // TODO(xhwang): Change this to NOTREACHED() when blink checks for key systems
276 // that do not support loadSession. See http://crbug.com/342481
277 promise->reject(NOT_SUPPORTED_ERROR, 0, "LoadSession() is not supported.");
280 void AesDecryptor::UpdateSession(const std::string& session_id,
281 const uint8* response,
282 int response_length,
283 scoped_ptr<SimpleCdmPromise> promise) {
284 CHECK(response);
285 CHECK_GT(response_length, 0);
287 // TODO(jrummell): Convert back to a DCHECK once prefixed EME is removed.
288 if (valid_sessions_.find(session_id) == valid_sessions_.end()) {
289 promise->reject(INVALID_ACCESS_ERROR, 0, "Session does not exist.");
290 return;
293 std::string key_string(reinterpret_cast<const char*>(response),
294 response_length);
296 KeyIdAndKeyPairs keys;
297 SessionType session_type = MediaKeys::TEMPORARY_SESSION;
298 if (!ExtractKeysFromJWKSet(key_string, &keys, &session_type)) {
299 promise->reject(
300 INVALID_ACCESS_ERROR, 0, "Response is not a valid JSON Web Key Set.");
301 return;
304 // Make sure that at least one key was extracted.
305 if (keys.empty()) {
306 promise->reject(
307 INVALID_ACCESS_ERROR, 0, "Response does not contain any keys.");
308 return;
311 for (KeyIdAndKeyPairs::iterator it = keys.begin(); it != keys.end(); ++it) {
312 if (it->second.length() !=
313 static_cast<size_t>(DecryptConfig::kDecryptionKeySize)) {
314 DVLOG(1) << "Invalid key length: " << it->second.length();
315 promise->reject(INVALID_ACCESS_ERROR, 0, "Invalid key length.");
316 return;
318 if (!AddDecryptionKey(session_id, it->first, it->second)) {
319 promise->reject(INVALID_ACCESS_ERROR, 0, "Unable to add key.");
320 return;
325 base::AutoLock auto_lock(new_key_cb_lock_);
327 if (!new_audio_key_cb_.is_null())
328 new_audio_key_cb_.Run();
330 if (!new_video_key_cb_.is_null())
331 new_video_key_cb_.Run();
334 promise->resolve();
336 // Create the list of all available keys for this session.
337 CdmKeysInfo keys_info;
339 base::AutoLock auto_lock(key_map_lock_);
340 for (const auto& item : key_map_) {
341 if (item.second->Contains(session_id)) {
342 scoped_ptr<CdmKeyInformation> key_info(new CdmKeyInformation);
343 key_info->key_id.assign(item.first.begin(), item.first.end());
344 key_info->status = CdmKeyInformation::USABLE;
345 key_info->system_code = 0;
346 keys_info.push_back(key_info.release());
351 // Assume that at least 1 new key has been successfully added and thus
352 // sending true for |has_additional_usable_key|. http://crbug.com/448219.
353 session_keys_change_cb_.Run(session_id, true, keys_info.Pass());
356 void AesDecryptor::CloseSession(const std::string& session_id,
357 scoped_ptr<SimpleCdmPromise> promise) {
358 // Validate that this is a reference to an active session and then forget it.
359 std::set<std::string>::iterator it = valid_sessions_.find(session_id);
360 DCHECK(it != valid_sessions_.end());
362 valid_sessions_.erase(it);
364 // Close the session.
365 DeleteKeysForSession(session_id);
366 promise->resolve();
367 session_closed_cb_.Run(session_id);
370 void AesDecryptor::RemoveSession(const std::string& session_id,
371 scoped_ptr<SimpleCdmPromise> promise) {
372 // AesDecryptor doesn't keep any persistent data, so this should be
373 // NOT_REACHED().
374 // TODO(jrummell): Make sure persistent session types are rejected.
375 // http://crbug.com/384152.
377 // However, v0.1b calls to CancelKeyRequest() will call this, so close the
378 // session, if it exists.
379 // TODO(jrummell): Remove the close() call when prefixed EME is removed.
380 // http://crbug.com/249976.
381 if (valid_sessions_.find(session_id) != valid_sessions_.end()) {
382 CloseSession(session_id, promise.Pass());
383 return;
386 promise->reject(INVALID_ACCESS_ERROR, 0, "Session does not exist.");
389 CdmContext* AesDecryptor::GetCdmContext() {
390 return this;
393 Decryptor* AesDecryptor::GetDecryptor() {
394 return this;
397 #if defined(ENABLE_BROWSER_CDMS)
398 int AesDecryptor::GetCdmId() const {
399 return kInvalidCdmId;
401 #endif // defined(ENABLE_BROWSER_CDMS)
403 void AesDecryptor::RegisterNewKeyCB(StreamType stream_type,
404 const NewKeyCB& new_key_cb) {
405 base::AutoLock auto_lock(new_key_cb_lock_);
407 switch (stream_type) {
408 case kAudio:
409 new_audio_key_cb_ = new_key_cb;
410 break;
411 case kVideo:
412 new_video_key_cb_ = new_key_cb;
413 break;
414 default:
415 NOTREACHED();
419 void AesDecryptor::Decrypt(StreamType stream_type,
420 const scoped_refptr<DecoderBuffer>& encrypted,
421 const DecryptCB& decrypt_cb) {
422 CHECK(encrypted->decrypt_config());
424 scoped_refptr<DecoderBuffer> decrypted;
425 // An empty iv string signals that the frame is unencrypted.
426 if (encrypted->decrypt_config()->iv().empty()) {
427 decrypted = DecoderBuffer::CopyFrom(encrypted->data(),
428 encrypted->data_size());
429 } else {
430 const std::string& key_id = encrypted->decrypt_config()->key_id();
431 DecryptionKey* key = GetKey(key_id);
432 if (!key) {
433 DVLOG(1) << "Could not find a matching key for the given key ID.";
434 decrypt_cb.Run(kNoKey, NULL);
435 return;
438 crypto::SymmetricKey* decryption_key = key->decryption_key();
439 decrypted = DecryptData(*encrypted.get(), decryption_key);
440 if (!decrypted.get()) {
441 DVLOG(1) << "Decryption failed.";
442 decrypt_cb.Run(kError, NULL);
443 return;
447 decrypted->set_timestamp(encrypted->timestamp());
448 decrypted->set_duration(encrypted->duration());
449 decrypt_cb.Run(kSuccess, decrypted);
452 void AesDecryptor::CancelDecrypt(StreamType stream_type) {
453 // Decrypt() calls the DecryptCB synchronously so there's nothing to cancel.
456 void AesDecryptor::InitializeAudioDecoder(const AudioDecoderConfig& config,
457 const DecoderInitCB& init_cb) {
458 // AesDecryptor does not support audio decoding.
459 init_cb.Run(false);
462 void AesDecryptor::InitializeVideoDecoder(const VideoDecoderConfig& config,
463 const DecoderInitCB& init_cb) {
464 // AesDecryptor does not support video decoding.
465 init_cb.Run(false);
468 void AesDecryptor::DecryptAndDecodeAudio(
469 const scoped_refptr<DecoderBuffer>& encrypted,
470 const AudioDecodeCB& audio_decode_cb) {
471 NOTREACHED() << "AesDecryptor does not support audio decoding";
474 void AesDecryptor::DecryptAndDecodeVideo(
475 const scoped_refptr<DecoderBuffer>& encrypted,
476 const VideoDecodeCB& video_decode_cb) {
477 NOTREACHED() << "AesDecryptor does not support video decoding";
480 void AesDecryptor::ResetDecoder(StreamType stream_type) {
481 NOTREACHED() << "AesDecryptor does not support audio/video decoding";
484 void AesDecryptor::DeinitializeDecoder(StreamType stream_type) {
485 NOTREACHED() << "AesDecryptor does not support audio/video decoding";
488 bool AesDecryptor::AddDecryptionKey(const std::string& session_id,
489 const std::string& key_id,
490 const std::string& key_string) {
491 scoped_ptr<DecryptionKey> decryption_key(new DecryptionKey(key_string));
492 if (!decryption_key->Init()) {
493 DVLOG(1) << "Could not initialize decryption key.";
494 return false;
497 base::AutoLock auto_lock(key_map_lock_);
498 KeyIdToSessionKeysMap::iterator key_id_entry = key_map_.find(key_id);
499 if (key_id_entry != key_map_.end()) {
500 key_id_entry->second->Insert(session_id, decryption_key.Pass());
501 return true;
504 // |key_id| not found, so need to create new entry.
505 scoped_ptr<SessionIdDecryptionKeyMap> inner_map(
506 new SessionIdDecryptionKeyMap());
507 inner_map->Insert(session_id, decryption_key.Pass());
508 key_map_.add(key_id, inner_map.Pass());
509 return true;
512 AesDecryptor::DecryptionKey* AesDecryptor::GetKey(
513 const std::string& key_id) const {
514 base::AutoLock auto_lock(key_map_lock_);
515 KeyIdToSessionKeysMap::const_iterator key_id_found = key_map_.find(key_id);
516 if (key_id_found == key_map_.end())
517 return NULL;
519 // Return the key from the "latest" session_id entry.
520 return key_id_found->second->LatestDecryptionKey();
523 void AesDecryptor::DeleteKeysForSession(const std::string& session_id) {
524 base::AutoLock auto_lock(key_map_lock_);
526 // Remove all keys associated with |session_id|. Since the data is
527 // optimized for access in GetKey(), we need to look at each entry in
528 // |key_map_|.
529 KeyIdToSessionKeysMap::iterator it = key_map_.begin();
530 while (it != key_map_.end()) {
531 it->second->Erase(session_id);
532 if (it->second->Empty()) {
533 // Need to get rid of the entry for this key_id. This will mess up the
534 // iterator, so we need to increment it first.
535 KeyIdToSessionKeysMap::iterator current = it;
536 ++it;
537 key_map_.erase(current);
538 } else {
539 ++it;
544 AesDecryptor::DecryptionKey::DecryptionKey(const std::string& secret)
545 : secret_(secret) {
548 AesDecryptor::DecryptionKey::~DecryptionKey() {}
550 bool AesDecryptor::DecryptionKey::Init() {
551 CHECK(!secret_.empty());
552 decryption_key_.reset(crypto::SymmetricKey::Import(
553 crypto::SymmetricKey::AES, secret_));
554 if (!decryption_key_)
555 return false;
556 return true;
559 } // namespace media