Refactor oemcrypto mock into stand alone reference code

Merge from Widevine repo of http://go/wvgerrit/46204
Refactor utility code - split the mock, step 1

Merge from Widevine repo of http://go/wvgerrit/46205
Move some OEMCrypto types to common header - split the mock, step 2

Merge from Widevine repo of http://go/wvgerrit/46206
Split mock into two -- step 3

Merge from Widevine repo of http://go/wvgerrit/47460
Split the mock into two -- step 3.5

The CL moves several files used by oemcrypto and cdm into a common
subdirectory, so that it may more easily be shared with partners.

The CORE_DISALLOW_COPY_AND_ASSIGN macro was moved to its own header in
the util/include directory.

This CL removes some references to the mock from other code, and puts
some constants and types, such as the definition of the keybox, into a
header in oemcrypto.

Test: tested as part of http://go/ag/4674759
bug: 76393338
Change-Id: I75b4bde7062ed8ee572c97ebc2f4da018f4be0c9
This commit is contained in:
Fred Gylys-Colwell
2018-06-29 16:57:19 -07:00
parent b8091eaa7d
commit 947531a6a9
109 changed files with 806 additions and 1428 deletions

View File

@@ -0,0 +1,24 @@
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Clock - Platform independent interface for a time library
//
#ifndef WVCDM_UTIL_CLOCK_H_
#define WVCDM_UTIL_CLOCK_H_
#include <stdint.h>
namespace wvcdm {
// Provides time related information. The implementation is platform dependent.
class Clock {
public:
Clock() {}
virtual ~Clock() {}
// Provides the number of seconds since an epoch - 01/01/1970 00:00 UTC
virtual int64_t GetCurrentTime();
};
} // namespace wvcdm
#endif // WVCDM_UTIL_CLOCK_H_

View File

@@ -0,0 +1,15 @@
// Copyright 2018 Google Inc. All Rights Reserved.
#ifndef WVCDM_UTIL_DISALLOW_COPY_AND_ASSIGN_H_
#define WVCDM_UTIL_DISALLOW_COPY_AND_ASSIGN_H_
namespace wvcdm {
#define CORE_DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
} // namespace wvcdm
#endif // WVCDM_UTIL_DISALLOW_COPY_AND_ASSIGN_H_

View File

@@ -0,0 +1,80 @@
// Copyright 2013 Google Inc. All Rights Reserved.
//
// File - Platform independent interface for a File class
//
#ifndef WVCDM_UTIL_FILE_STORE_H_
#define WVCDM_UTIL_FILE_STORE_H_
#include <unistd.h>
#include <string>
#include <vector>
#include "disallow_copy_and_assign.h"
namespace wvcdm {
// File class. The implementation is platform dependent.
class File {
public:
virtual ssize_t Read(char* buffer, size_t bytes);
virtual ssize_t Write(const char* buffer, size_t bytes);
virtual void Close();
protected:
class Impl;
File(Impl*);
virtual ~File();
private:
Impl* impl_;
friend class FileSystem;
CORE_DISALLOW_COPY_AND_ASSIGN(File);
};
class FileSystem {
public:
class Impl;
// defines as bit flag
enum OpenFlags {
kNoFlags = 0,
kCreate = 1,
kReadOnly = 2, // defaults to read and write access
kTruncate = 4
};
FileSystem();
FileSystem(const std::string& origin, void* extra_data);
virtual ~FileSystem();
virtual File* Open(const std::string& file_path, int flags);
virtual bool Exists(const std::string& file_path);
virtual bool Remove(const std::string& file_path);
virtual ssize_t FileSize(const std::string& file_path);
// Return the filenames stored at dir_path.
// dir_path will be stripped from the returned names.
virtual bool List(const std::string& dir_path,
std::vector<std::string>* names);
const std::string& origin() const { return origin_; }
void SetOrigin(const std::string& origin);
const std::string& identifier() const { return identifier_; }
void SetIdentifier(const std::string& identifier);
bool IsGlobal() const { return identifier_.empty(); }
private:
Impl* impl_;
std::string origin_;
std::string identifier_;
CORE_DISALLOW_COPY_AND_ASSIGN(FileSystem);
};
} // namespace wvcdm
#endif // WVCDM_UTIL_FILE_STORE_H_

View File

@@ -0,0 +1,29 @@
// Copyright 2018 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
#include <string>
#include <vector>
#include "wv_cdm_types.h"
namespace wvcdm {
const char kCurrentDirectory[] = ".";
const char kParentDirectory[] = "..";
const char kDirectoryDelimiter = '/';
const char kWildcard[] = "*";
bool IsCurrentOrParentDirectory(char* dir);
class FileUtils {
public:
static bool Exists(const std::string& src);
static bool Remove(const std::string& src);
static bool Copy(const std::string& src, const std::string& dest);
static bool List(const std::string& path, std::vector<std::string>* files);
static bool IsRegularFile(const std::string& path);
static bool IsDirectory(const std::string& path);
static bool CreateDirectory(const std::string& path);
};
} // namespace wvcdm

View File

@@ -0,0 +1,51 @@
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Lock - Platform independent interface for a Mutex class
//
#ifndef WVCDM_UTIL_LOCK_H_
#define WVCDM_UTIL_LOCK_H_
#include "disallow_copy_and_assign.h"
namespace wvcdm {
// Simple lock class. The implementation is platform dependent.
//
// The lock must be unlocked by the thread that locked it.
// The lock is also not recursive (ie. cannot be taken multiple times).
class Lock {
public:
Lock();
~Lock();
void Acquire();
void Release();
friend class AutoLock;
private:
class Impl;
Impl* impl_;
CORE_DISALLOW_COPY_AND_ASSIGN(Lock);
};
// Manages the lock automatically. It will be locked when AutoLock
// is constructed and release when AutoLock goes out of scope.
class AutoLock {
public:
explicit AutoLock(Lock& lock) : lock_(&lock) { lock_->Acquire(); }
explicit AutoLock(Lock* lock) : lock_(lock) { lock_->Acquire(); }
~AutoLock() { lock_->Release(); }
private:
Lock* lock_;
CORE_DISALLOW_COPY_AND_ASSIGN(AutoLock);
};
} // namespace wvcdm
#endif // WVCDM_UTIL_LOCK_H_

View File

@@ -0,0 +1,46 @@
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Log - Platform independent interface for a Logging class
//
#ifndef WVCDM_UTIL_LOG_H_
#define WVCDM_UTIL_LOG_H_
namespace wvcdm {
// Simple logging class. The implementation is platform dependent.
typedef enum {
LOG_ERROR,
LOG_WARN,
LOG_INFO,
LOG_DEBUG,
LOG_VERBOSE
} LogPriority;
extern LogPriority g_cutoff;
// Enable/disable verbose logging (LOGV).
// This function is supplied for cases where the system layer does not
// initialize logging. This is also needed to initialize logging in
// unit tests.
void InitLogging();
void Log(const char* file, const char* function, int line, LogPriority level,
const char* fmt, ...);
// Log APIs
#ifndef LOGE
#define LOGE(...) Log(__FILE__, __func__, __LINE__, \
wvcdm::LOG_ERROR, __VA_ARGS__)
#define LOGW(...) Log(__FILE__, __func__, __LINE__, \
wvcdm::LOG_WARN, __VA_ARGS__)
#define LOGI(...) Log(__FILE__, __func__, __LINE__, \
wvcdm::LOG_INFO, __VA_ARGS__)
#define LOGD(...) Log(__FILE__, __func__, __LINE__, \
wvcdm::LOG_DEBUG, __VA_ARGS__)
#define LOGV(...) Log(__FILE__, __func__, __LINE__, \
wvcdm::LOG_VERBOSE, __VA_ARGS__)
#endif
} // namespace wvcdm
#endif // WVCDM_UTIL_LOG_H_

View File

@@ -0,0 +1,30 @@
// Copyright 2013 Google Inc. All Rights Reserved.
#ifndef WVCDM_UTIL_STRING_CONVERSIONS_H_
#define WVCDM_UTIL_STRING_CONVERSIONS_H_
#include <stddef.h>
#include <stdint.h>
#include <string>
#include <vector>
namespace wvcdm {
std::vector<uint8_t> a2b_hex(const std::string& b);
std::vector<uint8_t> a2b_hex(const std::string& label, const std::string& b);
std::string a2bs_hex(const std::string& b);
std::string b2a_hex(const std::vector<uint8_t>& b);
std::string b2a_hex(const std::string& b);
std::string Base64Encode(const std::vector<uint8_t>& bin_input);
std::vector<uint8_t> Base64Decode(const std::string& bin_input);
std::string Base64SafeEncode(const std::vector<uint8_t>& bin_input);
std::string Base64SafeEncodeNoPad(const std::vector<uint8_t>& bin_input);
std::vector<uint8_t> Base64SafeDecode(const std::string& bin_input);
std::string HexEncode(const uint8_t* bytes, unsigned size);
std::string IntToString(int value);
int64_t htonll64(int64_t x);
inline int64_t ntohll64(int64_t x) { return htonll64(x); }
} // namespace wvcdm
#endif // WVCDM_UTIL_STRING_CONVERSIONS_H_

View File

@@ -0,0 +1,20 @@
// Copyright 2018 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
//
// Clock - implemented using the standard linux time library
#include "clock.h"
#include <sys/time.h>
namespace wvcdm {
int64_t Clock::GetCurrentTime() {
struct timeval tv;
tv.tv_sec = tv.tv_usec = 0;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
} // namespace wvcdm

View File

@@ -0,0 +1,184 @@
// Copyright 2018 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
//
// File class - provides a simple android specific file implementation
#include "file_store.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "file_utils.h"
#include "log.h"
#include "string_conversions.h"
#include "wv_cdm_constants.h"
#include <openssl/md5.h>
#include <openssl/sha.h>
namespace wvcdm {
namespace {
const char kCertificateFileNamePrefix[] = "cert";
const char kCertificateFileNameExt[] = ".bin";
const char kCertificateFileName[] = "cert.bin";
std::string GetFileNameSafeHash(const std::string& input) {
std::vector<uint8_t> hash(MD5_DIGEST_LENGTH);
const unsigned char* input_ptr =
reinterpret_cast<const unsigned char*>(input.data());
MD5(input_ptr, input.size(), &hash[0]);
return wvcdm::Base64SafeEncode(hash);
}
std::string GetFileNameForIdentifier(const std::string path,
const std::string identifier) {
std::string file_name = path;
std::string dir_path;
const size_t delimiter_pos = path.rfind(kDirectoryDelimiter);
if (delimiter_pos != std::string::npos) {
dir_path = file_name.substr(0, delimiter_pos);
file_name = path.substr(delimiter_pos + 1);
}
if (file_name == kCertificateFileName && !identifier.empty()) {
const std::string hash = GetFileNameSafeHash(identifier);
file_name = kCertificateFileNamePrefix + hash + kCertificateFileNameExt;
}
if (dir_path.empty())
return file_name;
else
return dir_path + kDirectoryDelimiter + file_name;
}
} // namespace
class File::Impl {
public:
Impl(FILE* file, const std::string& file_path)
: file_(file), file_path_(file_path) {}
virtual ~Impl() {}
FILE* file_;
std::string file_path_;
};
File::File(Impl* impl) : impl_(impl) {}
File::~File() {
Close();
delete impl_;
}
void File::Close() {
if (impl_ && impl_->file_) {
fflush(impl_->file_);
fsync(fileno(impl_->file_));
fclose(impl_->file_);
impl_->file_ = NULL;
}
}
ssize_t File::Read(char* buffer, size_t bytes) {
if (impl_ && impl_->file_) {
size_t len = fread(buffer, sizeof(char), bytes, impl_->file_);
if (len == 0) {
LOGW("File::Read: fread failed: %d", errno);
}
return len;
}
LOGW("File::Read: file not open");
return -1;
}
ssize_t File::Write(const char* buffer, size_t bytes) {
if (impl_ && impl_->file_) {
size_t len = fwrite(buffer, sizeof(char), bytes, impl_->file_);
if (len == 0) {
LOGW("File::Write: fwrite failed: %d", errno);
}
return len;
}
LOGW("File::Write: file not open");
return -1;
}
class FileSystem::Impl {};
FileSystem::FileSystem() : FileSystem(EMPTY_ORIGIN, NULL) {}
FileSystem::FileSystem(const std::string& origin, void* /* extra_data */)
: origin_(origin) {}
FileSystem::~FileSystem() {}
File* FileSystem::Open(const std::string& in_name, int flags) {
std::string open_flags;
std::string name = GetFileNameForIdentifier(in_name, identifier_);
// create the enclosing directory if it does not exist
size_t delimiter_pos = name.rfind(kDirectoryDelimiter);
if (delimiter_pos != std::string::npos) {
std::string dir_path = name.substr(0, delimiter_pos);
if ((flags & FileSystem::kCreate) && !Exists(dir_path))
FileUtils::CreateDirectory(dir_path);
}
// ensure only owners has access
mode_t old_mask = umask(077);
if (((flags & FileSystem::kTruncate) && Exists(name)) ||
((flags & FileSystem::kCreate) && !Exists(name))) {
FILE* fp = fopen(name.c_str(), "w+");
if (fp) {
fclose(fp);
}
}
open_flags = (flags & FileSystem::kReadOnly) ? "rb" : "rb+";
FILE* file = fopen(name.c_str(), open_flags.c_str());
umask(old_mask);
if (!file) {
LOGW("File::Open: fopen failed: %d", errno);
return NULL;
}
return new File(new File::Impl(file, name));
}
bool FileSystem::Exists(const std::string& path) {
return FileUtils::Exists(GetFileNameForIdentifier(path, identifier_));
}
bool FileSystem::Remove(const std::string& path) {
return FileUtils::Remove(GetFileNameForIdentifier(path, identifier_));
}
ssize_t FileSystem::FileSize(const std::string& in_path) {
std::string path = GetFileNameForIdentifier(in_path, identifier_);
struct stat buf;
if (stat(path.c_str(), &buf) == 0)
return buf.st_size;
else
return -1;
}
bool FileSystem::List(const std::string& path,
std::vector<std::string>* filenames) {
return FileUtils::List(GetFileNameForIdentifier(path, origin_), filenames);
}
void FileSystem::SetOrigin(const std::string& origin) { origin_ = origin; }
void FileSystem::SetIdentifier(const std::string& identifier) {
identifier_ = identifier;
}
} // namespace wvcdm

View File

@@ -0,0 +1,215 @@
// Copyright 2018 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
#include "file_utils.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "file_store.h"
#include "log.h"
#include "properties.h"
namespace wvcdm {
bool IsCurrentOrParentDirectory(char* dir) {
return strcmp(dir, kCurrentDirectory) == 0 ||
strcmp(dir, kParentDirectory) == 0;
}
bool FileUtils::Exists(const std::string& path) {
struct stat buf;
int res = stat(path.c_str(), &buf) == 0;
if (!res) {
LOGV("File::Exists: stat failed: %d", errno);
}
return res;
}
bool FileUtils::Remove(const std::string& path) {
if (FileUtils::IsDirectory(path)) {
// Handle directory deletion
DIR* dir;
if ((dir = opendir(path.c_str())) != NULL) {
// first remove files and dir within it
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
if (!IsCurrentOrParentDirectory(entry->d_name)) {
std::string path_to_remove = path + kDirectoryDelimiter;
path_to_remove += entry->d_name;
if (!Remove(path_to_remove)) {
closedir(dir);
return false;
}
}
}
closedir(dir);
}
if (rmdir(path.c_str())) {
LOGW("File::Remove: rmdir failed: %d", errno);
return false;
}
return true;
} else {
size_t wildcard_pos = path.find(kWildcard);
if (wildcard_pos == std::string::npos) {
// Handle file deletion
if (unlink(path.c_str()) && (errno != ENOENT)) {
LOGW("File::Remove: unlink failed: %d", errno);
return false;
}
} else {
// Handle wildcard specified file deletion
size_t delimiter_pos = path.rfind(kDirectoryDelimiter, wildcard_pos);
if (delimiter_pos == std::string::npos) {
LOGW("File::Remove: unable to find path delimiter before wildcard");
return false;
}
DIR* dir;
std::string dir_path = path.substr(0, delimiter_pos);
if ((dir = opendir(dir_path.c_str())) == NULL) {
LOGW("File::Remove: directory open failed for wildcard");
return false;
}
struct dirent* entry;
std::string ext = path.substr(wildcard_pos + 1);
while ((entry = readdir(dir)) != NULL) {
size_t filename_len = strlen(entry->d_name);
if (filename_len > ext.size()) {
if (strcmp(entry->d_name + filename_len - ext.size(), ext.c_str()) ==
0) {
std::string file_path_to_remove =
dir_path + kDirectoryDelimiter + entry->d_name;
if (!Remove(file_path_to_remove)) {
closedir(dir);
return false;
}
}
}
}
closedir(dir);
}
return true;
}
}
bool FileUtils::Copy(const std::string& src, const std::string& dest) {
struct stat stat_buf;
if (stat(src.c_str(), &stat_buf)) {
LOGV("File::Copy: file %s stat error: %d", src.c_str(), errno);
return false;
}
int fd_src = open(src.c_str(), O_RDONLY);
if (fd_src < 0) {
LOGW("File::Copy: unable to open file %s: %d", src.c_str(), errno);
return false;
}
int fd_dest = open(dest.c_str(), O_WRONLY | O_CREAT, stat_buf.st_mode);
if (fd_dest < 0) {
LOGW("File::Copy: unable to open file %s: %d", dest.c_str(), errno);
close(fd_src);
return false;
}
off_t offset = 0;
bool status = true;
if (sendfile(fd_dest, fd_src, &offset, stat_buf.st_size) < 0) {
LOGV("File::Copy: unable to copy %s to %s: %d", src.c_str(), dest.c_str(),
errno);
status = false;
}
close(fd_src);
close(fd_dest);
return status;
}
bool FileUtils::List(const std::string& path, std::vector<std::string>* files) {
if (NULL == files) {
LOGV("File::List: files destination not provided");
return false;
}
if (!FileUtils::Exists(path)) {
LOGV("File::List: path %s does not exist: %d", path.c_str(), errno);
return false;
}
DIR* dir = opendir(path.c_str());
if (dir == NULL) {
LOGW("File::List: unable to open directory %s: %d", path.c_str(), errno);
return false;
}
files->clear();
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
if (!IsCurrentOrParentDirectory(entry->d_name)) {
files->push_back(entry->d_name);
}
}
closedir(dir);
return true;
}
bool FileUtils::IsRegularFile(const std::string& path) {
struct stat buf;
if (stat(path.c_str(), &buf) == 0)
return buf.st_mode & S_IFREG;
else
return false;
}
bool FileUtils::IsDirectory(const std::string& path) {
struct stat buf;
if (stat(path.c_str(), &buf) == 0)
return buf.st_mode & S_IFDIR;
else
return false;
}
bool FileUtils::CreateDirectory(const std::string& path_in) {
std::string path = path_in;
size_t size = path.size();
if ((size == 1) && (path[0] == kDirectoryDelimiter)) return true;
if (size <= 1) return false;
size_t pos = path.find(kDirectoryDelimiter, 1);
while (pos < size) {
path[pos] = '\0';
if (mkdir(path.c_str(), 0700) != 0) {
if (errno != EEXIST) {
LOGW("File::CreateDirectory: mkdir failed: %d\n", errno);
return false;
}
}
path[pos] = kDirectoryDelimiter;
pos = path.find(kDirectoryDelimiter, pos + 1);
}
if (path[size - 1] != kDirectoryDelimiter) {
if (mkdir(path.c_str(), 0700) != 0) {
if (errno != EEXIST) {
LOGW("File::CreateDirectory: mkdir failed: %d\n", errno);
return false;
}
}
}
return true;
}
} // namespace wvcdm

View File

@@ -0,0 +1,32 @@
// Copyright 2018 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
//
// Lock class - provides a simple android specific mutex implementation
#include "lock.h"
#include <utils/Mutex.h>
namespace wvcdm {
class Lock::Impl {
public:
android::Mutex lock_;
};
Lock::Lock() : impl_(new Lock::Impl()) {
}
Lock::~Lock() {
delete impl_;
}
void Lock::Acquire() {
impl_->lock_.lock();
}
void Lock::Release() {
impl_->lock_.unlock();
}
} // namespace wvcdm

View File

@@ -0,0 +1,78 @@
// Copyright 2018 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine Master
// License Agreement.
//
// Log - implemented using the standard Android logging mechanism
/*
* Qutoing from system/core/include/log/log.h:
* Normally we strip ALOGV (VERBOSE messages) from release builds.
* You can modify this (for example with "#define LOG_NDEBUG 0"
* at the top of your source file) to change that behavior.
*/
#ifndef LOG_NDEBUG
#ifdef NDEBUG
#define LOG_NDEBUG 1
#else
#define LOG_NDEBUG 0
#endif
#endif
#define LOG_TAG "WVCdm"
#define LOG_BUF_SIZE 1024
#include "log.h"
#include <utils/Log.h>
#include <string>
#include <stdio.h>
#include <stdarg.h>
/*
* Uncomment the line below if you want to have the LOGV messages to print
* IMPORTANT : this will affect all of CDM
*/
// #define LOG_NDEBUG 0
namespace wvcdm {
LogPriority g_cutoff = LOG_VERBOSE;
void InitLogging() {}
void Log(const char* file, const char* function, int line, LogPriority level,
const char* format, ...) {
const char* filename = strrchr(file, '/');
filename = filename == nullptr ? file : filename + 1;
char buf[LOG_BUF_SIZE];
int len = snprintf(buf, LOG_BUF_SIZE, "[%s(%d):%s] ", filename, line,
function);
if (len < 0) len = 0;
if (static_cast<unsigned int>(len) < sizeof(buf)) {
va_list ap;
va_start(ap, format);
vsnprintf(buf+len, LOG_BUF_SIZE-len, format, ap);
va_end(ap);
}
android_LogPriority prio = ANDROID_LOG_VERBOSE;
switch(level) {
case LOG_ERROR: prio = ANDROID_LOG_ERROR; break;
case LOG_WARN: prio = ANDROID_LOG_WARN; break;
case LOG_INFO: prio = ANDROID_LOG_INFO; break;
case LOG_DEBUG: prio = ANDROID_LOG_DEBUG; break;
#if LOG_NDEBUG
case LOG_VERBOSE: return;
#else
case LOG_VERBOSE: prio = ANDROID_LOG_VERBOSE; break;
#endif
}
__android_log_write(prio, LOG_TAG, buf);
}
} // namespace wvcdm

View File

@@ -0,0 +1,293 @@
// Copyright 2013 Google Inc. All Rights Reserved.
#include "string_conversions.h"
#include <arpa/inet.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <vector>
#include "log.h"
namespace wvcdm {
static const char kBase64Codes[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// Gets the low |n| bits of |in|.
#define GET_LOW_BITS(in, n) ((in) & ((1 << (n)) - 1))
// Gets the given (zero-indexed) bits [a, b) of |in|.
#define GET_BITS(in, a, b) GET_LOW_BITS((in) >> (a), (b) - (a))
// Calculates a/b using round-up division (only works for positive numbers).
#define CEIL_DIVIDE(a, b) ((((a) - 1) / (b)) + 1)
int DecodeBase64Char(char c) {
const char* it = strchr(kBase64Codes, c);
if (it == NULL)
return -1;
return it - kBase64Codes;
}
bool DecodeHexChar(char ch, unsigned char* digit) {
if (ch >= '0' && ch <= '9') {
*digit = ch - '0';
} else {
ch = tolower(ch);
if ((ch >= 'a') && (ch <= 'f')) {
*digit = ch - 'a' + 10;
} else {
return false;
}
}
return true;
}
// converts an ascii hex string(2 bytes per digit) into a decimal byte string
std::vector<uint8_t> a2b_hex(const std::string& byte) {
std::vector<uint8_t> array;
unsigned int count = byte.size();
if (count == 0 || (count % 2) != 0) {
LOGE("Invalid input size %u for string %s", count, byte.c_str());
return array;
}
for (unsigned int i = 0; i < count / 2; ++i) {
unsigned char msb = 0; // most significant 4 bits
unsigned char lsb = 0; // least significant 4 bits
if (!DecodeHexChar(byte[i * 2], &msb) ||
!DecodeHexChar(byte[i * 2 + 1], &lsb)) {
LOGE("Invalid hex value %c%c at index %d", byte[i * 2], byte[i * 2 + 1],
i);
return array;
}
array.push_back((msb << 4) | lsb);
}
return array;
}
// converts an ascii hex string(2 bytes per digit) into a decimal byte string
// dump the string with the label.
std::vector<uint8_t> a2b_hex(const std::string& label,
const std::string& byte) {
std::cout << std::endl
<< "[[DUMP: " << label << " ]= \"" << byte << "\"]" << std::endl
<< std::endl;
return a2b_hex(byte);
}
std::string a2bs_hex(const std::string& byte) {
std::vector<uint8_t> array = a2b_hex(byte);
return std::string(array.begin(), array.end());
}
std::string b2a_hex(const std::vector<uint8_t>& byte) {
return HexEncode(&byte[0], byte.size());
}
std::string b2a_hex(const std::string& byte) {
return HexEncode(reinterpret_cast<const uint8_t*>(byte.data()),
byte.length());
}
// Encode for standard base64 encoding (RFC4648).
// https://en.wikipedia.org/wiki/Base64
// Text | M | a | n |
// ASCI | 77 (0x4d) | 97 (0x61) | 110 (0x6e) |
// Bits | 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0 |
// Index | 19 | 22 | 5 | 46 |
// Base64 | T | W | F | u |
// | <----------------- 24-bits -----------------> |
std::string Base64Encode(const std::vector<uint8_t>& bin_input) {
if (bin_input.empty()) {
return std::string();
}
// |temp| stores a 24-bit block that is treated as an array where insertions
// occur from high to low.
uint32_t temp = 0;
size_t out_index = 0;
const size_t out_size = CEIL_DIVIDE(bin_input.size(), 3) * 4;
std::string result(out_size, '\0');
for (size_t i = 0; i < bin_input.size(); i++) {
// "insert" 8-bits of data
temp |= (bin_input[i] << ((2 - (i % 3)) * 8));
if (i % 3 == 2) {
result[out_index++] = kBase64Codes[GET_BITS(temp, 18, 24)];
result[out_index++] = kBase64Codes[GET_BITS(temp, 12, 18)];
result[out_index++] = kBase64Codes[GET_BITS(temp, 6, 12)];
result[out_index++] = kBase64Codes[GET_BITS(temp, 0, 6)];
temp = 0;
}
}
if (bin_input.size() % 3 == 1) {
result[out_index++] = kBase64Codes[GET_BITS(temp, 18, 24)];
result[out_index++] = kBase64Codes[GET_BITS(temp, 12, 18)];
result[out_index++] = '=';
result[out_index++] = '=';
} else if (bin_input.size() % 3 == 2) {
result[out_index++] = kBase64Codes[GET_BITS(temp, 18, 24)];
result[out_index++] = kBase64Codes[GET_BITS(temp, 12, 18)];
result[out_index++] = kBase64Codes[GET_BITS(temp, 6, 12)];
result[out_index++] = '=';
}
return result;
}
// Filename-friendly base64 encoding (RFC4648), commonly referred to
// as Base64WebSafeEncode.
//
// This is the encoding required to interface with the provisioning server, as
// well as for certain license server transactions. It is also used for logging
// certain strings. The difference between web safe encoding vs regular encoding
// is that the web safe version replaces '+' with '-' and '/' with '_'.
std::string Base64SafeEncode(const std::vector<uint8_t>& bin_input) {
if (bin_input.empty()) {
return std::string();
}
std::string ret = Base64Encode(bin_input);
for (size_t i = 0; i < ret.size(); i++) {
if (ret[i] == '+')
ret[i] = '-';
else if (ret[i] == '/')
ret[i] = '_';
}
return ret;
}
std::string Base64SafeEncodeNoPad(const std::vector<uint8_t>& bin_input) {
std::string b64_output = Base64SafeEncode(bin_input);
// Output size: ceiling [ bin_input.size() * 4 / 3 ].
b64_output.resize((bin_input.size() * 4 + 2) / 3);
return b64_output;
}
// Decode for standard base64 encoding (RFC4648).
std::vector<uint8_t> Base64Decode(const std::string& b64_input) {
if (b64_input.empty()) {
return std::vector<uint8_t>();
}
const size_t out_size_max = CEIL_DIVIDE(b64_input.size() * 3, 4);
std::vector<uint8_t> result(out_size_max, '\0');
// |temp| stores 24-bits of data that is treated as an array where insertions
// occur from high to low.
uint32_t temp = 0;
size_t out_index = 0;
size_t i;
for (i = 0; i < b64_input.size(); i++) {
if (b64_input[i] == '=') {
// Verify an '=' only appears at the end. We want i to remain at the
// first '=', so we need an inner loop.
for (size_t j = i; j < b64_input.size(); j++) {
if (b64_input[j] != '=') {
LOGE("base64Decode failed");
return std::vector<uint8_t>();
}
}
break;
}
const int decoded = DecodeBase64Char(b64_input[i]);
if (decoded < 0) {
LOGE("base64Decode failed");
return std::vector<uint8_t>();
}
// "insert" 6-bits of data
temp |= (decoded << ((3 - (i % 4)) * 6));
if (i % 4 == 3) {
result[out_index++] = GET_BITS(temp, 16, 24);
result[out_index++] = GET_BITS(temp, 8, 16);
result[out_index++] = GET_BITS(temp, 0, 8);
temp = 0;
}
}
switch (i % 4) {
case 1:
LOGE("base64Decode failed");
return std::vector<uint8_t>();
case 2:
result[out_index++] = GET_BITS(temp, 16, 24);
break;
case 3:
result[out_index++] = GET_BITS(temp, 16, 24);
result[out_index++] = GET_BITS(temp, 8, 16);
break;
}
result.resize(out_index);
return result;
}
// Decode for Filename-friendly base64 encoding (RFC4648), commonly referred
// as Base64WebSafeDecode. Add padding if needed.
std::vector<uint8_t> Base64SafeDecode(const std::string& b64_input) {
if (b64_input.empty()) {
return std::vector<uint8_t>();
}
// Make a copy so we can modify it to replace the web-safe special characters
// with the normal ones.
std::string input_copy = b64_input;
for (size_t i = 0; i < input_copy.size(); i++) {
if (input_copy[i] == '-')
input_copy[i] = '+';
else if (input_copy[i] == '_')
input_copy[i] = '/';
}
return Base64Decode(input_copy);
}
std::string HexEncode(const uint8_t* in_buffer, unsigned int size) {
static const char kHexChars[] = "0123456789ABCDEF";
// Each input byte creates two output hex characters.
std::string out_buffer(size * 2, '\0');
for (unsigned int i = 0; i < size; ++i) {
char byte = in_buffer[i];
out_buffer[(i << 1)] = kHexChars[(byte >> 4) & 0xf];
out_buffer[(i << 1) + 1] = kHexChars[byte & 0xf];
}
return out_buffer;
}
std::string IntToString(int value) {
// log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
// So round up to allocate 3 output characters per byte, plus 1 for '-'.
const int kOutputBufSize = 3 * sizeof(int) + 1;
char buffer[kOutputBufSize];
memset(buffer, 0, kOutputBufSize);
snprintf(buffer, kOutputBufSize, "%d", value);
std::string out_string(buffer);
return out_string;
}
int64_t htonll64(int64_t x) { // Convert to big endian (network-byte-order)
union {
uint32_t array[2];
int64_t number;
} mixed;
mixed.number = 1;
if (mixed.array[0] == 1) { // Little Endian.
mixed.number = x;
uint32_t temp = mixed.array[0];
mixed.array[0] = htonl(mixed.array[1]);
mixed.array[1] = htonl(temp);
return mixed.number;
} else { // Big Endian.
return x;
}
}
} // namespace wvcdm