summaryrefslogtreecommitdiffstats
path: root/dom/media/gmp-plugin/gmp-test-decryptor.cpp
blob: afa8096021c2caf1176cff54bb04112ada68e736 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "gmp-test-decryptor.h"
#include "gmp-test-storage.h"
#include "gmp-test-output-protection.h"

#include <string>
#include <vector>
#include <iostream>
#include <istream>
#include <iterator>
#include <sstream>
#include <set>

#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"

using namespace std;

std::string FakeDecryptor::sNodeId;

FakeDecryptor* FakeDecryptor::sInstance = nullptr;
extern GMPPlatformAPI* g_platform_api; // Defined in gmp-fake.cpp

class GMPMutexAutoLock
{
public:
  explicit GMPMutexAutoLock(GMPMutex* aMutex) : mMutex(aMutex) {
    mMutex->Acquire();
  }
  ~GMPMutexAutoLock() {
    mMutex->Release();
  }
private:
  GMPMutex* const mMutex;
};

class TestManager {
public:
  TestManager() : mMutex(CreateMutex()) {}

  // Register a test with the test manager.
  void BeginTest(const string& aTestID) {
    GMPMutexAutoLock lock(mMutex);
    auto found = mTestIDs.find(aTestID);
    if (found == mTestIDs.end()) {
      mTestIDs.insert(aTestID);
    } else {
      Error("FAIL BeginTest test already existed: " + aTestID);
    }
  }

  // Notify the test manager that the test is finished. If all tests are done,
  // test manager will send "test-storage complete" to notify the parent that
  // all tests are finished and also delete itself.
  void EndTest(const string& aTestID) {
    bool isEmpty = false;
    {
      GMPMutexAutoLock lock(mMutex);
      auto found = mTestIDs.find(aTestID);
      if (found != mTestIDs.end()) {
        mTestIDs.erase(aTestID);
        isEmpty = mTestIDs.empty();
      } else {
        Error("FAIL EndTest test not existed: " + aTestID);
        return;
      }
    }
    if (isEmpty) {
      Finish();
      delete this;
    }
  }

private:
  ~TestManager() {
    mMutex->Destroy();
  }

  static void Error(const string& msg) {
    FakeDecryptor::Message(msg);
  }

  static void Finish() {
    FakeDecryptor::Message("test-storage complete");
  }

  static GMPMutex* CreateMutex() {
    GMPMutex* mutex = nullptr;
    g_platform_api->createmutex(&mutex);
    return mutex;
  }

  GMPMutex* const mMutex;
  set<string> mTestIDs;
};

FakeDecryptor::FakeDecryptor(GMPDecryptorHost* aHost)
  : mCallback(nullptr)
  , mHost(aHost)
{
  MOZ_ASSERT(!sInstance);
  sInstance = this;
}

void FakeDecryptor::DecryptingComplete()
{
  sInstance = nullptr;
  delete this;
}

void
FakeDecryptor::Message(const std::string& aMessage)
{
  MOZ_ASSERT(sInstance);
  const static std::string sid("fake-session-id");
  sInstance->mCallback->SessionMessage(sid.c_str(), sid.size(),
                                       kGMPLicenseRequest,
                                       (const uint8_t*)aMessage.c_str(), aMessage.size());
}

std::vector<std::string>
Tokenize(const std::string& aString)
{
  std::stringstream strstr(aString);
  std::istream_iterator<std::string> it(strstr), end;
  return std::vector<std::string>(it, end);
}

static const string TruncateRecordId = "truncate-record-id";
static const string TruncateRecordData = "I will soon be truncated";

class ReadThenTask : public GMPTask {
public:
  ReadThenTask(string aId, ReadContinuation* aThen)
    : mId(aId)
    , mThen(aThen)
  {}
  void Run() override {
    ReadRecord(mId, mThen);
  }
  void Destroy() override {
    delete this;
  }
  string mId;
  ReadContinuation* mThen;
};

class SendMessageTask : public GMPTask {
public:
  explicit SendMessageTask(const string& aMessage,
                           TestManager* aTestManager = nullptr,
                           const string& aTestID = "")
    : mMessage(aMessage), mTestmanager(aTestManager), mTestID(aTestID) {}

  void Run() override {
    FakeDecryptor::Message(mMessage);
    if (mTestmanager) {
      mTestmanager->EndTest(mTestID);
    }
  }

  void Destroy() override {
    delete this;
  }

private:
  string mMessage;
  TestManager* const mTestmanager;
  const string mTestID;
};

class TestEmptyContinuation : public ReadContinuation {
public:
  TestEmptyContinuation(TestManager* aTestManager, const string& aTestID)
    : mTestmanager(aTestManager), mTestID(aTestID) {}

  void ReadComplete(GMPErr aErr, const std::string& aData) override {
    if (aData != "") {
      FakeDecryptor::Message("FAIL TestEmptyContinuation record was not truncated");
    }
    mTestmanager->EndTest(mTestID);
    delete this;
  }

private:
  TestManager* const mTestmanager;
  const string mTestID;
};

class TruncateContinuation : public ReadContinuation {
public:
  TruncateContinuation(const string& aID,
                       TestManager* aTestManager,
                       const string& aTestID)
    : mID(aID), mTestmanager(aTestManager), mTestID(aTestID) {}

  void ReadComplete(GMPErr aErr, const std::string& aData) override {
    if (aData != TruncateRecordData) {
      FakeDecryptor::Message("FAIL TruncateContinuation read data doesn't match written data");
    }
    auto cont = new TestEmptyContinuation(mTestmanager, mTestID);
    auto msg = "FAIL in TruncateContinuation write.";
    auto failTask = new SendMessageTask(msg, mTestmanager, mTestID);
    WriteRecord(mID, nullptr, 0, new ReadThenTask(mID, cont), failTask);
    delete this;
  }

private:
  const string mID;
  TestManager* const mTestmanager;
  const string mTestID;
};

class VerifyAndFinishContinuation : public ReadContinuation {
public:
  explicit VerifyAndFinishContinuation(string aValue,
                                       TestManager* aTestManager,
                                       const string& aTestID)
  : mValue(aValue), mTestmanager(aTestManager), mTestID(aTestID) {}

  void ReadComplete(GMPErr aErr, const std::string& aData) override {
    if (aData != mValue) {
      FakeDecryptor::Message("FAIL VerifyAndFinishContinuation read data doesn't match expected data");
    }
    mTestmanager->EndTest(mTestID);
    delete this;
  }

private:
  string mValue;
  TestManager* const mTestmanager;
  const string mTestID;
};

class VerifyAndOverwriteContinuation : public ReadContinuation {
public:
  VerifyAndOverwriteContinuation(string aId, string aValue, string aOverwrite,
                                 TestManager* aTestManager, const string& aTestID)
    : mId(aId)
    , mValue(aValue)
    , mOverwrite(aOverwrite)
    , mTestmanager(aTestManager)
    , mTestID(aTestID)
  {}

  void ReadComplete(GMPErr aErr, const std::string& aData) override {
    if (aData != mValue) {
      FakeDecryptor::Message("FAIL VerifyAndOverwriteContinuation read data doesn't match expected data");
    }
    auto cont = new VerifyAndFinishContinuation(mOverwrite, mTestmanager, mTestID);
    auto msg = "FAIL in VerifyAndOverwriteContinuation write.";
    auto failTask = new SendMessageTask(msg, mTestmanager, mTestID);
    WriteRecord(mId, mOverwrite, new ReadThenTask(mId, cont), failTask);
    delete this;
  }

private:
  string mId;
  string mValue;
  string mOverwrite;
  TestManager* const mTestmanager;
  const string mTestID;
};

static const string OpenAgainRecordId = "open-again-record-id";

class OpenedSecondTimeContinuation : public OpenContinuation {
public:
  explicit OpenedSecondTimeContinuation(GMPRecord* aRecord,
                                        TestManager* aTestManager,
                                        const string& aTestID)
    : mRecord(aRecord), mTestmanager(aTestManager), mTestID(aTestID) {
    MOZ_ASSERT(aRecord);
  }

  virtual void OpenComplete(GMPErr aStatus, GMPRecord* aRecord) override {
    if (GMP_SUCCEEDED(aStatus)) {
      FakeDecryptor::Message("FAIL OpenSecondTimeContinuation should not be able to re-open record.");
    }
    if (aRecord) {
      aRecord->Close();
    }
    // Succeeded, open should have failed.
    mTestmanager->EndTest(mTestID);
    mRecord->Close();
  }

private:
  GMPRecord* mRecord;
  TestManager* const mTestmanager;
  const string mTestID;
};

class OpenedFirstTimeContinuation : public OpenContinuation {
public:
  OpenedFirstTimeContinuation(const string& aID,
                              TestManager* aTestManager,
                              const string& aTestID)
    : mID(aID), mTestmanager(aTestManager), mTestID(aTestID) {}

  virtual void OpenComplete(GMPErr aStatus, GMPRecord* aRecord) override {
    if (GMP_FAILED(aStatus)) {
      FakeDecryptor::Message("FAIL OpenAgainContinuation to open record initially.");
      mTestmanager->EndTest(mTestID);
      if (aRecord) {
        aRecord->Close();
      }
      return;
    }

    auto cont = new OpenedSecondTimeContinuation(aRecord, mTestmanager, mTestID);
    GMPOpenRecord(mID, cont);
  }

private:
  const string mID;
  TestManager* const mTestmanager;
  const string mTestID;
};

static void
DoTestStorage(const string& aPrefix, TestManager* aTestManager)
{
  // Basic I/O tests. We run three cases concurrently. The tests, like
  // GMPStorage run asynchronously. When they've all passed, we send
  // a message back to the parent process, or a failure message if not.

  // Test 1: Basic I/O test, and test that writing 0 bytes in a record
  // deletes record.
  //
  // Write data to truncate record, then
  // read data, verify that we read what we wrote, then
  // write 0 bytes to truncate record, then
  // read data, verify that 0 bytes was read
  const string id1 = aPrefix + TruncateRecordId;
  const string testID1 = aPrefix + "write-test-1";
  aTestManager->BeginTest(testID1);
  auto cont1 = new TruncateContinuation(id1, aTestManager, testID1);
  auto msg1 = "FAIL in TestStorage writing TruncateRecord.";
  auto failTask1 = new SendMessageTask(msg1, aTestManager, testID1);
  WriteRecord(id1, TruncateRecordData,
              new ReadThenTask(id1, cont1), failTask1);

  // Test 2: Test that overwriting a record with a shorter record truncates
  // the record to the shorter record.
  //
  // Write record, then
  // read and verify record, then
  // write a shorter record to same record.
  // read and verify
  string id2 = aPrefix + "record1";
  string record1 = "This is the first write to a record.";
  string overwrite = "A shorter record";
  const string testID2 = aPrefix + "write-test-2";
  aTestManager->BeginTest(testID2);
  auto task2 = new VerifyAndOverwriteContinuation(id2, record1, overwrite,
                                                  aTestManager, testID2);
  auto msg2 = "FAIL in TestStorage writing record1.";
  auto failTask2 = new SendMessageTask(msg2, aTestManager, testID2);
  WriteRecord(id2, record1, new ReadThenTask(id2, task2), failTask2);

  // Test 3: Test that opening a record while it's already open fails.
  //
  // Open record1, then
  // open record1, should fail.
  // close record1
  const string id3 = aPrefix + OpenAgainRecordId;
  const string testID3 = aPrefix + "open-test-1";
  aTestManager->BeginTest(testID3);
  auto task3 = new OpenedFirstTimeContinuation(id3, aTestManager, testID3);
  GMPOpenRecord(id3, task3);
}

class TestStorageTask : public GMPTask {
public:
  TestStorageTask(const string& aPrefix, TestManager* aTestManager)
    : mPrefix(aPrefix), mTestManager(aTestManager) {}
  virtual void Destroy() { delete this; }
  virtual void Run() {
    DoTestStorage(mPrefix, mTestManager);
  }
private:
  const string mPrefix;
  TestManager* const mTestManager;
};

void
FakeDecryptor::TestStorage()
{
  TestManager* testManager = new TestManager();
  GMPThread* thread1 = nullptr;
  GMPThread* thread2 = nullptr;

  // Main thread tests.
  DoTestStorage("mt1-", testManager);
  DoTestStorage("mt2-", testManager);

  // Off-main-thread tests.
  if (GMP_SUCCEEDED(g_platform_api->createthread(&thread1))) {
    thread1->Post(new TestStorageTask("thread1-", testManager));
  } else {
    FakeDecryptor::Message("FAIL to create thread1 for storage tests");
  }

  if (GMP_SUCCEEDED(g_platform_api->createthread(&thread2))) {
    thread2->Post(new TestStorageTask("thread2-", testManager));
  } else {
    FakeDecryptor::Message("FAIL to create thread2 for storage tests");
  }

  if (thread1) {
    thread1->Join();
  }

  if (thread2) {
    thread2->Join();
  }

  // Note: Once all tests finish, TestManager will dispatch "test-pass" message,
  // which ends the test for the parent.
}

class ReportWritten : public GMPTask {
public:
  ReportWritten(const string& aRecordId, const string& aValue)
    : mRecordId(aRecordId)
    , mValue(aValue)
  {}
  void Run() override {
    FakeDecryptor::Message("stored " + mRecordId + " " + mValue);
  }
  void Destroy() override {
    delete this;
  }
  const string mRecordId;
  const string mValue;
};

class ReportReadStatusContinuation : public ReadContinuation {
public:
  explicit ReportReadStatusContinuation(const string& aRecordId)
    : mRecordId(aRecordId)
  {}
  void ReadComplete(GMPErr aErr, const std::string& aData) override {
    if (GMP_FAILED(aErr)) {
      FakeDecryptor::Message("retrieve " + mRecordId + " failed");
    } else {
      stringstream ss;
      ss << aData.size();
      string len;
      ss >> len;
      FakeDecryptor::Message("retrieve " + mRecordId + " succeeded (length " +
                             len + " bytes)");
    }
    delete this;
  }
  string mRecordId;
};

class ReportReadRecordContinuation : public ReadContinuation {
public:
  explicit ReportReadRecordContinuation(const string& aRecordId)
    : mRecordId(aRecordId)
  {}
  void ReadComplete(GMPErr aErr, const std::string& aData) override {
    if (GMP_FAILED(aErr)) {
      FakeDecryptor::Message("retrieved " + mRecordId + " failed");
    } else {
      FakeDecryptor::Message("retrieved " + mRecordId + " " + aData);
    }
    delete this;
  }
  string mRecordId;
};

static void
RecvGMPRecordIterator(GMPRecordIterator* aRecordIterator,
                      void* aUserArg,
                      GMPErr aStatus)
{
  FakeDecryptor* decryptor = reinterpret_cast<FakeDecryptor*>(aUserArg);
  decryptor->ProcessRecordNames(aRecordIterator, aStatus);
}

void
FakeDecryptor::ProcessRecordNames(GMPRecordIterator* aRecordIterator,
                                  GMPErr aStatus)
{
  if (sInstance != this) {
    FakeDecryptor::Message("Error aUserArg was not passed through GetRecordIterator");
    return;
  }
  if (GMP_FAILED(aStatus)) {
    FakeDecryptor::Message("Error GetRecordIterator failed");
    return;
  }
  std::string response("record-names ");
  bool first = true;
  const char* name = nullptr;
  uint32_t len = 0;
  while (GMP_SUCCEEDED(aRecordIterator->GetName(&name, &len))) {
    std::string s(name, name+len);
    if (!first) {
      response += ",";
    } else {
      first = false;
    }
    response += s;
    aRecordIterator->NextRecord();
  }
  aRecordIterator->Close();
  FakeDecryptor::Message(response);
}

enum ShutdownMode {
  ShutdownNormal,
  ShutdownTimeout,
  ShutdownStoreToken
};

static ShutdownMode sShutdownMode = ShutdownNormal;
static string sShutdownToken = "";

void
FakeDecryptor::UpdateSession(uint32_t aPromiseId,
                             const char* aSessionId,
                             uint32_t aSessionIdLength,
                             const uint8_t* aResponse,
                             uint32_t aResponseSize)
{
  std::string response((const char*)aResponse, (const char*)(aResponse)+aResponseSize);
  std::vector<std::string> tokens = Tokenize(response);
  const string& task = tokens[0];
  if (task == "test-storage") {
    TestStorage();
  } else if (task == "store") {
      // send "stored record" message on complete.
    const string& id = tokens[1];
    const string& value = tokens[2];
    WriteRecord(id,
                value,
                new ReportWritten(id, value),
                new SendMessageTask("FAIL in writing record."));
  } else if (task == "retrieve") {
    const string& id = tokens[1];
    ReadRecord(id, new ReportReadStatusContinuation(id));
  } else if (task == "shutdown-mode") {
    const string& mode = tokens[1];
    if (mode == "timeout") {
      sShutdownMode = ShutdownTimeout;
    } else if (mode == "token") {
      sShutdownMode = ShutdownStoreToken;
      sShutdownToken = tokens[2];
      Message("shutdown-token received " + sShutdownToken);
    }
  } else if (task == "retrieve-shutdown-token") {
    ReadRecord("shutdown-token", new ReportReadRecordContinuation("shutdown-token"));
  } else if (task == "test-op-apis") {
    mozilla::gmptest::TestOuputProtectionAPIs();
  } else if (task == "retrieve-plugin-voucher") {
    const uint8_t* rawVoucher = nullptr;
    uint32_t length = 0;
    mHost->GetPluginVoucher(&rawVoucher, &length);
    std::string voucher((const char*)rawVoucher, (const char*)(rawVoucher + length));
    Message("retrieved plugin-voucher: " + voucher);
  } else if (task == "retrieve-record-names") {
    GMPEnumRecordNames(&RecvGMPRecordIterator, this);
  } else if (task == "retrieve-node-id") {
    Message("node-id " + sNodeId);
  }
}

class CompleteShutdownTask : public GMPTask {
public:
  explicit CompleteShutdownTask(GMPAsyncShutdownHost* aHost)
    : mHost(aHost)
  {
  }
  virtual void Run() {
    mHost->ShutdownComplete();
  }
  virtual void Destroy() { delete this; }
  GMPAsyncShutdownHost* mHost;
};

void
TestAsyncShutdown::BeginShutdown() {
  switch (sShutdownMode) {
    case ShutdownNormal:
      mHost->ShutdownComplete();
      break;
    case ShutdownTimeout:
      // Don't do anything; wait for timeout, Gecko should kill
      // the plugin and recover.
      break;
    case ShutdownStoreToken:
      // Store message, then shutdown.
      WriteRecord("shutdown-token",
                  sShutdownToken,
                  new CompleteShutdownTask(mHost),
                  new SendMessageTask("FAIL writing shutdown-token."));
      break;
  }
}