Implement MoveFileLocal (with creating a snapshot).
[chromium-blink-merge.git] / media / cdm / aes_decryptor.cc
blob1506f7fc32b2b9f736837fdf659f995fd8d96ce0
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/cenc_utils.h"
23 #include "media/cdm/json_web_key.h"
25 namespace media {
27 // Keeps track of the session IDs and DecryptionKeys. The keys are ordered by
28 // insertion time (last insertion is first). It takes ownership of the
29 // DecryptionKeys.
30 class AesDecryptor::SessionIdDecryptionKeyMap {
31 // Use a std::list to actually hold the data. Insertion is always done
32 // at the front, so the "latest" decryption key is always the first one
33 // in the list.
34 typedef std::list<std::pair<std::string, DecryptionKey*> > KeyList;
36 public:
37 SessionIdDecryptionKeyMap() {}
38 ~SessionIdDecryptionKeyMap() { STLDeleteValues(&key_list_); }
40 // Replaces value if |session_id| is already present, or adds it if not.
41 // This |decryption_key| becomes the latest until another insertion or
42 // |session_id| is erased.
43 void Insert(const std::string& session_id,
44 scoped_ptr<DecryptionKey> decryption_key);
46 // Deletes the entry for |session_id| if present.
47 void Erase(const std::string& session_id);
49 // Returns whether the list is empty
50 bool Empty() const { return key_list_.empty(); }
52 // Returns the last inserted DecryptionKey.
53 DecryptionKey* LatestDecryptionKey() {
54 DCHECK(!key_list_.empty());
55 return key_list_.begin()->second;
58 bool Contains(const std::string& session_id) {
59 return Find(session_id) != key_list_.end();
62 private:
63 // Searches the list for an element with |session_id|.
64 KeyList::iterator Find(const std::string& session_id);
66 // Deletes the entry pointed to by |position|.
67 void Erase(KeyList::iterator position);
69 KeyList key_list_;
71 DISALLOW_COPY_AND_ASSIGN(SessionIdDecryptionKeyMap);
74 void AesDecryptor::SessionIdDecryptionKeyMap::Insert(
75 const std::string& session_id,
76 scoped_ptr<DecryptionKey> decryption_key) {
77 KeyList::iterator it = Find(session_id);
78 if (it != key_list_.end())
79 Erase(it);
80 DecryptionKey* raw_ptr = decryption_key.release();
81 key_list_.push_front(std::make_pair(session_id, raw_ptr));
84 void AesDecryptor::SessionIdDecryptionKeyMap::Erase(
85 const std::string& session_id) {
86 KeyList::iterator it = Find(session_id);
87 if (it == key_list_.end())
88 return;
89 Erase(it);
92 AesDecryptor::SessionIdDecryptionKeyMap::KeyList::iterator
93 AesDecryptor::SessionIdDecryptionKeyMap::Find(const std::string& session_id) {
94 for (KeyList::iterator it = key_list_.begin(); it != key_list_.end(); ++it) {
95 if (it->first == session_id)
96 return it;
98 return key_list_.end();
101 void AesDecryptor::SessionIdDecryptionKeyMap::Erase(
102 KeyList::iterator position) {
103 DCHECK(position->second);
104 delete position->second;
105 key_list_.erase(position);
108 uint32 AesDecryptor::next_session_id_ = 1;
110 enum ClearBytesBufferSel {
111 kSrcContainsClearBytes,
112 kDstContainsClearBytes
115 static void CopySubsamples(const std::vector<SubsampleEntry>& subsamples,
116 const ClearBytesBufferSel sel,
117 const uint8* src,
118 uint8* dst) {
119 for (size_t i = 0; i < subsamples.size(); i++) {
120 const SubsampleEntry& subsample = subsamples[i];
121 if (sel == kSrcContainsClearBytes) {
122 src += subsample.clear_bytes;
123 } else {
124 dst += subsample.clear_bytes;
126 memcpy(dst, src, subsample.cypher_bytes);
127 src += subsample.cypher_bytes;
128 dst += subsample.cypher_bytes;
132 // Decrypts |input| using |key|. Returns a DecoderBuffer with the decrypted
133 // data if decryption succeeded or NULL if decryption failed.
134 static scoped_refptr<DecoderBuffer> DecryptData(const DecoderBuffer& input,
135 crypto::SymmetricKey* key) {
136 CHECK(input.data_size());
137 CHECK(input.decrypt_config());
138 CHECK(key);
140 crypto::Encryptor encryptor;
141 if (!encryptor.Init(key, crypto::Encryptor::CTR, "")) {
142 DVLOG(1) << "Could not initialize decryptor.";
143 return NULL;
146 DCHECK_EQ(input.decrypt_config()->iv().size(),
147 static_cast<size_t>(DecryptConfig::kDecryptionKeySize));
148 if (!encryptor.SetCounter(input.decrypt_config()->iv())) {
149 DVLOG(1) << "Could not set counter block.";
150 return NULL;
153 const char* sample = reinterpret_cast<const char*>(input.data());
154 size_t sample_size = static_cast<size_t>(input.data_size());
156 DCHECK_GT(sample_size, 0U) << "No sample data to be decrypted.";
157 if (sample_size == 0)
158 return NULL;
160 if (input.decrypt_config()->subsamples().empty()) {
161 std::string decrypted_text;
162 base::StringPiece encrypted_text(sample, sample_size);
163 if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) {
164 DVLOG(1) << "Could not decrypt data.";
165 return NULL;
168 // TODO(xhwang): Find a way to avoid this data copy.
169 return DecoderBuffer::CopyFrom(
170 reinterpret_cast<const uint8*>(decrypted_text.data()),
171 decrypted_text.size());
174 const std::vector<SubsampleEntry>& subsamples =
175 input.decrypt_config()->subsamples();
177 size_t total_clear_size = 0;
178 size_t total_encrypted_size = 0;
179 for (size_t i = 0; i < subsamples.size(); i++) {
180 total_clear_size += subsamples[i].clear_bytes;
181 total_encrypted_size += subsamples[i].cypher_bytes;
182 // Check for overflow. This check is valid because *_size is unsigned.
183 DCHECK(total_clear_size >= subsamples[i].clear_bytes);
184 if (total_encrypted_size < subsamples[i].cypher_bytes)
185 return NULL;
187 size_t total_size = total_clear_size + total_encrypted_size;
188 if (total_size < total_clear_size || total_size != sample_size) {
189 DVLOG(1) << "Subsample sizes do not equal input size";
190 return NULL;
193 // No need to decrypt if there is no encrypted data.
194 if (total_encrypted_size <= 0) {
195 return DecoderBuffer::CopyFrom(reinterpret_cast<const uint8*>(sample),
196 sample_size);
199 // The encrypted portions of all subsamples must form a contiguous block,
200 // such that an encrypted subsample that ends away from a block boundary is
201 // immediately followed by the start of the next encrypted subsample. We
202 // copy all encrypted subsamples to a contiguous buffer, decrypt them, then
203 // copy the decrypted bytes over the encrypted bytes in the output.
204 // TODO(strobe): attempt to reduce number of memory copies
205 scoped_ptr<uint8[]> encrypted_bytes(new uint8[total_encrypted_size]);
206 CopySubsamples(subsamples, kSrcContainsClearBytes,
207 reinterpret_cast<const uint8*>(sample), encrypted_bytes.get());
209 base::StringPiece encrypted_text(
210 reinterpret_cast<const char*>(encrypted_bytes.get()),
211 total_encrypted_size);
212 std::string decrypted_text;
213 if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) {
214 DVLOG(1) << "Could not decrypt data.";
215 return NULL;
217 DCHECK_EQ(decrypted_text.size(), encrypted_text.size());
219 scoped_refptr<DecoderBuffer> output = DecoderBuffer::CopyFrom(
220 reinterpret_cast<const uint8*>(sample), sample_size);
221 CopySubsamples(subsamples, kDstContainsClearBytes,
222 reinterpret_cast<const uint8*>(decrypted_text.data()),
223 output->writable_data());
224 return output;
227 AesDecryptor::AesDecryptor(const SessionMessageCB& session_message_cb,
228 const SessionClosedCB& session_closed_cb,
229 const SessionKeysChangeCB& session_keys_change_cb)
230 : session_message_cb_(session_message_cb),
231 session_closed_cb_(session_closed_cb),
232 session_keys_change_cb_(session_keys_change_cb) {
233 DCHECK(!session_message_cb_.is_null());
234 DCHECK(!session_closed_cb_.is_null());
235 DCHECK(!session_keys_change_cb_.is_null());
238 AesDecryptor::~AesDecryptor() {
239 key_map_.clear();
242 void AesDecryptor::SetServerCertificate(const uint8* certificate_data,
243 int certificate_data_length,
244 scoped_ptr<SimpleCdmPromise> promise) {
245 promise->reject(
246 NOT_SUPPORTED_ERROR, 0, "SetServerCertificate() is not supported.");
249 void AesDecryptor::CreateSessionAndGenerateRequest(
250 SessionType session_type,
251 const std::string& init_data_type,
252 const uint8* init_data,
253 int init_data_length,
254 scoped_ptr<NewSessionCdmPromise> promise) {
255 std::string session_id(base::UintToString(next_session_id_++));
256 valid_sessions_.insert(session_id);
258 // For now, the AesDecryptor does not care about |session_type|.
259 // TODO(jrummell): Validate |session_type|.
261 std::vector<uint8> message;
262 // TODO(jrummell): Since unprefixed will never send NULL, remove this check
263 // when prefixed EME is removed (http://crbug.com/249976).
264 if (init_data && init_data_length) {
265 std::vector<std::vector<uint8>> keys;
266 if (init_data_type == "webm") {
267 // |init_data| is simply the key needed.
268 keys.push_back(
269 std::vector<uint8>(init_data, init_data + init_data_length));
270 } else if (init_data_type == "cenc") {
271 // |init_data| is a set of 0 or more concatenated 'pssh' boxes.
272 if (!GetKeyIdsForCommonSystemId(init_data, init_data_length, &keys)) {
273 promise->reject(NOT_SUPPORTED_ERROR, 0, "No supported PSSH box found.");
274 return;
276 } else if (init_data_type == "keyids") {
277 std::string init_data_string(init_data, init_data + init_data_length);
278 std::string error_message;
279 if (!ExtractKeyIdsFromKeyIdsInitData(init_data_string, &keys,
280 &error_message)) {
281 promise->reject(NOT_SUPPORTED_ERROR, 0, error_message);
282 return;
284 } else {
285 promise->reject(NOT_SUPPORTED_ERROR, 0, "init_data_type not supported.");
286 return;
288 CreateLicenseRequest(keys, session_type, &message);
291 promise->resolve(session_id);
293 // No URL needed for license requests.
294 session_message_cb_.Run(session_id, LICENSE_REQUEST, message,
295 GURL::EmptyGURL());
298 void AesDecryptor::LoadSession(SessionType session_type,
299 const std::string& session_id,
300 scoped_ptr<NewSessionCdmPromise> promise) {
301 // TODO(xhwang): Change this to NOTREACHED() when blink checks for key systems
302 // that do not support loadSession. See http://crbug.com/342481
303 promise->reject(NOT_SUPPORTED_ERROR, 0, "LoadSession() is not supported.");
306 void AesDecryptor::UpdateSession(const std::string& session_id,
307 const uint8* response,
308 int response_length,
309 scoped_ptr<SimpleCdmPromise> promise) {
310 CHECK(response);
311 CHECK_GT(response_length, 0);
313 // TODO(jrummell): Convert back to a DCHECK once prefixed EME is removed.
314 if (valid_sessions_.find(session_id) == valid_sessions_.end()) {
315 promise->reject(INVALID_ACCESS_ERROR, 0, "Session does not exist.");
316 return;
319 std::string key_string(reinterpret_cast<const char*>(response),
320 response_length);
322 KeyIdAndKeyPairs keys;
323 SessionType session_type = MediaKeys::TEMPORARY_SESSION;
324 if (!ExtractKeysFromJWKSet(key_string, &keys, &session_type)) {
325 promise->reject(
326 INVALID_ACCESS_ERROR, 0, "Response is not a valid JSON Web Key Set.");
327 return;
330 // Make sure that at least one key was extracted.
331 if (keys.empty()) {
332 promise->reject(
333 INVALID_ACCESS_ERROR, 0, "Response does not contain any keys.");
334 return;
337 for (KeyIdAndKeyPairs::iterator it = keys.begin(); it != keys.end(); ++it) {
338 if (it->second.length() !=
339 static_cast<size_t>(DecryptConfig::kDecryptionKeySize)) {
340 DVLOG(1) << "Invalid key length: " << it->second.length();
341 promise->reject(INVALID_ACCESS_ERROR, 0, "Invalid key length.");
342 return;
344 if (!AddDecryptionKey(session_id, it->first, it->second)) {
345 promise->reject(INVALID_ACCESS_ERROR, 0, "Unable to add key.");
346 return;
351 base::AutoLock auto_lock(new_key_cb_lock_);
353 if (!new_audio_key_cb_.is_null())
354 new_audio_key_cb_.Run();
356 if (!new_video_key_cb_.is_null())
357 new_video_key_cb_.Run();
360 promise->resolve();
362 // Create the list of all available keys for this session.
363 CdmKeysInfo keys_info;
365 base::AutoLock auto_lock(key_map_lock_);
366 for (const auto& item : key_map_) {
367 if (item.second->Contains(session_id)) {
368 scoped_ptr<CdmKeyInformation> key_info(new CdmKeyInformation);
369 key_info->key_id.assign(item.first.begin(), item.first.end());
370 key_info->status = CdmKeyInformation::USABLE;
371 key_info->system_code = 0;
372 keys_info.push_back(key_info.release());
377 // Assume that at least 1 new key has been successfully added and thus
378 // sending true for |has_additional_usable_key|. http://crbug.com/448219.
379 session_keys_change_cb_.Run(session_id, true, keys_info.Pass());
382 void AesDecryptor::CloseSession(const std::string& session_id,
383 scoped_ptr<SimpleCdmPromise> promise) {
384 // Validate that this is a reference to an active session and then forget it.
385 std::set<std::string>::iterator it = valid_sessions_.find(session_id);
386 DCHECK(it != valid_sessions_.end());
388 valid_sessions_.erase(it);
390 // Close the session.
391 DeleteKeysForSession(session_id);
392 promise->resolve();
393 session_closed_cb_.Run(session_id);
396 void AesDecryptor::RemoveSession(const std::string& session_id,
397 scoped_ptr<SimpleCdmPromise> promise) {
398 // AesDecryptor doesn't keep any persistent data, so this should be
399 // NOT_REACHED().
400 // TODO(jrummell): Make sure persistent session types are rejected.
401 // http://crbug.com/384152.
403 // However, v0.1b calls to CancelKeyRequest() will call this, so close the
404 // session, if it exists.
405 // TODO(jrummell): Remove the close() call when prefixed EME is removed.
406 // http://crbug.com/249976.
407 if (valid_sessions_.find(session_id) != valid_sessions_.end()) {
408 CloseSession(session_id, promise.Pass());
409 return;
412 promise->reject(INVALID_ACCESS_ERROR, 0, "Session does not exist.");
415 CdmContext* AesDecryptor::GetCdmContext() {
416 return this;
419 Decryptor* AesDecryptor::GetDecryptor() {
420 return this;
423 #if defined(ENABLE_BROWSER_CDMS)
424 int AesDecryptor::GetCdmId() const {
425 return kInvalidCdmId;
427 #endif // defined(ENABLE_BROWSER_CDMS)
429 void AesDecryptor::RegisterNewKeyCB(StreamType stream_type,
430 const NewKeyCB& new_key_cb) {
431 base::AutoLock auto_lock(new_key_cb_lock_);
433 switch (stream_type) {
434 case kAudio:
435 new_audio_key_cb_ = new_key_cb;
436 break;
437 case kVideo:
438 new_video_key_cb_ = new_key_cb;
439 break;
440 default:
441 NOTREACHED();
445 void AesDecryptor::Decrypt(StreamType stream_type,
446 const scoped_refptr<DecoderBuffer>& encrypted,
447 const DecryptCB& decrypt_cb) {
448 CHECK(encrypted->decrypt_config());
450 scoped_refptr<DecoderBuffer> decrypted;
451 // An empty iv string signals that the frame is unencrypted.
452 if (encrypted->decrypt_config()->iv().empty()) {
453 decrypted = DecoderBuffer::CopyFrom(encrypted->data(),
454 encrypted->data_size());
455 } else {
456 const std::string& key_id = encrypted->decrypt_config()->key_id();
457 DecryptionKey* key = GetKey(key_id);
458 if (!key) {
459 DVLOG(1) << "Could not find a matching key for the given key ID.";
460 decrypt_cb.Run(kNoKey, NULL);
461 return;
464 crypto::SymmetricKey* decryption_key = key->decryption_key();
465 decrypted = DecryptData(*encrypted.get(), decryption_key);
466 if (!decrypted.get()) {
467 DVLOG(1) << "Decryption failed.";
468 decrypt_cb.Run(kError, NULL);
469 return;
473 decrypted->set_timestamp(encrypted->timestamp());
474 decrypted->set_duration(encrypted->duration());
475 decrypt_cb.Run(kSuccess, decrypted);
478 void AesDecryptor::CancelDecrypt(StreamType stream_type) {
479 // Decrypt() calls the DecryptCB synchronously so there's nothing to cancel.
482 void AesDecryptor::InitializeAudioDecoder(const AudioDecoderConfig& config,
483 const DecoderInitCB& init_cb) {
484 // AesDecryptor does not support audio decoding.
485 init_cb.Run(false);
488 void AesDecryptor::InitializeVideoDecoder(const VideoDecoderConfig& config,
489 const DecoderInitCB& init_cb) {
490 // AesDecryptor does not support video decoding.
491 init_cb.Run(false);
494 void AesDecryptor::DecryptAndDecodeAudio(
495 const scoped_refptr<DecoderBuffer>& encrypted,
496 const AudioDecodeCB& audio_decode_cb) {
497 NOTREACHED() << "AesDecryptor does not support audio decoding";
500 void AesDecryptor::DecryptAndDecodeVideo(
501 const scoped_refptr<DecoderBuffer>& encrypted,
502 const VideoDecodeCB& video_decode_cb) {
503 NOTREACHED() << "AesDecryptor does not support video decoding";
506 void AesDecryptor::ResetDecoder(StreamType stream_type) {
507 NOTREACHED() << "AesDecryptor does not support audio/video decoding";
510 void AesDecryptor::DeinitializeDecoder(StreamType stream_type) {
511 NOTREACHED() << "AesDecryptor does not support audio/video decoding";
514 bool AesDecryptor::AddDecryptionKey(const std::string& session_id,
515 const std::string& key_id,
516 const std::string& key_string) {
517 scoped_ptr<DecryptionKey> decryption_key(new DecryptionKey(key_string));
518 if (!decryption_key->Init()) {
519 DVLOG(1) << "Could not initialize decryption key.";
520 return false;
523 base::AutoLock auto_lock(key_map_lock_);
524 KeyIdToSessionKeysMap::iterator key_id_entry = key_map_.find(key_id);
525 if (key_id_entry != key_map_.end()) {
526 key_id_entry->second->Insert(session_id, decryption_key.Pass());
527 return true;
530 // |key_id| not found, so need to create new entry.
531 scoped_ptr<SessionIdDecryptionKeyMap> inner_map(
532 new SessionIdDecryptionKeyMap());
533 inner_map->Insert(session_id, decryption_key.Pass());
534 key_map_.add(key_id, inner_map.Pass());
535 return true;
538 AesDecryptor::DecryptionKey* AesDecryptor::GetKey(
539 const std::string& key_id) const {
540 base::AutoLock auto_lock(key_map_lock_);
541 KeyIdToSessionKeysMap::const_iterator key_id_found = key_map_.find(key_id);
542 if (key_id_found == key_map_.end())
543 return NULL;
545 // Return the key from the "latest" session_id entry.
546 return key_id_found->second->LatestDecryptionKey();
549 void AesDecryptor::DeleteKeysForSession(const std::string& session_id) {
550 base::AutoLock auto_lock(key_map_lock_);
552 // Remove all keys associated with |session_id|. Since the data is
553 // optimized for access in GetKey(), we need to look at each entry in
554 // |key_map_|.
555 KeyIdToSessionKeysMap::iterator it = key_map_.begin();
556 while (it != key_map_.end()) {
557 it->second->Erase(session_id);
558 if (it->second->Empty()) {
559 // Need to get rid of the entry for this key_id. This will mess up the
560 // iterator, so we need to increment it first.
561 KeyIdToSessionKeysMap::iterator current = it;
562 ++it;
563 key_map_.erase(current);
564 } else {
565 ++it;
570 AesDecryptor::DecryptionKey::DecryptionKey(const std::string& secret)
571 : secret_(secret) {
574 AesDecryptor::DecryptionKey::~DecryptionKey() {}
576 bool AesDecryptor::DecryptionKey::Init() {
577 CHECK(!secret_.empty());
578 decryption_key_.reset(crypto::SymmetricKey::Import(
579 crypto::SymmetricKey::AES, secret_));
580 if (!decryption_key_)
581 return false;
582 return true;
585 } // namespace media