DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
widevine_key_source.cc
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/media/base/widevine_key_source.h"
8 
9 #include "packager/base/base64.h"
10 #include "packager/base/bind.h"
11 #include "packager/base/json/json_reader.h"
12 #include "packager/base/json/json_writer.h"
13 #include "packager/base/memory/ref_counted.h"
14 #include "packager/base/stl_util.h"
15 #include "packager/media/base/http_key_fetcher.h"
16 #include "packager/media/base/producer_consumer_queue.h"
17 #include "packager/media/base/request_signer.h"
18 
19 #define RCHECK(x) \
20  do { \
21  if (!(x)) { \
22  LOG(ERROR) << "Failure while processing: " << #x; \
23  return false; \
24  } \
25  } while (0)
26 
27 namespace edash_packager {
28 namespace {
29 
30 const bool kEnableKeyRotation = true;
31 
32 const char kLicenseStatusOK[] = "OK";
33 // Server may return INTERNAL_ERROR intermittently, which is a transient error
34 // and the next client request may succeed without problem.
35 const char kLicenseStatusTransientError[] = "INTERNAL_ERROR";
36 
37 // Number of times to retry requesting keys in case of a transient error from
38 // the server.
39 const int kNumTransientErrorRetries = 5;
40 const int kFirstRetryDelayMilliseconds = 1000;
41 
42 // Default crypto period count, which is the number of keys to fetch on every
43 // key rotation enabled request.
44 const int kDefaultCryptoPeriodCount = 10;
45 const int kGetKeyTimeoutInSeconds = 5 * 60; // 5 minutes.
46 const int kKeyFetchTimeoutInSeconds = 60; // 1 minute.
47 
48 bool Base64StringToBytes(const std::string& base64_string,
49  std::vector<uint8_t>* bytes) {
50  DCHECK(bytes);
51  std::string str;
52  if (!base::Base64Decode(base64_string, &str))
53  return false;
54  bytes->assign(str.begin(), str.end());
55  return true;
56 }
57 
58 void BytesToBase64String(const std::vector<uint8_t>& bytes,
59  std::string* base64_string) {
60  DCHECK(base64_string);
61  base::Base64Encode(base::StringPiece(reinterpret_cast<const char*>
62  (bytes.data()), bytes.size()),
63  base64_string);
64 }
65 
66 bool GetKeyFromTrack(const base::DictionaryValue& track_dict,
67  std::vector<uint8_t>* key) {
68  DCHECK(key);
69  std::string key_base64_string;
70  RCHECK(track_dict.GetString("key", &key_base64_string));
71  VLOG(2) << "Key:" << key_base64_string;
72  RCHECK(Base64StringToBytes(key_base64_string, key));
73  return true;
74 }
75 
76 bool GetKeyIdFromTrack(const base::DictionaryValue& track_dict,
77  std::vector<uint8_t>* key_id) {
78  DCHECK(key_id);
79  std::string key_id_base64_string;
80  RCHECK(track_dict.GetString("key_id", &key_id_base64_string));
81  VLOG(2) << "Keyid:" << key_id_base64_string;
82  RCHECK(Base64StringToBytes(key_id_base64_string, key_id));
83  return true;
84 }
85 
86 bool GetPsshDataFromTrack(const base::DictionaryValue& track_dict,
87  std::vector<uint8_t>* pssh_data) {
88  DCHECK(pssh_data);
89 
90  const base::ListValue* pssh_list;
91  RCHECK(track_dict.GetList("pssh", &pssh_list));
92  // Invariant check. We don't want to crash in release mode if possible.
93  // The following code handles it gracefully if GetSize() does not return 1.
94  DCHECK_EQ(1u, pssh_list->GetSize());
95 
96  const base::DictionaryValue* pssh_dict;
97  RCHECK(pssh_list->GetDictionary(0, &pssh_dict));
98  std::string drm_type;
99  RCHECK(pssh_dict->GetString("drm_type", &drm_type));
100  if (drm_type != "WIDEVINE") {
101  LOG(ERROR) << "Expecting drm_type 'WIDEVINE', get '" << drm_type << "'.";
102  return false;
103  }
104  std::string pssh_data_base64_string;
105  RCHECK(pssh_dict->GetString("data", &pssh_data_base64_string));
106 
107  VLOG(2) << "Pssh Data:" << pssh_data_base64_string;
108  RCHECK(Base64StringToBytes(pssh_data_base64_string, pssh_data));
109  return true;
110 }
111 
112 } // namespace
113 
114 namespace media {
115 
116 // A ref counted wrapper for EncryptionKeyMap.
117 class WidevineKeySource::RefCountedEncryptionKeyMap
118  : public base::RefCountedThreadSafe<RefCountedEncryptionKeyMap> {
119  public:
120  explicit RefCountedEncryptionKeyMap(EncryptionKeyMap* encryption_key_map) {
121  DCHECK(encryption_key_map);
122  encryption_key_map_.swap(*encryption_key_map);
123  }
124 
125  std::map<KeySource::TrackType, EncryptionKey*>& map() {
126  return encryption_key_map_;
127  }
128 
129  private:
130  friend class base::RefCountedThreadSafe<RefCountedEncryptionKeyMap>;
131 
132  ~RefCountedEncryptionKeyMap() { STLDeleteValues(&encryption_key_map_); }
133 
134  EncryptionKeyMap encryption_key_map_;
135 
136  DISALLOW_COPY_AND_ASSIGN(RefCountedEncryptionKeyMap);
137 };
138 
139 WidevineKeySource::WidevineKeySource(const std::string& server_url)
140  : key_production_thread_("KeyProductionThread",
141  base::Bind(&WidevineKeySource::FetchKeysTask,
142  base::Unretained(this))),
143  key_fetcher_(new HttpKeyFetcher(kKeyFetchTimeoutInSeconds)),
144  server_url_(server_url),
145  crypto_period_count_(kDefaultCryptoPeriodCount),
146  key_production_started_(false),
147  start_key_production_(false, false),
148  first_crypto_period_index_(0) {
149  key_production_thread_.Start();
150 }
151 
152 WidevineKeySource::~WidevineKeySource() {
153  if (key_pool_)
154  key_pool_->Stop();
155  if (key_production_thread_.HasBeenStarted()) {
156  // Signal the production thread to start key production if it is not
157  // signaled yet so the thread can be joined.
158  start_key_production_.Signal();
159  key_production_thread_.Join();
160  }
161  STLDeleteValues(&encryption_key_map_);
162 }
163 
164 Status WidevineKeySource::FetchKeys(const std::vector<uint8_t>& content_id,
165  const std::string& policy) {
166  base::AutoLock scoped_lock(lock_);
167  request_dict_.Clear();
168  std::string content_id_base64_string;
169  BytesToBase64String(content_id, &content_id_base64_string);
170  request_dict_.SetString("content_id", content_id_base64_string);
171  request_dict_.SetString("policy", policy);
172  return FetchKeysInternal(!kEnableKeyRotation, 0, false);
173 }
174 
175 Status WidevineKeySource::FetchKeys(const std::vector<uint8_t>& pssh_data) {
176  base::AutoLock scoped_lock(lock_);
177  request_dict_.Clear();
178  std::string pssh_data_base64_string;
179  BytesToBase64String(pssh_data, &pssh_data_base64_string);
180  request_dict_.SetString("pssh_data", pssh_data_base64_string);
181  return FetchKeysInternal(!kEnableKeyRotation, 0, false);
182 }
183 
185  base::AutoLock scoped_lock(lock_);
186  request_dict_.Clear();
187  request_dict_.SetInteger("asset_id", asset_id);
188  return FetchKeysInternal(!kEnableKeyRotation, 0, true);
189 }
190 
191 Status WidevineKeySource::GetKey(TrackType track_type, EncryptionKey* key) {
192  DCHECK(key);
193  if (encryption_key_map_.find(track_type) == encryption_key_map_.end()) {
194  return Status(error::INTERNAL_ERROR,
195  "Cannot find key of type " + TrackTypeToString(track_type));
196  }
197  *key = *encryption_key_map_[track_type];
198  return Status::OK;
199 }
200 
201 Status WidevineKeySource::GetKey(const std::vector<uint8_t>& key_id,
202  EncryptionKey* key) {
203  DCHECK(key);
204  for (std::map<TrackType, EncryptionKey*>::iterator iter =
205  encryption_key_map_.begin();
206  iter != encryption_key_map_.end();
207  ++iter) {
208  if (iter->second->key_id == key_id) {
209  *key = *iter->second;
210  return Status::OK;
211  }
212  }
213  return Status(error::INTERNAL_ERROR,
214  "Cannot find key with specified key ID");
215 }
216 
217 Status WidevineKeySource::GetCryptoPeriodKey(uint32_t crypto_period_index,
218  TrackType track_type,
219  EncryptionKey* key) {
220  DCHECK(key_production_thread_.HasBeenStarted());
221  // TODO(kqyang): This is not elegant. Consider refactoring later.
222  {
223  base::AutoLock scoped_lock(lock_);
224  if (!key_production_started_) {
225  // Another client may have a slightly smaller starting crypto period
226  // index. Set the initial value to account for that.
227  first_crypto_period_index_ =
228  crypto_period_index ? crypto_period_index - 1 : 0;
229  DCHECK(!key_pool_);
230  key_pool_.reset(new EncryptionKeyQueue(crypto_period_count_,
231  first_crypto_period_index_));
232  start_key_production_.Signal();
233  key_production_started_ = true;
234  }
235  }
236  return GetKeyInternal(crypto_period_index, track_type, key);
237 }
238 
239 std::string WidevineKeySource::UUID() {
240  return "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
241 }
242 
243 void WidevineKeySource::set_signer(scoped_ptr<RequestSigner> signer) {
244  signer_ = signer.Pass();
245 }
246 
247 void WidevineKeySource::set_key_fetcher(scoped_ptr<KeyFetcher> key_fetcher) {
248  key_fetcher_ = key_fetcher.Pass();
249 }
250 
251 Status WidevineKeySource::GetKeyInternal(uint32_t crypto_period_index,
252  TrackType track_type,
253  EncryptionKey* key) {
254  DCHECK(key_pool_);
255  DCHECK(key);
256  DCHECK_LE(track_type, NUM_VALID_TRACK_TYPES);
257  DCHECK_NE(track_type, TRACK_TYPE_UNKNOWN);
258 
259  scoped_refptr<RefCountedEncryptionKeyMap> ref_counted_encryption_key_map;
260  Status status =
261  key_pool_->Peek(crypto_period_index, &ref_counted_encryption_key_map,
262  kGetKeyTimeoutInSeconds * 1000);
263  if (!status.ok()) {
264  if (status.error_code() == error::STOPPED) {
265  CHECK(!common_encryption_request_status_.ok());
266  return common_encryption_request_status_;
267  }
268  return status;
269  }
270 
271  EncryptionKeyMap& encryption_key_map = ref_counted_encryption_key_map->map();
272  if (encryption_key_map.find(track_type) == encryption_key_map.end()) {
273  return Status(error::INTERNAL_ERROR,
274  "Cannot find key of type " + TrackTypeToString(track_type));
275  }
276  *key = *encryption_key_map[track_type];
277  return Status::OK;
278 }
279 
280 void WidevineKeySource::FetchKeysTask() {
281  // Wait until key production is signaled.
282  start_key_production_.Wait();
283  if (!key_pool_ || key_pool_->Stopped())
284  return;
285 
286  Status status = FetchKeysInternal(kEnableKeyRotation,
287  first_crypto_period_index_,
288  false);
289  while (status.ok()) {
290  first_crypto_period_index_ += crypto_period_count_;
291  status = FetchKeysInternal(kEnableKeyRotation,
292  first_crypto_period_index_,
293  false);
294  }
295  common_encryption_request_status_ = status;
296  key_pool_->Stop();
297 }
298 
299 Status WidevineKeySource::FetchKeysInternal(bool enable_key_rotation,
300  uint32_t first_crypto_period_index,
301  bool widevine_classic) {
302  std::string request;
303  FillRequest(enable_key_rotation,
304  first_crypto_period_index,
305  &request);
306 
307  std::string message;
308  Status status = GenerateKeyMessage(request, &message);
309  if (!status.ok())
310  return status;
311  VLOG(1) << "Message: " << message;
312 
313  std::string raw_response;
314  int64_t sleep_duration = kFirstRetryDelayMilliseconds;
315 
316  // Perform client side retries if seeing server transient error to workaround
317  // server limitation.
318  for (int i = 0; i < kNumTransientErrorRetries; ++i) {
319  status = key_fetcher_->FetchKeys(server_url_, message, &raw_response);
320  if (status.ok()) {
321  VLOG(1) << "Retry [" << i << "] Response:" << raw_response;
322 
323  std::string response;
324  if (!DecodeResponse(raw_response, &response)) {
325  return Status(error::SERVER_ERROR,
326  "Failed to decode response '" + raw_response + "'.");
327  }
328 
329  bool transient_error = false;
330  if (ExtractEncryptionKey(enable_key_rotation,
331  widevine_classic,
332  response,
333  &transient_error))
334  return Status::OK;
335 
336  if (!transient_error) {
337  return Status(
338  error::SERVER_ERROR,
339  "Failed to extract encryption key from '" + response + "'.");
340  }
341  } else if (status.error_code() != error::TIME_OUT) {
342  return status;
343  }
344 
345  // Exponential backoff.
346  if (i != kNumTransientErrorRetries - 1) {
347  base::PlatformThread::Sleep(
348  base::TimeDelta::FromMilliseconds(sleep_duration));
349  sleep_duration *= 2;
350  }
351  }
352  return Status(error::SERVER_ERROR,
353  "Failed to recover from server internal error.");
354 }
355 
356 void WidevineKeySource::FillRequest(bool enable_key_rotation,
357  uint32_t first_crypto_period_index,
358  std::string* request) {
359  DCHECK(request);
360  DCHECK(!request_dict_.empty());
361 
362  // Build tracks.
363  base::ListValue* tracks = new base::ListValue();
364 
365  base::DictionaryValue* track_sd = new base::DictionaryValue();
366  track_sd->SetString("type", "SD");
367  tracks->Append(track_sd);
368  base::DictionaryValue* track_hd = new base::DictionaryValue();
369  track_hd->SetString("type", "HD");
370  tracks->Append(track_hd);
371  base::DictionaryValue* track_audio = new base::DictionaryValue();
372  track_audio->SetString("type", "AUDIO");
373  tracks->Append(track_audio);
374 
375  request_dict_.Set("tracks", tracks);
376 
377  // Build DRM types.
378  base::ListValue* drm_types = new base::ListValue();
379  drm_types->AppendString("WIDEVINE");
380  request_dict_.Set("drm_types", drm_types);
381 
382  // Build key rotation fields.
383  if (enable_key_rotation) {
384  request_dict_.SetInteger("first_crypto_period_index",
385  first_crypto_period_index);
386  request_dict_.SetInteger("crypto_period_count", crypto_period_count_);
387  }
388 
389  base::JSONWriter::Write(request_dict_, request);
390 }
391 
392 Status WidevineKeySource::GenerateKeyMessage(const std::string& request,
393  std::string* message) {
394  DCHECK(message);
395 
396  std::string request_base64_string;
397  base::Base64Encode(request, &request_base64_string);
398 
399  base::DictionaryValue request_dict;
400  request_dict.SetString("request", request_base64_string);
401 
402  // Sign the request.
403  if (signer_) {
404  std::string signature;
405  if (!signer_->GenerateSignature(request, &signature))
406  return Status(error::INTERNAL_ERROR, "Signature generation failed.");
407 
408  std::string signature_base64_string;
409  base::Base64Encode(signature, &signature_base64_string);
410 
411  request_dict.SetString("signature", signature_base64_string);
412  request_dict.SetString("signer", signer_->signer_name());
413  }
414 
415  base::JSONWriter::Write(request_dict, message);
416  return Status::OK;
417 }
418 
419 bool WidevineKeySource::DecodeResponse(
420  const std::string& raw_response,
421  std::string* response) {
422  DCHECK(response);
423 
424  // Extract base64 formatted response from JSON formatted raw response.
425  scoped_ptr<base::Value> root(base::JSONReader::Read(raw_response));
426  if (!root) {
427  LOG(ERROR) << "'" << raw_response << "' is not in JSON format.";
428  return false;
429  }
430  const base::DictionaryValue* response_dict = NULL;
431  RCHECK(root->GetAsDictionary(&response_dict));
432 
433  std::string response_base64_string;
434  RCHECK(response_dict->GetString("response", &response_base64_string));
435  RCHECK(base::Base64Decode(response_base64_string, response));
436  return true;
437 }
438 
439 bool WidevineKeySource::ExtractEncryptionKey(
440  bool enable_key_rotation,
441  bool widevine_classic,
442  const std::string& response,
443  bool* transient_error) {
444  DCHECK(transient_error);
445  *transient_error = false;
446 
447  scoped_ptr<base::Value> root(base::JSONReader::Read(response));
448  if (!root) {
449  LOG(ERROR) << "'" << response << "' is not in JSON format.";
450  return false;
451  }
452 
453  const base::DictionaryValue* license_dict = NULL;
454  RCHECK(root->GetAsDictionary(&license_dict));
455 
456  std::string license_status;
457  RCHECK(license_dict->GetString("status", &license_status));
458  if (license_status != kLicenseStatusOK) {
459  LOG(ERROR) << "Received non-OK license response: " << response;
460  *transient_error = (license_status == kLicenseStatusTransientError);
461  return false;
462  }
463 
464  const base::ListValue* tracks;
465  RCHECK(license_dict->GetList("tracks", &tracks));
466  // Should have at least one track per crypto_period.
467  RCHECK(enable_key_rotation ? tracks->GetSize() >= 1 * crypto_period_count_
468  : tracks->GetSize() >= 1);
469 
470  int current_crypto_period_index = first_crypto_period_index_;
471 
472  EncryptionKeyMap encryption_key_map;
473  for (size_t i = 0; i < tracks->GetSize(); ++i) {
474  const base::DictionaryValue* track_dict;
475  RCHECK(tracks->GetDictionary(i, &track_dict));
476 
477  if (enable_key_rotation) {
478  int crypto_period_index;
479  RCHECK(
480  track_dict->GetInteger("crypto_period_index", &crypto_period_index));
481  if (crypto_period_index != current_crypto_period_index) {
482  if (crypto_period_index != current_crypto_period_index + 1) {
483  LOG(ERROR) << "Expecting crypto period index "
484  << current_crypto_period_index << " or "
485  << current_crypto_period_index + 1 << "; Seen "
486  << crypto_period_index << " at track " << i;
487  return false;
488  }
489  if (!PushToKeyPool(&encryption_key_map))
490  return false;
491  ++current_crypto_period_index;
492  }
493  }
494 
495  std::string track_type_str;
496  RCHECK(track_dict->GetString("type", &track_type_str));
497  TrackType track_type = GetTrackTypeFromString(track_type_str);
498  DCHECK_NE(TRACK_TYPE_UNKNOWN, track_type);
499  RCHECK(encryption_key_map.find(track_type) == encryption_key_map.end());
500 
501  scoped_ptr<EncryptionKey> encryption_key(new EncryptionKey());
502 
503  if (!GetKeyFromTrack(*track_dict, &encryption_key->key))
504  return false;
505 
506  // Get key ID and PSSH data for CENC content only.
507  if (!widevine_classic) {
508  if (!GetKeyIdFromTrack(*track_dict, &encryption_key->key_id))
509  return false;
510 
511  std::vector<uint8_t> pssh_data;
512  if (!GetPsshDataFromTrack(*track_dict, &pssh_data))
513  return false;
514  encryption_key->pssh = PsshBoxFromPsshData(pssh_data);
515  }
516  encryption_key_map[track_type] = encryption_key.release();
517  }
518 
519  DCHECK(!encryption_key_map.empty());
520  if (!enable_key_rotation) {
521  encryption_key_map_ = encryption_key_map;
522  return true;
523  }
524  return PushToKeyPool(&encryption_key_map);
525 }
526 
527 bool WidevineKeySource::PushToKeyPool(
528  EncryptionKeyMap* encryption_key_map) {
529  DCHECK(key_pool_);
530  DCHECK(encryption_key_map);
531  Status status =
532  key_pool_->Push(scoped_refptr<RefCountedEncryptionKeyMap>(
533  new RefCountedEncryptionKeyMap(encryption_key_map)),
534  kInfiniteTimeout);
535  encryption_key_map->clear();
536  if (!status.ok()) {
537  DCHECK_EQ(error::STOPPED, status.error_code());
538  return false;
539  }
540  return true;
541 }
542 
543 } // namespace media
544 } // namespace edash_packager
WidevineKeySource(const std::string &server_url)
void set_signer(scoped_ptr< RequestSigner > signer)
Status GetKey(TrackType track_type, EncryptionKey *key) override
void set_key_fetcher(scoped_ptr< KeyFetcher > key_fetcher)
Status FetchKeys(const std::vector< uint8_t > &content_id, const std::string &policy) override
static std::vector< uint8_t > PsshBoxFromPsshData(const std::vector< uint8_t > &pssh_data)
Definition: key_source.cc:164
Status GetCryptoPeriodKey(uint32_t crypto_period_index, TrackType track_type, EncryptionKey *key) override
static TrackType GetTrackTypeFromString(const std::string &track_type_string)
Convert string representation of track type to enum representation.
Definition: key_source.cc:136
static std::string TrackTypeToString(TrackType track_type)
Convert TrackType to string.
Definition: key_source.cc:150