diff options
author | Jihyun Kim <jihyun86.kim@samsung.com> | 2012-09-12 21:08:11 +0900 |
---|---|---|
committer | Dima Zavin <dima@android.com> | 2012-09-14 14:03:50 -0700 |
commit | 9081ca65cb7959b6a06ba44823f84a6afa8bca2f (patch) | |
tree | 6aa7d988424ede4a57acd72de485fbd8008bc332 /mobicore | |
parent | 5c88d1f2e176e716cd51df32c6835ec3b89b20e1 (diff) | |
download | exynos5-9081ca65cb7959b6a06ba44823f84a6afa8bca2f.tar.gz |
mobicore: update MobiCore userspace daemon and libraries
Mobicore is updated to MC1.2_V003 from MC1.2_V002.
So, mobicore driver is updated following
SAMSUNG_Exynos5250_EngineeringRelease_MC1.2_V003
In addition, provisioning library is removed.
Change-Id: I833315b54bbc9b046017d7ddddcb1a19e028bcf9
Signed-off-by: Jihyun Kim <jihyun86.kim@samsung.com>
Diffstat (limited to 'mobicore')
53 files changed, 1944 insertions, 4602 deletions
diff --git a/mobicore/Android.mk b/mobicore/Android.mk index f30202c..c89cb22 100644 --- a/mobicore/Android.mk +++ b/mobicore/Android.mk @@ -5,11 +5,20 @@ # ============================================================================= MOBICORE_PROJECT_PATH := $(call my-dir) # Setup common variables -COMP_PATH_Logwrapper := $(MOBICORE_PROJECT_PATH)/common/LogWrapper +LOG_WRAPPER := $(MOBICORE_PROJECT_PATH)/common/LogWrapper COMP_PATH_MobiCore := $(MOBICORE_PROJECT_PATH)/common/MobiCore COMP_PATH_MobiCoreDriverMod := $(MOBICORE_PROJECT_PATH)/include +# Application wide Cflags +GLOBAL_INCLUDES := bionic \ + external/stlport/stlport \ + $(COMP_PATH_MobiCore)/inc \ + $(COMP_PATH_MobiCoreDriverMod)/Public \ + $(COMP_PATH_MobiCore)/inc/TlCm + +GLOBAL_LIBRARIES := libstlport + # Include the Daemon include $(MOBICORE_PROJECT_PATH)/daemon/Android.mk @@ -17,9 +26,6 @@ MC_INCLUDE_DIR := $(COMP_PATH_MobiCore)/inc \ $(COMP_PATH_MobiCore)/inc/TlCm \ $(MOBICORE_PROJECT_PATH)/daemon/ClientLib/public \ $(MOBICORE_PROJECT_PATH)/daemon/Registry/Public - MC_DEBUG := _DEBUG - -# Include the provisioning lib -include $(MOBICORE_PROJECT_PATH)/provlib/Android.mk - +SYSTEM_LIB_DIR=/system/lib +GDM_PROVLIB_SHARED_LIBS=libMcClient diff --git a/mobicore/common/LogWrapper/log.h b/mobicore/common/LogWrapper/log.h index f289b73..36c1746 100644 --- a/mobicore/common/LogWrapper/log.h +++ b/mobicore/common/LogWrapper/log.h @@ -38,27 +38,49 @@ #include <stdio.h> #include <android/log.h> +/** LOG_I(fmt, args...) + * Informative logging, only shown in debug version + */ + +/** LOG_W(fmt, args...) + * Warnings logging, only shown in debug version + */ + +/** LOG_E(fmt, args...) + * Error logging, shown in debug and release version + */ + +/** LOG_V(fmt, args...) + * Verbose logging, shown in debug version if the including file defines LOG_VERBOSE + */ + +/** LOG_I_BUF(szDescriptor, blob, sizeOfBlob) + * Binary logging, line-wise output to LOG_I + */ #define EOL "\n" #define DUMMY_FUNCTION() do{}while(0) - #ifdef LOG_ANDROID - -#ifdef NDEBUG +// log to adb logcat +#ifdef NDEBUG // no logging in debug version #define LOG_I(fmt, args...) DUMMY_FUNCTION() #define LOG_W(fmt, args...) DUMMY_FUNCTION() #else - #define LOG_I(fmt, args...) LOG_i("%d : "fmt , __LINE__ , ## args) - #define LOG_W(fmt, args...) LOG_w("%d : "fmt , __LINE__ , ## args) + // add LINE + #define LOG_I(fmt, args...) LOG_i(fmt";%d", ## args, __LINE__) + #define LOG_W(fmt, args...) LOG_w(fmt";%d", ## args, __LINE__) #endif - #define _LOG_E(fmt, args...) LOG_e("%d : "fmt , __LINE__ , ## args) + // LOG_E is always defined + #define _LOG_E(fmt, args...) LOG_e(fmt, ## args) + // actually mapping to log system, adding level and tag. #define LOG_i(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOG_w(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define LOG_e(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #else //!defined(LOG_ANDROID) +// log to std.out using printf // #level / #LOG_TAG ( process_id): __VA_ARGS__ // Example: @@ -72,7 +94,7 @@ } while(1!=1) -#ifdef NDEBUG +#ifdef NDEBUG // no logging in debug version #define LOG_I(fmt, args...) DUMMY_FUNCTION() #define LOG_W(fmt, args...) DUMMY_FUNCTION() #else @@ -83,6 +105,11 @@ #endif //defined(LOG_ANDROID) +#if defined(LOG_VERBOSE) +#define LOG_V LOG_I +#else +#define LOG_V(...) DUMMY_FUNCTION() +#endif /** LOG_E() needs to be more prominent: * Display "*********** ERROR ***********" before actual error message. @@ -90,11 +117,14 @@ #define LOG_E(...) \ do \ { \ - _LOG_E("*****************************"); \ - _LOG_E("********* ERROR *********"); \ - _LOG_E(__VA_ARGS__); \ + _LOG_E(" *****************************"); \ + _LOG_E(" *** ERROR: "__VA_ARGS__); \ + _LOG_E(" *** Detected in %s:%i/%s()", __FILE__, __LINE__, __FUNCTION__); \ + _LOG_E(" *****************************"); \ } while(1!=1) +#define LOG_ERRNO(MESSAGE) \ + LOG_E("%s failed with \"%s\"(errno %i)", MESSAGE, strerror(errno), errno); #define LOG_I_BUF LOG_I_Buf diff --git a/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h b/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h index 6e17afd..6d10131 100644 --- a/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h +++ b/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h @@ -1,4 +1,4 @@ -/** @addtogroup CMP +/** @addtmt=unixgroup CMP * @{ * @file * Content management trustlet UUID definitions. diff --git a/mobicore/common/MobiCore/inc/mcSo.h b/mobicore/common/MobiCore/inc/mcSo.h index cf1f4ae..f91858c 100644 --- a/mobicore/common/MobiCore/inc/mcSo.h +++ b/mobicore/common/MobiCore/inc/mcSo.h @@ -39,8 +39,15 @@ #include "mcUuid.h" #include "mcSpid.h" -#define SO_VERSION_MAJOR 2 -#define SO_VERSION_MINOR 0 +#define SO_USE_VERSION_22 FALSE + +#if SO_USE_VERSION_22 + #define SO_VERSION_MAJOR 2 + #define SO_VERSION_MINOR 2 +#else + #define SO_VERSION_MAJOR 2 + #define SO_VERSION_MINOR 1 +#endif #define MC_ENUM_32BIT_SPACER ((int32_t)-1) @@ -92,7 +99,51 @@ typedef struct { mcUuid_t uuid; } tlApiSpTrustletId_t; -/** Secure object header. +/** Secure object header v2.2. + * A secure object header introduces a secure object. + * Layout of a secure object: + * <pre> + * <code> + * + * +--------+------------------+------------------+--------+--------+ + * | Header | plain-data | encrypted-data | hash | random | + * +--------+------------------+------------------+--------+--------+ + * + * /--------/---- plainLen ----/-- encryptedLen --/-- 32 --/-- 16 --/ + * + * /----------------- toBeHashedLen --------------/ + * + * /-- toBeEncryptedLen --/ + * + * /--------------------------- totalSoSize ------------------------/ + * + * </code> + * </pre> + */ + +/** Secure object header v2.1. + * A secure object header introduces a secure object. + * Layout of a secure object: + * <pre> + * <code> + * + * +--------+------------------+------------------+--------+--------+---------+ + * | Header | plain-data | encrypted-data | hash | random | padding | + * +--------+------------------+------------------+--------+--------+---------+ + * + * /--------/---- plainLen ----/-- encryptedLen --/-- 24 --/--- 9 --/- 0..15 -/ + * + * /----------------- toBeHashedLen --------------/ + * + * /-- toBeEncryptedLen --/ + * + * /--------------------------- totalSoSize ----------------------------------/ + * + * </code> + * </pre> + */ + +/** Secure object header v2.0. * A secure object header introduces a secure object. * Layout of a secure object: * <pre> @@ -140,12 +191,32 @@ typedef struct { /** Maximum number of ISO padding bytes. */ #define MC_SO_MAX_PADDING_SIZE (MC_SO_ENCRYPT_BLOCK_SIZE) -/** Size of hash used for secure objects. */ +/** Size of hash used for secure objects v2. */ #define MC_SO_HASH_SIZE 32 -/** Calculates gross size of cryptogram within secure object including ISO padding bytes. */ -#define MC_SO_ENCRYPT_PADDED_SIZE(netsize) ( (netsize) + \ - MC_SO_MAX_PADDING_SIZE - (netsize) % MC_SO_MAX_PADDING_SIZE ) +/** Size of hash used for secure object v2.1. */ +#define MC_SO21_HASH_SIZE 24 +/** Size of random used for secure objects v2.1. */ +#define MC_SO21_RND_SIZE 9 + +/** Size of hash used for secure object v2.2. */ +#define MC_SO22_HASH_SIZE 32 +/** Size of random used for secure objects v2.2. */ +#define MC_SO22_RND_SIZE 16 + +/** Hash size for current generated wrapping */ +#define MC_SO2X_HASH_SIZE (SO_USE_VERSION_22 ? MC_SO22_HASH_SIZE : MC_SO21_HASH_SIZE) +/** Random size for current generated wrapping */ +#define MC_SO2X_RND_SIZE (SO_USE_VERSION_22 ? MC_SO22_RND_SIZE : MC_SO21_RND_SIZE) + +#if SO_USE_VERSION_22 + // #define MC_SO_ENCRYPT_PADDED_SIZE(netsize) netsize +#else + /** Calculates gross size of cryptogram within secure object including ISO padding bytes. */ + #define MC_SO_ENCRYPT_PADDED_SIZE(netsize) ( (netsize) + \ + MC_SO_MAX_PADDING_SIZE - (netsize) % MC_SO_MAX_PADDING_SIZE ) +#endif + /** Calculates the total size of a secure object. * @param plainLen Length of plain text part within secure object. @@ -154,10 +225,17 @@ typedef struct { * @return Total (gross) size of the secure object or 0 if given parameters are * illegal or would lead to a secure object of invalid size. */ -#define MC_SO_SIZE(plainLen, encryptedLen) ( \ - ((plainLen) + (encryptedLen) < (encryptedLen) || (plainLen) + (encryptedLen) > MC_SO_PAYLOAD_MAX_SIZE) ? 0 : \ - sizeof(mcSoHeader_t) + (plainLen) + MC_SO_ENCRYPT_PADDED_SIZE((encryptedLen) + MC_SO_HASH_SIZE) \ -) +#if SO_USE_VERSION_22 + #define MC_SO_SIZE(plainLen, encryptedLen) ( \ + ((plainLen) + (encryptedLen) < (encryptedLen) || (plainLen) + (encryptedLen) > MC_SO_PAYLOAD_MAX_SIZE) ? 0 : \ + sizeof(mcSoHeader_t) + (plainLen) + (encryptedLen) +MC_SO22_HASH_SIZE +MC_SO22_RND_SIZE \ + ) +#else + #define MC_SO_SIZE(plainLen, encryptedLen) ( \ + ((plainLen) + (encryptedLen) < (encryptedLen) || (plainLen) + (encryptedLen) > MC_SO_PAYLOAD_MAX_SIZE) ? 0 : \ + sizeof(mcSoHeader_t) + (plainLen) + MC_SO_ENCRYPT_PADDED_SIZE((encryptedLen) + MC_SO_HASH_SIZE) \ + ) +#endif #endif // MC_SO_H_ diff --git a/mobicore/daemon/Android.mk b/mobicore/daemon/Android.mk index 37a3fe3..9ec9a56 100644 --- a/mobicore/daemon/Android.mk +++ b/mobicore/daemon/Android.mk @@ -1,8 +1,112 @@ # ============================================================================= # -# Makefile pointing to all makefiles within the project. +# MobiCore Android build components # # ============================================================================= -APP_PROJECT_PATH := $(call my-dir) -# Including all Android.mk files from subdirectories -include $(call all-subdir-makefiles) + +LOCAL_PATH := $(call my-dir) + +# Client Library +# ============================================================================= +include $(CLEAR_VARS) +LOCAL_MODULE := libMcClient +LOCAL_MODULE_TAGS := optional +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) +#LOCAL_PRELINK_MODULE := false + +LOCAL_CFLAGS := -fvisibility=hidden -fvisibility-inlines-hidden +LOCAL_CFLAGS += -DLOG_TAG=\"McClient\" + +# Add new source files here +LOCAL_SRC_FILES += \ + ClientLib/Device.cpp \ + ClientLib/ClientLib.cpp \ + ClientLib/Session.cpp \ + Common/CMutex.cpp \ + Common/Connection.cpp + +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Common + +include $(LOCAL_PATH)/Kernel/Android.mk +# Import logwrapper +include $(LOG_WRAPPER)/Android.mk + +include $(BUILD_SHARED_LIBRARY) + +# Daemon Application +# ============================================================================= +include $(CLEAR_VARS) + +LOCAL_MODULE := mcDriverDaemon +LOCAL_MODULE_TAGS := optional +LOCAL_CFLAGS += -include buildTag.h +LOCAL_CFLAGS += -DLOG_TAG=\"McDaemon\" +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) + +include $(LOCAL_PATH)/Daemon/Android.mk + +# Common Source files required for building the daemon +LOCAL_SRC_FILES += Common/CMutex.cpp \ + Common/Connection.cpp \ + Common/NetlinkConnection.cpp \ + Common/CSemaphore.cpp \ + Common/CThread.cpp + +# Includes required for the Daemon +LOCAL_C_INCLUDES += $(LOCAL_PATH)/ClientLib/public \ + $(LOCAL_PATH)/Common + +# Common components +include $(LOCAL_PATH)/Kernel/Android.mk +include $(LOCAL_PATH)/Registry/Android.mk +# Logwrapper +include $(LOG_WRAPPER)/Android.mk + +include $(BUILD_EXECUTABLE) + +# Registry Shared Library +# ============================================================================= +include $(CLEAR_VARS) + +LOCAL_MODULE := libMcRegistry +LOCAL_MODULE_TAGS := optional +LOCAL_CFLAGS += -DLOG_TAG=\"McRegistry\" +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) +#LOCAL_PRELINK_MODULE := false + +LOCAL_C_INCLUDES += $(LOCAL_PATH)/ClientLib/public + +include $(LOCAL_PATH)/Registry/Android.mk + +# Import logwrapper +include $(LOG_WRAPPER)/Android.mk + +include $(BUILD_SHARED_LIBRARY) + + +# Provisioning Agent Shared Library +# ============================================================================= +include $(CLEAR_VARS) + +LOCAL_MODULE := libPaApi +LOCAL_MODULE_TAGS := optional +LOCAL_CFLAGS += -DLOG_TAG=\"PaApi\" +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) +#LOCAL_PRELINK_MODULE := false +LOCAL_C_INCLUDES += $(LOCAL_PATH)/ClientLib/public +include $(LOCAL_PATH)/PaApi/Android.mk + +# Import logwrapper +include $(LOG_WRAPPER)/Android.mk + +LOCAL_SHARED_LIBRARIES += libMcClient +include $(BUILD_SHARED_LIBRARY) + +# ============================================================================= +ifneq ($(filter-out Generic,$(PLATFORM)),) + $(call import-module,$(COMP_PATH_QualcommQSEEComAPI)) +endif diff --git a/mobicore/daemon/ClientLib/Android.mk b/mobicore/daemon/ClientLib/Android.mk index c2bf7e9..8081935 100644 --- a/mobicore/daemon/ClientLib/Android.mk +++ b/mobicore/daemon/ClientLib/Android.mk @@ -1,47 +1,7 @@ # ============================================================================= # -# Module: libMcClient.so -# -# C(version) Client Lib for Linux TLCs +# Module: libMcClient.so - Client Lib for TLC's # # ============================================================================= -LOCAL_PATH := $(call my-dir) -MY_CLIENTLIB_PATH := $(LOCAL_PATH) - -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcClient -LOCAL_MODULE_TAGS := eng -LOCAL_PRELINK_MODULE := false - -# External include files -LOCAL_C_INCLUDES += bionic \ - external/stlport/stlport - -# Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(LOCAL_PATH)/public \ - $(APP_PROJECT_PATH) \ - $(APP_PROJECT_PATH)/Daemon/public \ - $(APP_PROJECT_PATH)/Kernel \ - $(APP_PROJECT_PATH)/Kernel/Platforms/Generic \ - $(APP_PROJECT_PATH)/Common - -# Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(COMP_PATH_MobiCore)/inc \ - $(COMP_PATH_MobiCoreDriverMod)/Public - -# Add new source files here -LOCAL_SRC_FILES +=\ - Device.cpp\ - ClientLib.cpp\ - Session.cpp - -LOCAL_STATIC_LIBRARIES = libstlport_static libMcKernel libMcCommon - -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions -include $(COMP_PATH_Logwrapper)/Android.mk - -include $(BUILD_SHARED_LIBRARY) +LOCAL_PATH := $(call my-dir) diff --git a/mobicore/daemon/ClientLib/ClientLib.cpp b/mobicore/daemon/ClientLib/ClientLib.cpp index 9b6c5df..efa976f 100644 --- a/mobicore/daemon/ClientLib/ClientLib.cpp +++ b/mobicore/daemon/ClientLib/ClientLib.cpp @@ -8,7 +8,7 @@ * Handles sessions and notifications via MCI buffer. * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -36,11 +36,11 @@ #include <stdint.h> #include <stdbool.h> #include <list> -#include <cassert> +#include "assert.h" #include "public/MobiCoreDriverApi.h" -#include "mc_drv_module_api.h" +#include "mc_linux.h" #include "Connection.h" #include "CMutex.h" #include "Device.h" @@ -49,7 +49,6 @@ #include "Daemon/public/MobiCoreDriverCmd.h" #include "Daemon/public/mcVersion.h" -#define LOG_TAG "McClient" #include "log.h" MC_CHECK_VERSION(DAEMON, 0, 2); @@ -65,79 +64,120 @@ using namespace std; list<Device*> devices; // Forward declarations. -static uint32_t getDaemonVersion(Connection* devCon); +uint32_t getDaemonVersion(Connection* devCon); +CMutex devMutex; //------------------------------------------------------------------------------ -static Device *resolveDeviceId( - uint32_t deviceId -) { - Device *ret = NULL; - - // Get Session for sessionId - for (list<Device*>::iterator iterator = devices.begin(); - iterator != devices.end(); - ++iterator) - { +Device *resolveDeviceId(uint32_t deviceId) +{ + for (list<Device*>::iterator iterator = devices.begin(); + iterator != devices.end(); ++iterator) { Device *device = (*iterator); - if (device->deviceId == deviceId) - { - ret = device; - break; + if (device->deviceId == deviceId) { + return device; } } - return ret; + return NULL; } //------------------------------------------------------------------------------ -static void addDevice( - Device *device -) { +void addDevice(Device *device) +{ devices.push_back(device); } //------------------------------------------------------------------------------ -static bool removeDevice( - uint32_t deviceId -) { - bool ret = false; - +bool removeDevice(uint32_t deviceId) +{ for (list<Device*>::iterator iterator = devices.begin(); iterator != devices.end(); ++iterator) { Device *device = (*iterator); - if (device->deviceId == deviceId) - { + if (device->deviceId == deviceId) { devices.erase(iterator); delete device; - ret = true; - break; + return true; } } - return ret; + return false; } +//------------------------------------------------------------------------------ +// Parameter checking functions +// Note that android-ndk renames __func__ to __PRETTY_FUNCTION__ +// see also /prebuilt/ndk/android-ndk-r4/platforms/android-8/arch-arm/usr/include/sys/cdefs.h + +#define CHECK_DEVICE(device) \ + if (NULL == device) \ + { \ + LOG_E("Device not found"); \ + mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; \ + break; \ + } + +#define CHECK_NOT_NULL(X) \ + if (NULL == X) \ + { \ + LOG_E("Parameter \""#X "\" is NULL"); \ + mcResult = MC_DRV_ERR_INVALID_PARAMETER; \ + break; \ + } + +#define CHECK_SESSION(S,SID) \ + if (NULL == S) \ + { \ + LOG_E("Session %i not found", SID); \ + mcResult = MC_DRV_ERR_UNKNOWN_SESSION; \ + break; \ + } //------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcOpenDevice( - uint32_t deviceId -) { +// Socket marshaling and checking functions +#define SEND_TO_DAEMON(CONNECTION, COMMAND, ...) \ +{ \ + COMMAND ##_struct x = { \ + COMMAND, \ + __VA_ARGS__ \ + }; \ + int ret = CONNECTION->writeData(&x, sizeof x); \ + if(ret < 0) { \ + LOG_E("%s sending to Daemon failed.",__FUNCTION__); \ + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; \ + break; \ + } \ +} +#define RECV_FROM_DAEMON(CONNECTION, RSP_STRUCT) \ +{ \ + int ret = CONNECTION->readData( \ + RSP_STRUCT, \ + sizeof(*RSP_STRUCT)); \ + if (ret < 0) \ + { \ + LOG_E("%s(): reading from Daemon failed", __FUNCTION__); \ + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; \ + break; \ + } \ +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcOpenDevice(uint32_t deviceId) +{ mcResult_t mcResult = MC_DRV_OK; - static CMutex mutex; + Connection *devCon = NULL; - mutex.lock(); // Enter critical section + devMutex.lock(); + LOG_I("===%s(%i)===", __FUNCTION__, deviceId); - do - { + do { Device *device = resolveDeviceId(deviceId); - if (NULL != device) - { - LOG_E("mcOpenDevice(): Device %d already opened", deviceId); + if (device != NULL) { + LOG_E("Device %d already opened", deviceId); mcResult = MC_DRV_ERR_INVALID_OPERATION; break; } @@ -146,7 +186,7 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenDevice( devCon = new Connection(); if (!devCon->connect(SOCK_PATH)) { - LOG_E("mcOpenDevice(): Could not connect to %s", SOCK_PATH); + LOG_W(" Could not connect to %s socket", SOCK_PATH); mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; break; } @@ -158,54 +198,27 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenDevice( mcResult = MC_DRV_ERR_DAEMON_VERSION; break; } - LOG_I("%s", errmsg); + LOG_I(" %s", errmsg); // Forward device open to the daemon and read result - mcDrvCmdOpenDevice_t mcDrvCmdOpenDevice = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_OPEN_DEVICE - }, - /* .payload = */ { - /* .deviceId = */ deviceId - } - }; + SEND_TO_DAEMON(devCon, MC_DRV_CMD_OPEN_DEVICE, deviceId); - int len = devCon->writeData( - &mcDrvCmdOpenDevice, - sizeof(mcDrvCmdOpenDevice)); - if (len < 0) - { - LOG_E("mcOpenDevice(): CMD_OPEN_DEVICE writeCmd failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - mcDrvResponseHeader_t rspHeader; - len = devCon->readData( - &rspHeader, - sizeof(rspHeader)); - if (len != sizeof(rspHeader)) - { - LOG_E("mcOpenDevice(): CMD_OPEN_DEVICE readRsp failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } - if (MC_DRV_RSP_OK != rspHeader.responseId) - { - LOG_E("mcOpenDevice(): CMD_OPEN_DEVICE failed, respId=%d", rspHeader.responseId); - switch(rspHeader.responseId) - { + if (responseId != MC_DRV_RSP_OK) { + LOG_W(" %s(): Request at Daemon failed, respId=%d ", __FUNCTION__, responseId); + switch(responseId) { case MC_DRV_RSP_PAYLOAD_LENGTH_ERROR: - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; + break; case MC_DRV_INVALID_DEVICE_NAME: - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; + mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; + break; case MC_DRV_RSP_DEVICE_ALREADY_OPENED: default: - mcResult = MC_DRV_ERR_INVALID_OPERATION; - break; + mcResult = MC_DRV_ERR_INVALID_OPERATION; + break; } break; } @@ -213,12 +226,11 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenDevice( // there is no payload to read device = new Device(deviceId, devCon); - if (!device->open(MC_DRV_MOD_DEVNODE_FULLPATH)) - { + if (!device->open("/dev/" MC_USER_DEVNODE)) { delete device; // devCon is freed in the Device destructor devCon = NULL; - LOG_E("mcOpenDevice(): could not open device file: %s", MC_DRV_MOD_DEVNODE_FULLPATH); + LOG_E("mcOpenDevice(): could not open device file: /dev/%s", MC_USER_DEVNODE); mcResult = MC_DRV_ERR_INVALID_DEVICE_FILE; break; } @@ -226,13 +238,15 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenDevice( addDevice(device); } while (false); - - if (mcResult != MC_DRV_OK && devCon != NULL) - { - delete devCon; - } - mutex.unlock(); // Exit critical section + devMutex.unlock(); + if (mcResult != MC_DRV_OK) { + if (devCon != NULL) + delete devCon; + LOG_I(" Device not opened."); + } else { + LOG_I(" Successfully opened the device."); + } return mcResult; } @@ -243,58 +257,28 @@ __MC_CLIENT_LIB_API mcResult_t mcCloseDevice( uint32_t deviceId ) { mcResult_t mcResult = MC_DRV_OK; - static CMutex mutex; - - mutex.lock(); // Enter critical section - do - { + devMutex.lock(); + LOG_I("===%s(%i)===", __FUNCTION__, deviceId); + do { Device *device = resolveDeviceId(deviceId); - if (NULL == device) - { - LOG_E("mcCloseDevice(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + CHECK_DEVICE(device); + Connection *devCon = device->connection; // Return if not all sessions have been closed - if (device->hasSessions()) - { - LOG_E("mcCloseDevice(): cannot close with sessions still pending"); + if (device->hasSessions()) { + LOG_E("Trying to close device while sessions are still pending."); mcResult = MC_DRV_ERR_SESSION_PENDING; break; } - mcDrvCmdCloseDevice_t mcDrvCmdCloseDevice = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_CLOSE_DEVICE - } - }; - int len = devCon->writeData( - &mcDrvCmdCloseDevice, - sizeof(mcDrvCmdCloseDevice)); - // ignore error, but log details - if (len < 0) - { - LOG_E("mcCloseDevice(): CMD_CLOSE_DEVICE writeCmd failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - } + SEND_TO_DAEMON(devCon, MC_DRV_CMD_CLOSE_DEVICE); - mcDrvResponseHeader_t rspHeader; - len = devCon->readData( - &rspHeader, - sizeof(rspHeader)); - if (len != sizeof(rspHeader)) - { - LOG_E("mcCloseDevice(): CMD_CLOSE_DEVICE readResp failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - if (MC_DRV_RSP_OK != rspHeader.responseId) - { - LOG_E("mcCloseDevice(): CMD_CLOSE_DEVICE failed, respId=%d", rspHeader.responseId); + if (responseId != MC_DRV_RSP_OK) { + LOG_E("mcCloseDevice(): CMD_CLOSE_DEVICE failed, respId=%d", responseId); mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; break; } @@ -303,8 +287,7 @@ __MC_CLIENT_LIB_API mcResult_t mcCloseDevice( } while (false); - mutex.unlock(); // Exit critical section - + devMutex.unlock(); return mcResult; } @@ -317,45 +300,26 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( uint32_t len ) { mcResult_t mcResult = MC_DRV_OK; - static CMutex mutex; - mutex.lock(); // Enter critical section + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + do { + CHECK_NOT_NULL(session); + CHECK_NOT_NULL(uuid); + CHECK_NOT_NULL(tci); - do - { - if (NULL == session) - { - LOG_E("mcOpenSession(): Session is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (NULL == uuid) - { - LOG_E("mcOpenSession(): UUID is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (NULL == tci) - { - LOG_E("mcOpenSession(): TCI is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } if (len > MC_MAX_TCI_LEN) { - LOG_E("mcOpenSession(): TCI length is longer than %d", MC_MAX_TCI_LEN); + LOG_E("TCI length is longer than %d", MC_MAX_TCI_LEN); mcResult = MC_DRV_ERR_INVALID_PARAMETER; break; } // Get the device associated with the given session Device *device = resolveDeviceId(session->deviceId); - if (NULL == device) - { - LOG_E("mcOpenSession(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + CHECK_DEVICE(device); + Connection *devCon = device->connection; // Get the physical address of the given TCI @@ -367,57 +331,25 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( break; } - if (pWsm->len < len) - { + if (pWsm->len < len) { LOG_E("mcOpenSession(): length is more than allocated TCI"); mcResult = MC_DRV_ERR_INVALID_PARAMETER; break; } - // Prepare open session command - mcDrvCmdOpenSession_t cmdOpenSession = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_OPEN_SESSION - }, - /* .payload = */ { - /* .deviceId = */ session->deviceId, - /* .uuid = */ *uuid, - /* .tci = */ (uint32_t)pWsm->physAddr, - /* .len = */ len - } - }; - - // Transmit command data - - int len = devCon->writeData( - &cmdOpenSession, - sizeof(cmdOpenSession)); - if (sizeof(cmdOpenSession) != len) - { - LOG_E("mcOpenSession(): CMD_OPEN_SESSION writeData failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + SEND_TO_DAEMON(devCon, MC_DRV_CMD_OPEN_SESSION, + session->deviceId, + *uuid, + (uint32_t)pWsm->physAddr, + len); // Read command response + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - // read header first - mcDrvResponseHeader_t rspHeader; - len = devCon->readData( - &rspHeader, - sizeof(rspHeader)); - if (sizeof(rspHeader) != len) - { - LOG_E("mcOpenSession(): CMD_OPEN_SESSION readResp failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } - - if (MC_DRV_RSP_OK != rspHeader.responseId) - { - LOG_E("mcOpenSession(): CMD_OPEN_SESSION failed, respId=%d", rspHeader.responseId); - switch(rspHeader.responseId) + if (responseId != MC_DRV_RSP_OK) { + LOG_E("Daemon reported failing of OPEN SESSION command, responseId %d.", responseId); + switch(responseId) { case MC_DRV_RSP_WRONG_PUBLIC_KEY: mcResult = MC_DRV_ERR_WRONG_PUBLIC_KEY; @@ -444,14 +376,13 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( mcResult = MC_DRV_ERR_UNWRAP_TRUSTLET_FAILED; break; case MC_DRV_RSP_TRUSTLET_NOT_FOUND: - mcResult = MC_DRV_ERR_INVALID_DEVICE_FILE; - break; + mcResult = MC_DRV_ERR_INVALID_DEVICE_FILE; + break; case MC_DRV_RSP_PAYLOAD_LENGTH_ERROR: case MC_DRV_RSP_DEVICE_NOT_OPENED: case MC_DRV_RSP_FAILED: default: - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; } break; @@ -459,19 +390,13 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( // read payload mcDrvRspOpenSessionPayload_t rspOpenSessionPayload; - len = devCon->readData( - &rspOpenSessionPayload, - sizeof(rspOpenSessionPayload)); - if (sizeof(rspOpenSessionPayload) != len) - { - LOG_E("mcOpenSession(): CMD_OPEN_SESSION readPayload failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + RECV_FROM_DAEMON(devCon, &rspOpenSessionPayload); // Register session with handle session->sessionId = rspOpenSessionPayload.sessionId; + LOG_I(" Service is started. Setting up channel for notifications."); + // Set up second channel for notifications Connection *sessionConnection = new Connection(); if (!sessionConnection->connect(SOCK_PATH)) @@ -482,125 +407,73 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( break; } - //TODO CONTINOUE HERE !!!! FIX RW RETURN HANDLING!!!! - - // Write command to use channel for notifications - mcDrvCmdNqConnect_t cmdNqConnect = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_NQ_CONNECT - }, - /* .payload = */ { - /* .deviceId = */ session->deviceId, - /* .sessionId = */ session->sessionId, - /* .deviceSessionId = */ rspOpenSessionPayload.deviceSessionId, - /* .sessionMagic = */ rspOpenSessionPayload.sessionMagic - } - }; - sessionConnection->writeData( - &cmdNqConnect, - sizeof(cmdNqConnect)); - - - // Read command response, header first - len = sessionConnection->readData( - &rspHeader, - sizeof(rspHeader)); - if (sizeof(rspHeader) != len) - { - LOG_E("mcOpenSession(): CMD_NQ_CONNECT readRsp failed, ret=%d", len); - delete sessionConnection; - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + do { + SEND_TO_DAEMON(sessionConnection, MC_DRV_CMD_NQ_CONNECT, + session->deviceId, + session->sessionId, + rspOpenSessionPayload.deviceSessionId, + rspOpenSessionPayload.sessionMagic); - if (MC_DRV_RSP_OK != rspHeader.responseId) - { - LOG_E("mcOpenSession(): CMD_NQ_CONNECT failed, respId=%d", rspHeader.responseId); + uint32_t responseId; + RECV_FROM_DAEMON(sessionConnection, &responseId); + + if (MC_DRV_RSP_OK != responseId) + { + LOG_E("mcOpenSession(): CMD_NQ_CONNECT failed, respId=%d", responseId); + mcResult = MC_DRV_ERR_NQ_FAILED; + break; + } + + } while (0); + if (MC_DRV_OK != mcResult) { delete sessionConnection; - mcResult = MC_DRV_ERR_NQ_FAILED; break; } // there is no payload. // Session has been established, new session object must be created - device->createNewSession( - session->sessionId, - sessionConnection); + device->createNewSession(session->sessionId, sessionConnection); - } while (false); + LOG_I(" Successfully opened session %d.", session->sessionId); - mutex.unlock(); // Exit critical section + } while (false); + devMutex.unlock(); return mcResult; } //------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcCloseSession( - mcSessionHandle_t *session -) { +__MC_CLIENT_LIB_API mcResult_t mcCloseSession(mcSessionHandle_t *session) +{ mcResult_t mcResult = MC_DRV_OK; - static CMutex mutex; - - mutex.lock(); // Enter critical section + LOG_I("===%s()===", __FUNCTION__); + devMutex.lock(); do { - if (NULL == session) - { - LOG_E("mcCloseSession(): Session is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + CHECK_NOT_NULL(session); + LOG_I(" Closing session %d.", session->sessionId); - Device *device = resolveDeviceId(session->deviceId); - if (NULL == device) - { - LOG_E("mcCloseSession(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - Connection *devCon = device->connection; + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); - Session *nqSession = device->resolveSessionId(session->sessionId); - if (NULL == nqSession) - { - LOG_E("mcCloseSession(): Session not found"); - mcResult = MC_DRV_ERR_UNKNOWN_SESSION; - break; - } + Connection *devCon = device->connection; - // Write close session command - mcDrvCmdCloseSession_t cmdCloseSession = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_CLOSE_SESSION - }, - /* .payload = */ { - /* .sessionId = */ session->sessionId, - } - }; - devCon->writeData( - &cmdCloseSession, - sizeof(cmdCloseSession)); + Session *nqSession = device->resolveSessionId(session->sessionId); - // Read command response - mcDrvResponseHeader_t rspHeader; - int len = devCon->readData( - &rspHeader, - sizeof(rspHeader)); - if (sizeof(rspHeader) != len) - { - LOG_E("mcCloseSession(): CMD_CLOSE_SESSION readRsp failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + CHECK_SESSION(nqSession, session->sessionId); + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_CLOSE_SESSION, session->sessionId); + + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - if (MC_DRV_RSP_OK != rspHeader.responseId) + if (MC_DRV_RSP_OK != responseId) { - LOG_E("mcCloseSession(): CMD_CLOSE_SESSION failed, respId=%d", rspHeader.responseId); + LOG_E("mcCloseSession(): CMD_CLOSE_SESSION failed, respId=%d", responseId); + // TODO-2012-08-03-haenellu: Think about better error codes here. mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; break; } @@ -610,8 +483,7 @@ __MC_CLIENT_LIB_API mcResult_t mcCloseSession( mcResult = MC_DRV_OK; } while (false); - - mutex.unlock(); // Exit critical section + devMutex.unlock(); return mcResult; } @@ -622,53 +494,26 @@ __MC_CLIENT_LIB_API mcResult_t mcNotify( mcSessionHandle_t *session ) { mcResult_t mcResult = MC_DRV_OK; - - LOG_I("===%s()===", __func__); + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); - do - { - if (NULL == session) - { - LOG_E("mcNotify(): Session is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + do { + CHECK_NOT_NULL(session); + LOG_I(" Notifying session %d.", session->sessionId); Device *device = resolveDeviceId(session->deviceId); - if (NULL == device) - { - LOG_E("mcNotify(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - Connection *devCon = device->connection; - - Session *nqsession = device->resolveSessionId(session->sessionId); - if (NULL == nqsession) - { - LOG_E("mcNotify(): Session not found"); - mcResult = MC_DRV_ERR_UNKNOWN_SESSION; - break; - } + CHECK_DEVICE(device); - mcDrvCmdNotify_t cmdNotify = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_NOTIFY - }, - /* .payload = */ { - /* .sessionId = */ session->sessionId, - } - }; + Connection *devCon = device->connection; - devCon->writeData( - &cmdNotify, - sizeof(cmdNotify)); + Session *nqsession = device->resolveSessionId(session->sessionId); + CHECK_SESSION(nqsession, session->sessionId); + SEND_TO_DAEMON(devCon, MC_DRV_CMD_NOTIFY, session->sessionId); // Daemon will not return a response - } while(false); + devMutex.unlock(); return mcResult; } @@ -679,32 +524,20 @@ __MC_CLIENT_LIB_API mcResult_t mcWaitNotification( int32_t timeout ) { mcResult_t mcResult = MC_DRV_OK; - - LOG_I("===%s()===", __func__); + + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); do { - if (NULL == session) - { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + CHECK_NOT_NULL(session); + LOG_I(" Waiting for notification of session %d.", session->sessionId); - Device *device = resolveDeviceId(session->deviceId); - if (NULL == device) - { - LOG_E("mcWaitNotification(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); Session *nqSession = device->resolveSessionId(session->sessionId); - if (NULL == nqSession) - { - LOG_E("mcWaitNotification(): Session not found"); - mcResult = MC_DRV_ERR_UNKNOWN_SESSION; - break; - } + CHECK_SESSION(nqSession, session->sessionId); Connection * nqconnection = nqSession->notificationConnection; uint32_t count = 0; @@ -719,9 +552,8 @@ __MC_CLIENT_LIB_API mcResult_t mcWaitNotification( timeout); //Exit on timeout in first run //Later runs have timeout set to 0. -2 means, there is no more data. - if (0 == count && -2 == numRead) - { - LOG_E("mcWaitNotification(): read timeout"); + if (count == 0 && numRead == -2 ) { + LOG_W("Timeout hit at %s", __FUNCTION__); mcResult = MC_DRV_ERR_TIMEOUT; break; } @@ -729,30 +561,25 @@ __MC_CLIENT_LIB_API mcResult_t mcWaitNotification( // no timeout for the following reads timeout = 0; - if (numRead != sizeof(notification_t)) - { - if (0 == count) - { - //failure in first read, notify it + if (numRead != sizeof(notification_t)) { + if (count == 0) { + //failure in first read, notify it mcResult = MC_DRV_ERR_NOTIFICATION; LOG_E("mcWaitNotification(): read notification failed, %i bytes received", (int)numRead); break; - } - else - { - // Read of the n-th notification failed/timeout. We don't tell the - // caller, as we got valid notifications before. - mcResult = MC_DRV_OK; - break; + } else { + // Read of the n-th notification failed/timeout. We don't tell the + // caller, as we got valid notifications before. + mcResult = MC_DRV_OK; + break; } } count++; - LOG_I("mcWaitNotification(): readNq count=%d, SessionID=%d, Payload=%d", + LOG_I(" Received notification %d for session %d, payload=%d", count, notification.sessionId, notification.payload); - if (0 != notification.payload) - { + if (notification.payload != 0) { // Session end point died -> store exit code nqSession->setErrorInfo(notification.payload); @@ -763,6 +590,7 @@ __MC_CLIENT_LIB_API mcResult_t mcWaitNotification( } while (false); + devMutex.unlock(); return mcResult; } @@ -773,34 +601,23 @@ __MC_CLIENT_LIB_API mcResult_t mcMallocWsm( uint32_t align, uint32_t len, uint8_t **wsm, - uint32_t wsmFlags -) { + uint32_t wsmFlags) +{ mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - static CMutex mutex; - LOG_I("===%s()===", __func__); + LOG_I("===%s(len=%i)===", __FUNCTION__, len); - mutex.lock(); // Enter critical section + devMutex.lock(); - do - { + do { Device *device = resolveDeviceId(deviceId); - if (NULL == device) - { - LOG_E("mcMallocWsm(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if(NULL == wsm) - { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + CHECK_DEVICE(device); + + CHECK_NOT_NULL(wsm); CWsm_ptr pWsm = device->allocateContiguousWsm(len); - if (NULL == pWsm) - { - LOG_E("mcMallocWsm(): Allocation of WSM failed"); + if (pWsm == NULL) { + LOG_W(" Allocation of WSM failed"); mcResult = MC_DRV_ERR_NO_FREE_MEMORY; break; } @@ -810,7 +627,7 @@ __MC_CLIENT_LIB_API mcResult_t mcMallocWsm( } while (false); - mutex.unlock(); // Exit critical section + devMutex.unlock(); return mcResult; } @@ -824,28 +641,21 @@ __MC_CLIENT_LIB_API mcResult_t mcFreeWsm( mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; Device *device; - static CMutex mutex; + devMutex.lock(); - LOG_I("===%s()===", __func__); - - mutex.lock(); // Enter critical section + LOG_I("===%s(%p)===", __FUNCTION__, wsm); do { // Get the device associated wit the given session device = resolveDeviceId(deviceId); - if (NULL == device) - { - LOG_E("mcFreeWsm(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + CHECK_DEVICE(device); // find WSM object CWsm_ptr pWsm = device->findContiguousWsm(wsm); if (NULL == pWsm) { - LOG_E("mcFreeWsm(): unknown address"); + LOG_E("address is unknown to mcFreeWsm"); mcResult = MC_DRV_ERR_INVALID_PARAMETER; break; } @@ -861,7 +671,7 @@ __MC_CLIENT_LIB_API mcResult_t mcFreeWsm( } while (false); - mutex.unlock(); // Exit critical section + devMutex.unlock(); return mcResult; } @@ -876,106 +686,55 @@ __MC_CLIENT_LIB_API mcResult_t mcMap( mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; static CMutex mutex; - mutex.lock(); // Enter critical section + LOG_I("===%s()===", __FUNCTION__); - do - { - if (NULL == sessionHandle) - { - LOG_E("mcMap(): sessionHandle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (NULL == mapInfo) - { - LOG_E("mcMap(): mapInfo is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (NULL == buf) - { - LOG_E("mcMap(): buf is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + devMutex.lock(); + + do { + CHECK_NOT_NULL(sessionHandle); + CHECK_NOT_NULL(mapInfo); + CHECK_NOT_NULL(buf); // Determine device the session belongs to Device *device = resolveDeviceId(sessionHandle->deviceId); - if (NULL == device) { - LOG_E("mcMap(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + CHECK_DEVICE(device); + Connection *devCon = device->connection; // Get session Session *session = device->resolveSessionId(sessionHandle->sessionId); - if (NULL == session) - { - LOG_E("mcMap(): Session not found"); - mcResult = MC_DRV_ERR_UNKNOWN_SESSION; - break; - } + CHECK_SESSION(session, sessionHandle->sessionId); - // Workaround Linux memory handling - if (NULL != buf) - { - for (uint32_t i = 0; i < bufLen; i += 4096) { - volatile uint8_t x = ((uint8_t *) buf)[i]; x = x; - } - } + LOG_I(" Mapping %p to session %d.", buf, sessionHandle->sessionId); // Register mapped bulk buffer to Kernel Module and keep mapped bulk buffer in mind BulkBufferDescriptor *bulkBuf = session->addBulkBuf(buf, bufLen); - if (NULL == bulkBuf) - { - LOG_E("mcMap(): Error mapping bulk buffer"); + if (bulkBuf == NULL) { + LOG_E("Registering buffer failed."); mcResult = MC_DRV_ERR_BULK_MAPPING; break; } - - // Prepare map command - mcDrvCmdMapBulkMem_t mcDrvCmdMapBulkMem = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_MAP_BULK_BUF - }, - /* .payload = */ { - /* .sessionId = */ session->sessionId, - /* .pAddrL2 = */ (uint32_t)bulkBuf->physAddrWsmL2, - /* .offsetPayload = */ (uint32_t)(bulkBuf->virtAddr) & 0xFFF, - /* .lenBulkMem = */ bulkBuf->len - } - }; - - // Transmit map command to MobiCore device - devCon->writeData( - &mcDrvCmdMapBulkMem, - sizeof(mcDrvCmdMapBulkMem)); + SEND_TO_DAEMON(devCon, MC_DRV_CMD_MAP_BULK_BUF, + session->sessionId, + (uint32_t)bulkBuf->physAddrWsmL2, + (uint32_t)(bulkBuf->virtAddr) & 0xFFF, + bulkBuf->len); // Read command response - mcDrvResponseHeader_t rspHeader; - int len = devCon->readData( - &rspHeader, - sizeof(rspHeader)); - if (sizeof(rspHeader) != len) - { - LOG_E("mcMap(): CMD_MAP_BULK_BUF readRsp failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - if (MC_DRV_RSP_OK != rspHeader.responseId) + if (responseId != MC_DRV_RSP_OK) { - LOG_E("mcMap(): CMD_MAP_BULK_BUF failed, respId=%d", rspHeader.responseId); + LOG_E("mcMap(): CMD_MAP_BULK_BUF failed, respId=%d", responseId); // REV We ignore Daemon Error code because client cannot handle it anyhow. + // TODO-2012-08-03-haenellu: Think about better error codes here. mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; // Unregister mapped bulk buffer from Kernel Module and remove mapped // bulk buffer from session maintenance - if (!session->removeBulkBuf(buf)) - { + if (!session->removeBulkBuf(buf)) { // Removing of bulk buffer not possible LOG_E("mcMap(): Unregistering of bulk memory from Kernel Module failed"); } @@ -983,9 +742,7 @@ __MC_CLIENT_LIB_API mcResult_t mcMap( } mcDrvRspMapBulkMemPayload_t rspMapBulkMemPayload; - devCon->readData( - &rspMapBulkMemPayload, - sizeof(rspMapBulkMemPayload)); + RECV_FROM_DAEMON(devCon, &rspMapBulkMemPayload); // Set mapping info for Trustlet mapInfo->sVirtualAddr = (void *) (rspMapBulkMemPayload.secureVirtualAdr); @@ -994,7 +751,7 @@ __MC_CLIENT_LIB_API mcResult_t mcMap( } while (false); - mutex.unlock(); // Exit critical section + devMutex.unlock(); return mcResult; } @@ -1008,91 +765,45 @@ __MC_CLIENT_LIB_API mcResult_t mcUnmap( mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; static CMutex mutex; - LOG_I("===%s()===", __func__); + LOG_I("===%s()===", __FUNCTION__); - mutex.lock(); // Enter critical section + devMutex.lock(); do { - if (NULL == sessionHandle) - { - LOG_E("mcUnmap(): sessionHandle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (NULL == mapInfo) - { - LOG_E("mcUnmap(): mapInfo is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (NULL == buf) - { - LOG_E("mcUnmap(): buf is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + CHECK_NOT_NULL(sessionHandle); + CHECK_NOT_NULL(mapInfo); + CHECK_NOT_NULL(buf); // Determine device the session belongs to Device *device = resolveDeviceId(sessionHandle->deviceId); - if (NULL == device) - { - LOG_E("mcUnmap(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + CHECK_DEVICE(device); + Connection *devCon = device->connection; // Get session Session *session = device->resolveSessionId(sessionHandle->sessionId); - if (NULL == session) - { - LOG_E("mcUnmap(): Session not found"); - mcResult = MC_DRV_ERR_UNKNOWN_SESSION; - break; - } + CHECK_SESSION(session, sessionHandle->sessionId); - // Prepare unmap command - mcDrvCmdUnmapBulkMem_t cmdUnmapBulkMem = { - // C++ does not support C99 designated initializers - /* .header = */ { - /* .commandId = */ MC_DRV_CMD_UNMAP_BULK_BUF - }, - /* .payload = */ { - /* .sessionId = */ session->sessionId, - /* .secureVirtualAdr = */ (uint32_t)(mapInfo->sVirtualAddr), - /* .lenBulkMem = mapInfo->sVirtualLen*/ - } - }; - - devCon->writeData( - &cmdUnmapBulkMem, - sizeof(cmdUnmapBulkMem)); + LOG_I(" Unmapping %p from session %d.", buf, sessionHandle->sessionId); - // Read command response - mcDrvResponseHeader_t rspHeader; - int len = devCon->readData( - &rspHeader, - sizeof(rspHeader)); - if (sizeof(rspHeader) != len) - { - LOG_E("mcUnmap(): CMD_UNMAP_BULK_BUF readRsp failed, ret=%d", len); - mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; - break; - } + SEND_TO_DAEMON(devCon, MC_DRV_CMD_UNMAP_BULK_BUF, + session->sessionId, + (uint32_t)(mapInfo->sVirtualAddr)); + + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - if (MC_DRV_RSP_OK != rspHeader.responseId) + if (MC_DRV_RSP_OK != responseId) { - LOG_E("mcUnmap(): CMD_UNMAP_BULK_BUF failed, respId=%d", rspHeader.responseId); - // REV We ignore Daemon Error code because client cannot handle it anyhow. + LOG_E("Daemon reported failing of UNMAP BULK BUF command, responseId %d.", responseId); + // TODO-2012-08-03-haenellu: Think about better error codes here. mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; break; } mcDrvRspUnmapBulkMemPayload_t rspUnmapBulkMemPayload; - devCon->readData( - &rspUnmapBulkMemPayload, - sizeof(rspUnmapBulkMemPayload)); + RECV_FROM_DAEMON(devCon, &rspUnmapBulkMemPayload); // REV axh: what about check the payload? @@ -1101,7 +812,8 @@ __MC_CLIENT_LIB_API mcResult_t mcUnmap( if (!session->removeBulkBuf(buf)) { // Removing of bulk buffer not possible - LOG_E("mcUnmap(): Unregistering of bulk memory from Kernel Module failed"); + // TODO-2012-08-03-haenellu: Think about better error codes here. + LOG_E("Unregistering of bulk memory from Kernel Module failed."); mcResult = MC_DRV_ERR_BULK_UNMAPPING; break; } @@ -1110,7 +822,7 @@ __MC_CLIENT_LIB_API mcResult_t mcUnmap( } while (false); - mutex.unlock(); // Exit critical section + devMutex.unlock(); return mcResult; } @@ -1122,40 +834,28 @@ __MC_CLIENT_LIB_API mcResult_t mcGetSessionErrorCode( int32_t *lastErr ) { mcResult_t mcResult = MC_DRV_OK; - - LOG_I("===%s()===", __func__); - do - { - if (NULL == session || NULL == lastErr) - { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + do { + CHECK_NOT_NULL(session); + CHECK_NOT_NULL(lastErr); // Get device Device *device = resolveDeviceId(session->deviceId); - if (NULL == device) - { - LOG_E("mcGetSessionErrorCode(): Device not found"); - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } + CHECK_DEVICE(device); // Get session Session *nqsession = device->resolveSessionId(session->sessionId); - if (NULL == nqsession) - { - LOG_E("mcGetSessionErrorCode(): Session not found"); - mcResult = MC_DRV_ERR_UNKNOWN_SESSION; - break; - } + CHECK_SESSION(nqsession, session->sessionId); // get session error code from session *lastErr = nqsession->getLastErr(); } while (false); + devMutex.unlock(); return mcResult; } @@ -1176,103 +876,74 @@ __MC_CLIENT_LIB_API mcResult_t mcGetMobiCoreVersion( ) { mcResult_t mcResult = MC_DRV_OK; - Device* device = resolveDeviceId(deviceId); - if (NULL == device) { - LOG_E("mcGetMobiCoreVersion(): Device not found"); - return MC_DRV_ERR_UNKNOWN_DEVICE; - } + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); - if (NULL == versionInfo) { - return MC_DRV_ERR_INVALID_PARAMETER; - } + do { + Device* device = resolveDeviceId(deviceId); - Connection* devCon = device->connection; + CHECK_DEVICE(device); + CHECK_NOT_NULL(versionInfo); - mcDrvCmdGetMobiCoreVersion_t mcDrvCmdGetMobiCoreVersion = { - { - MC_DRV_CMD_GET_MOBICORE_VERSION, - } - }; - int len = devCon->writeData( - &mcDrvCmdGetMobiCoreVersion, - sizeof(mcDrvCmdGetMobiCoreVersion)); - - if (len < 0) { - LOG_E("mcGetMobiCoreVersion(): MC_DRV_CMD_GET_MOBICORE_VERSION writeCmd failed, ret=%d", len); - return MC_DRV_ERR_DAEMON_UNREACHABLE; - } + Connection* devCon = device->connection; - // Read GET MOBICORE VERSION response. + SEND_TO_DAEMON(devCon, MC_DRV_CMD_GET_MOBICORE_VERSION); - // Read header first. - mcDrvResponseHeader_t rspHeader; - len = devCon->readData(&rspHeader, sizeof(rspHeader)); - if (sizeof(rspHeader) != len) { - LOG_E("mcGetMobiCoreVersion(): MC_DRV_CMD_GET_MOBICORE_VERSION failed to respond, ret=%d", len); - return MC_DRV_ERR_DAEMON_UNREACHABLE; - } + // Read GET MOBICORE VERSION response. - if (MC_DRV_RSP_OK != rspHeader.responseId) { - LOG_E("mcGetMobiCoreVersion(): MC_DRV_CMD_GET_MOBICORE_VERSION bad response, respId=%d", rspHeader.responseId); - return MC_DRV_ERR_DAEMON_UNREACHABLE; - } + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - // Read payload. - mcDrvRspGetMobiCoreVersionPayload_t rspGetMobiCoreVersionPayload; - len = devCon->readData(&rspGetMobiCoreVersionPayload, sizeof(rspGetMobiCoreVersionPayload)); - if (sizeof(rspGetMobiCoreVersionPayload) != len) { - LOG_E("mcGetMobiCoreVersion(): MC_DRV_CMD_GET_MOBICORE_VERSION readPayload failed, ret=%d", len); - return MC_DRV_ERR_DAEMON_UNREACHABLE; - } + if (MC_DRV_RSP_OK != responseId) { + LOG_E("mcGetMobiCoreVersion(): MC_DRV_CMD_GET_MOBICORE_VERSION bad response, respId=%d", responseId); + return MC_DRV_ERR_DAEMON_UNREACHABLE; + } + + // Read payload. + mcVersionInfo_t versionInfo_socket; + RECV_FROM_DAEMON(devCon, &versionInfo_socket); + + *versionInfo = versionInfo_socket; - *versionInfo = rspGetMobiCoreVersionPayload.versionInfo; + } while(0); + devMutex.unlock(); return mcResult; } //------------------------------------------------------------------------------ -static uint32_t getDaemonVersion( - Connection* devCon -) { +uint32_t getDaemonVersion(Connection* devCon) +{ assert(devCon != NULL); + mcResult_t mcResult = MC_DRV_OK; + uint32_t version = 0; - // Send GET VERSION command to daemon. - mcDrvCmdGetVersion_t cmdGetVersion = { - { - MC_DRV_CMD_GET_VERSION, - }, - }; - int len = devCon->writeData(&cmdGetVersion, sizeof(cmdGetVersion)); - if (sizeof(cmdGetVersion) != len) { - LOG_E("getDaemonVersion(): MC_DRV_CMD_GET_VERSION failed, ret=%d", len); - return 0; - } + LOG_I("===%s()===", __FUNCTION__); - // Read GET VERSION response. + do { + SEND_TO_DAEMON(devCon, MC_DRV_CMD_GET_VERSION); - // Read header first. - mcDrvResponseHeader_t rspHeader; - len = devCon->readData(&rspHeader, sizeof(rspHeader)); - if (sizeof(rspHeader) != len) { - LOG_E("getDaemonVersion(): MC_DRV_CMD_GET_VERSION failed to respond, ret=%d", len); - return 0; - } + uint32_t responseId; + RECV_FROM_DAEMON(devCon, &responseId); - if (MC_DRV_RSP_OK != rspHeader.responseId) { - LOG_E("getDaemonVersion(): MC_DRV_CMD_GET_VERSION bad response, respId=%d", rspHeader.responseId); - return 0; - } + if (MC_DRV_RSP_OK != responseId) { + LOG_E("getDaemonVersion(): MC_DRV_CMD_GET_VERSION bad response, respId=%d", responseId); + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; + break; + } + + RECV_FROM_DAEMON(devCon, &version); + + } while(0); + + devMutex.unlock(); - // Read payload. - mcDrvRspGetVersionPayload_t rspGetVersionPayload; - len = devCon->readData(&rspGetVersionPayload, sizeof(rspGetVersionPayload)); - if (sizeof(rspGetVersionPayload) != len) { - LOG_E("getDaemonVersion(): MC_DRV_CMD_GET_VERSION readPayload failed, ret=%d", len); + if (MC_DRV_OK != mcResult) { return 0; } - return rspGetVersionPayload.version; + return version; } /** @} */ diff --git a/mobicore/daemon/ClientLib/Device.cpp b/mobicore/daemon/ClientLib/Device.cpp index bde0a08..457b218 100644 --- a/mobicore/daemon/ClientLib/Device.cpp +++ b/mobicore/daemon/ClientLib/Device.cpp @@ -7,7 +7,7 @@ * Device and Trustlet Session management Funtions. * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -35,19 +35,15 @@ #include <stdint.h> #include <vector> -#include "mc_drv_module_api.h" - +#include "mc_linux.h" #include "Device.h" -#define LOG_TAG "McClientLib_Device" #include "log.h" //------------------------------------------------------------------------------ -Device::Device( - uint32_t deviceId, - Connection *connection -) { +Device::Device(uint32_t deviceId, Connection *connection) +{ this->deviceId = deviceId; this->connection = connection; @@ -56,9 +52,8 @@ Device::Device( //------------------------------------------------------------------------------ -Device::~Device( - void -) { +Device::~Device(void) +{ /* Delete all session objects. Usually this should not be needed as closeDevice() * requires that all sessions have been closed before. */ @@ -73,12 +68,12 @@ Device::~Device( wsmIterator_t wsmIterator = wsmL2List.begin(); while(wsmIterator != wsmL2List.end()) { - CWsm_ptr pWsm = *wsmIterator; + CWsm_ptr pWsm = *wsmIterator; - // ignore return code - pMcKMod->free(pWsm->handle); + // ignore return code + pMcKMod->free(pWsm->handle, pWsm->virtAddr, pWsm->len); - delete (*wsmIterator); + delete (*wsmIterator); wsmIterator = wsmL2List.erase(wsmIterator); } delete connection; @@ -87,43 +82,37 @@ Device::~Device( //------------------------------------------------------------------------------ -bool Device::open( - const char * deviceName -) { +bool Device::open(const char * deviceName) +{ return pMcKMod->open(deviceName); } //------------------------------------------------------------------------------ -void Device::close( - void -) { +void Device::close(void) +{ pMcKMod->close(); } //------------------------------------------------------------------------------ -bool Device::hasSessions( - void -) { +bool Device::hasSessions(void) +{ return sessionList.size() > 0; } //------------------------------------------------------------------------------ -void Device::createNewSession( - uint32_t sessionId, - Connection *connection -) { +void Device::createNewSession(uint32_t sessionId, Connection *connection) +{ Session *session = new Session(sessionId, pMcKMod, connection); sessionList.push_back(session); } //------------------------------------------------------------------------------ -bool Device::removeSession( - uint32_t sessionId -) { +bool Device::removeSession(uint32_t sessionId) +{ bool ret = false; sessionIterator_t interator = sessionList.begin(); @@ -146,16 +135,15 @@ bool Device::removeSession( //------------------------------------------------------------------------------ -Session *Device::resolveSessionId( - uint32_t sessionId -) { +Session *Device::resolveSessionId(uint32_t sessionId) +{ Session *ret = NULL; // Get Session for sessionId for ( sessionIterator_t interator = sessionList.begin(); - interator != sessionList.end(); - ++interator) - { + interator != sessionList.end(); + ++interator) + { if ((*interator)->sessionId == sessionId) { ret = (*interator); break; @@ -166,39 +154,28 @@ Session *Device::resolveSessionId( //------------------------------------------------------------------------------ -CWsm_ptr Device::allocateContiguousWsm( - uint32_t len -) { - CWsm_ptr pWsm = NULL; - do - { - if (0 == len) - { - break; - } - - // Allocate shared memory - addr_t virtAddr; - uint32_t handle; - addr_t physAddr; - bool mciReuse = false; - int ret = pMcKMod->mmap( - len, - &handle, - &virtAddr, - &physAddr, - &mciReuse); - if (0 != ret) - { - break; - } +CWsm_ptr Device::allocateContiguousWsm(uint32_t len) +{ + CWsm_ptr pWsm = NULL; + // Allocate shared memory + addr_t virtAddr; + uint32_t handle; + addr_t physAddr; + + if (!len) { + return NULL; + } - // Register (vaddr,paddr) with device - pWsm = new CWsm(virtAddr,len,handle,physAddr); + if (pMcKMod->mapWsm(len, &handle, &virtAddr, &physAddr)) { + return NULL; + } - wsmL2List.push_back(pWsm); - - } while(0); + LOG_I(" mapped handle %d to %p, phys=%p ", handle, virtAddr, physAddr); + + // Register (vaddr,paddr) with device + pWsm = new CWsm(virtAddr,len,handle,physAddr); + + wsmL2List.push_back(pWsm); // Return pointer to the allocated memory return pWsm; @@ -206,27 +183,24 @@ CWsm_ptr Device::allocateContiguousWsm( //------------------------------------------------------------------------------ -bool Device::freeContiguousWsm( - CWsm_ptr pWsm -) { +bool Device::freeContiguousWsm(CWsm_ptr pWsm) +{ bool ret = false; wsmIterator_t iterator; - for (iterator=wsmL2List.begin(); iterator!=wsmL2List.end(); ++iterator) - { - if (pWsm == *iterator) - { - ret = true; - break; - } + for (iterator=wsmL2List.begin(); iterator!=wsmL2List.end(); ++iterator) { + if (pWsm == *iterator){ + ret = true; + break; + } } if(ret) { - LOG_I("freeWsm virtAddr=0x%p, handle=%d", - pWsm->virtAddr,pWsm->handle); + LOG_I(" unmapping handle %d from %p, phys=%p", + pWsm->handle, pWsm->virtAddr, pWsm->physAddr); // ignore return code - pMcKMod->free(pWsm->handle); + pMcKMod->free(pWsm->handle, pWsm->virtAddr, pWsm->len); iterator = wsmL2List.erase(iterator); delete pWsm; @@ -236,22 +210,20 @@ bool Device::freeContiguousWsm( //------------------------------------------------------------------------------ -CWsm_ptr Device::findContiguousWsm( - addr_t virtAddr -) { - CWsm_ptr pWsm = NULL; +CWsm_ptr Device::findContiguousWsm(addr_t virtAddr) +{ + CWsm_ptr pWsm = NULL; for( wsmIterator_t iterator=wsmL2List.begin(); - iterator!=wsmL2List.end(); - ++iterator) + iterator!=wsmL2List.end(); + ++iterator) { CWsm_ptr pTmpWsm = *iterator; - if (virtAddr == pTmpWsm->virtAddr) - { + if (virtAddr == pTmpWsm->virtAddr) { pWsm = pTmpWsm; break; } - } + } return pWsm; } diff --git a/mobicore/daemon/ClientLib/Session.cpp b/mobicore/daemon/ClientLib/Session.cpp index 85e1398..65d33f1 100644 --- a/mobicore/daemon/ClientLib/Session.cpp +++ b/mobicore/daemon/ClientLib/Session.cpp @@ -2,7 +2,7 @@ * @{ * @file * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -30,11 +30,10 @@ #include <stdint.h> #include <vector> -#include "mc_drv_module_api.h" +#include "mc_linux.h" #include "Session.h" -#define LOG_TAG "McClient" #include "log.h" @@ -42,8 +41,8 @@ Session::Session( uint32_t sessionId, CMcKMod *mcKMod, - Connection *connection -) { + Connection *connection) +{ this->sessionId = sessionId; this->mcKMod = mcKMod; this->notificationConnection = connection; @@ -72,8 +71,7 @@ Session::~Session( // ignore any error, as we cannot do anything in this case. int ret = mcKMod->unregisterWsmL2(pBlkBufDescr->handle); - if (0 != ret) - { + if (ret != 0) { LOG_E("removeBulkBuf(): mcKModUnregisterWsmL2 failed: %d",ret); } @@ -83,6 +81,8 @@ Session::~Session( // Finally delete notification connection delete notificationConnection; + + unlock(); } @@ -117,6 +117,8 @@ BulkBufferDescriptor* Session::addBulkBuf( ) { if ((*iterator)->virtAddr == buf) { + // TODO-2012-08-03-haenellu: better error reporting. + LOG_E("Cannot map a buffer to multiple locations in one Trustlet."); return NULL; } } @@ -135,11 +137,11 @@ BulkBufferDescriptor* Session::addBulkBuf( &pPhysWsmL2); if (0 != ret) { - LOG_E("mcKModRegisterWsmL2 failed, ret=%d",ret); + LOG_V(" mcKMod->registerWsmL2() failed with %d",ret); break; } - LOG_I("addBulkBuf - Physical Address of L2 Table = 0x%X, handle=%d", + LOG_V(" addBulkBuf - Physical Address of L2 Table = 0x%X, handle=%d", (unsigned int)pPhysWsmL2, handle); @@ -165,7 +167,7 @@ bool Session::removeBulkBuf( bool ret = true; BulkBufferDescriptor *pBlkBufDescr = NULL; - LOG_I("removeBulkBuf(): Virtual Address = 0x%X", (unsigned int) virtAddr); + LOG_V("removeBulkBuf(): Virtual Address = 0x%X", (unsigned int) virtAddr); // Search and remove bulk buffer descriptor for ( bulkBufferDescrIterator_t iterator = bulkBufferDescriptors.begin(); @@ -183,18 +185,17 @@ bool Session::removeBulkBuf( if (NULL == pBlkBufDescr) { - LOG_E("removeBulkBuf - Virtual Address not found"); + LOG_E("%p not registered in session %d.", virtAddr, sessionId); ret = false; } else { - LOG_I("removeBulkBuf(): WsmL2 phys=0x%X, handle=%d", + LOG_V("removeBulkBuf(): WsmL2 phys=0x%X, handle=%d", (unsigned int)pBlkBufDescr->physAddrWsmL2, pBlkBufDescr->handle); // ignore any error, as we cannot do anything int ret = mcKMod->unregisterWsmL2(pBlkBufDescr->handle); - if (0 != ret) - { + if (ret != 0) { LOG_E("removeBulkBuf(): mcKModUnregisterWsmL2 failed: %d",ret); } diff --git a/mobicore/daemon/ClientLib/Session.h b/mobicore/daemon/ClientLib/Session.h index 8d609a8..d1c022a 100644 --- a/mobicore/daemon/ClientLib/Session.h +++ b/mobicore/daemon/ClientLib/Session.h @@ -2,7 +2,7 @@ * @{ * @file * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -33,9 +33,10 @@ #include <stdint.h> #include <list> -#include "mc_drv_module_api.h" +#include "mc_linux.h" #include "Connection.h" #include "CMcKMod.h" +#include "CMutex.h" class BulkBufferDescriptor{ @@ -69,8 +70,8 @@ typedef bulkBufferDescrList_t::iterator bulkBufferDescrIterator_t; */ typedef enum { - SESSION_STATE_INITIAL, - SESSION_STATE_OPEN, + SESSION_STATE_INITIAL, + SESSION_STATE_OPEN, SESSION_STATE_TRUSTLET_DEAD } sessionState_t; @@ -82,81 +83,72 @@ typedef enum */ typedef struct { sessionState_t state; /**< Session state */ - int32_t lastErr; /**< Last error of session */ + int32_t lastErr; /**< Last error of session */ } sessionInformation_t; class Session { - private: - - CMcKMod *mcKMod; - bulkBufferDescrList_t bulkBufferDescriptors; /**< Descriptors of additional bulk buffer of a session */ - sessionInformation_t sessionInfo; /**< Informations about session */ - + CMcKMod *mcKMod; + CMutex workLock; + bulkBufferDescrList_t bulkBufferDescriptors; /**< Descriptors of additional bulk buffer of a session */ + sessionInformation_t sessionInfo; /**< Informations about session */ public: - - uint32_t sessionId; - Connection *notificationConnection; - - Session( - uint32_t sessionId, - CMcKMod *mcKMod, - Connection *connection - ); - - virtual ~Session( - void - ); - - /** - * Add address information of additional bulk buffer memory to session and - * register virtual memory in kernel module. - * - * @attention The virtual address can only be added one time. If the virtual address already exist, NULL is returned. - * - * @param buf The virtual address of bulk buffer. - * @param len Length of bulk buffer. - * - * @return On success the actual Bulk buffer descriptor with all address information is retured, NULL if an error occurs. - */ - BulkBufferDescriptor * addBulkBuf( - addr_t buf, - uint32_t len - ); - - /** - * Remove address information of additional bulk buffer memory from session and - * unregister virtual memory in kernel module - * - * @param buf The virtual address of the bulk buffer. - * - * @return true on success. - */ - bool removeBulkBuf( - addr_t buf - ); - - /** - * Set additional error information of the last error that occured. - * - * @param errorCode The actual error. - */ - void setErrorInfo( - int32_t err - ); - - /** - * Get additional error information of the last error that occured. - * - * @attention After request the information is set to SESSION_ERR_NO. - * - * @return Last stored error code or SESSION_ERR_NO. - */ - int32_t getLastErr( - void - ); - + uint32_t sessionId; + Connection *notificationConnection; + + Session(uint32_t sessionId, CMcKMod *mcKMod, Connection *connection); + + virtual ~Session(void); + + /** + * Add address information of additional bulk buffer memory to session and + * register virtual memory in kernel module. + * + * @attention The virtual address can only be added one time. If the virtual address already exist, NULL is returned. + * + * @param buf The virtual address of bulk buffer. + * @param len Length of bulk buffer. + * + * @return On success the actual Bulk buffer descriptor with all address information is retured, NULL if an error occurs. + */ + BulkBufferDescriptor * addBulkBuf(addr_t buf, uint32_t len); + + /** + * Remove address information of additional bulk buffer memory from session and + * unregister virtual memory in kernel module + * + * @param buf The virtual address of the bulk buffer. + * + * @return true on success. + */ + bool removeBulkBuf(addr_t buf); + + /** + * Set additional error information of the last error that occured. + * + * @param errorCode The actual error. + */ + void setErrorInfo(int32_t err); + + /** + * Get additional error information of the last error that occured. + * + * @attention After request the information is set to SESSION_ERR_NO. + * + * @return Last stored error code or SESSION_ERR_NO. + */ + int32_t getLastErr(void); + + /** + * Lock session for operation + */ + void lock() { workLock.lock(); } + + /** + * Unlock session for operation + */ + void unlock() { workLock.unlock(); } }; typedef std::list<Session*> sessionList_t; diff --git a/mobicore/daemon/Common/Android.mk b/mobicore/daemon/Common/Android.mk index 1b6520c..39f050e 100644 --- a/mobicore/daemon/Common/Android.mk +++ b/mobicore/daemon/Common/Android.mk @@ -8,26 +8,20 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE := libMcCommon -LOCAL_MODULE_TAGS := eng +LOCAL_MODULE := Common # Add new source files here -LOCAL_SRC_FILES +=\ - CMutex.cpp\ - Connection.cpp\ - NetlinkConnection.cpp\ - CSemaphore.cpp\ - CThread.cpp +#LOCAL_SRC_FILES +=\ +# CMutex.cpp\ +# Connection.cpp\ +# NetlinkConnection.cpp\ +# CSemaphore.cpp\ +# CThread.cpp # Header files required by components including this module -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) -LOCAL_EXPORT_CPPFLAGS += -fno-rtti -fno-exceptions +LOCAL_EXPORT_C_INCLUDES += $(LOCAL_PATH) -LOCAL_C_INCLUDES += bionic \ - external/stlport/stlport - -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions - -include $(COMP_PATH_Logwrapper)/Android.mk +# Import logwrapper +#include $(COMP_PATH_Logwrapper)/Android.mk include $(BUILD_STATIC_LIBRARY) diff --git a/mobicore/daemon/Common/CThread.cpp b/mobicore/daemon/Common/CThread.cpp index 1508c13..7445556 100644 --- a/mobicore/daemon/Common/CThread.cpp +++ b/mobicore/daemon/Common/CThread.cpp @@ -32,7 +32,6 @@ */ #include "CThread.h" -#define LOG_TAG "McDaemon" #include "log.h" diff --git a/mobicore/daemon/Common/Connection.cpp b/mobicore/daemon/Common/Connection.cpp index d9b012b..08d5e00 100644 --- a/mobicore/daemon/Common/Connection.cpp +++ b/mobicore/daemon/Common/Connection.cpp @@ -37,7 +37,7 @@ #include "Connection.h" -#define LOG_TAG "McClient" +//#define LOG_VERBOSE #include "log.h" @@ -69,9 +69,10 @@ Connection::Connection( Connection::~Connection( void ) { - LOG_I("%s: Connection closed!", __func__); + LOG_V(" closing Connection..."); if (socketDescriptor != -1) close(socketDescriptor); + LOG_I(" Socket connection closed."); } @@ -84,19 +85,19 @@ bool Connection::connect( assert(NULL != dest); - LOG_I("connect(): Connecting to %s", dest); + LOG_I(" Connecting to %s socket", dest); do { remote.sun_family = AF_UNIX; strncpy(remote.sun_path, dest, sizeof(remote.sun_path) - 1); if ((socketDescriptor = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { - LOG_E("Can't open stream socket - errno: %d", errno); + LOG_ERRNO("Can't open stream socket."); break; } len = strlen(remote.sun_path) + sizeof(remote.sun_family); // The Daemon socket is in the Abstract Domain(LINUX ONLY!) remote.sun_path[0] = 0; if (::connect(socketDescriptor, (struct sockaddr *) &remote, len) < 0) { - LOG_E("connect() failed - errno: %d", errno); + LOG_ERRNO("connect()"); break; } ret = true; @@ -144,13 +145,13 @@ size_t Connection::readData( // check for read error if (-1 == (int)ret) { - LOG_E("readData(): select() failed, ret=%d, errno=%d", ret,errno); + LOG_ERRNO("select"); break; } // Handle case of no descriptor ready if (0 == ret) { - LOG_W("readData(): select() timed out"); + LOG_W(" Timeout during select() / No more notifications."); ret = -2; break; } @@ -160,16 +161,22 @@ size_t Connection::readData( // finally check if fd has been selected -> must socketDescriptor if (!FD_ISSET(socketDescriptor, &readfds)) { - LOG_E("readData(): failure, errno=%d", errno); + LOG_ERRNO("no fd is set, select"); break; } ret = recv(socketDescriptor, buffer, len, MSG_WAITALL); if(0 == ret) { - LOG_I("readData(): peer orderly closed connection."); + LOG_V(" readData(): peer orderly closed connection."); break; } +// if (ret != len) +// { +// LOG_ERRNO("could not receive all requested data because read"); +// LOG_E("ret = %d", ret); +// ret = -1; +// } }while(false); @@ -190,7 +197,8 @@ size_t Connection::writeData( ret = send(socketDescriptor, buffer, len, 0); if (ret != len) { - LOG_E( "writeData(): could no send all data, ret=%d, errno: %d", ret,errno); + LOG_ERRNO("could not send all data, because send"); + LOG_E("ret = %d", ret); ret = -1; } diff --git a/mobicore/daemon/Common/Connection.h b/mobicore/daemon/Common/Connection.h index 81e8dd8..53c657e 100644 --- a/mobicore/daemon/Common/Connection.h +++ b/mobicore/daemon/Common/Connection.h @@ -108,6 +108,7 @@ public: * @param buffer Pointer to source buffer. * @param len Number of bytes to read. * @return Number of bytes written. + * @return -1 if written bytes not equal to len. */ virtual size_t writeData( void *buffer, diff --git a/mobicore/daemon/Common/NetlinkConnection.cpp b/mobicore/daemon/Common/NetlinkConnection.cpp index 81b394b..f2d081c 100644 --- a/mobicore/daemon/Common/NetlinkConnection.cpp +++ b/mobicore/daemon/Common/NetlinkConnection.cpp @@ -41,7 +41,6 @@ #include "NetlinkConnection.h" -#define LOG_TAG "McDaemon" #include "log.h" @@ -101,7 +100,7 @@ NetlinkConnection::NetlinkConnection( NetlinkConnection::~NetlinkConnection( void ) { - LOG_I("%s: destroy connection for PID 0x%X", __func__, peerPid); + LOG_I("%s: destroy connection for PID 0x%X", __FUNCTION__, peerPid); socketDescriptor = -1; free(dataMsg); @@ -120,11 +119,11 @@ bool NetlinkConnection::connect( assert(NULL != dest); - LOG_I("%s: Connecting to SEQ 0x%X", __func__, MC_DAEMON_PID); + LOG_I("%s: Connecting to SEQ 0x%X", __FUNCTION__, MC_DAEMON_PID); do { if ((socketDescriptor = socket(PF_NETLINK, SOCK_DGRAM, MC_DAEMON_NETLINK)) < 0) { LOG_E("%s: Can't open netlink socket - errno: %d(%s)", - __func__, errno, strerror(errno)); + __FUNCTION__, errno, strerror(errno)); break; } memset(&addr, 0, sizeof(addr)); @@ -133,7 +132,7 @@ bool NetlinkConnection::connect( addr.nl_groups = 0; /* not in mcast groups */ if (bind(socketDescriptor, (struct sockaddr*)&addr, sizeof(addr)) < 0) { - LOG_E("%s: bind() failed - errno: %d(%s)", __func__, errno, strerror(errno)); + LOG_E("%s: bind() failed - errno: %d(%s)", __FUNCTION__, errno, strerror(errno)); close(socketDescriptor); // Set invalid socketDescriptor @@ -192,7 +191,7 @@ size_t NetlinkConnection::readData( } //LOG_I("%s: reading connection data %u, connection data left %u", - // __func__, len, dataLen); + // __FUNCTION__, len, dataLen); assert(dataStart != NULL); @@ -223,7 +222,7 @@ size_t NetlinkConnection::readData( } dataMutex.unlock(); - //LOG_I("%s: read %u", __func__, ret); + //LOG_I("%s: read %u", __FUNCTION__, ret); return ret; } @@ -241,7 +240,7 @@ size_t NetlinkConnection::writeData( assert(NULL != buffer); assert(-1 != socketDescriptor); - //LOG_I("%s: send data %u to PID %u", __func__, len, sequenceMagic); + //LOG_I("%s: send data %u to PID %u", __FUNCTION__, len, sequenceMagic); memset(&dest_addr, 0, sizeof(dest_addr)); dest_addr.nl_family = AF_NETLINK; @@ -272,7 +271,7 @@ size_t NetlinkConnection::writeData( if (ret != NLMSG_SPACE(len)) { LOG_E( "%s: could no send all data, ret=%d, errno: %d(%s)", - __func__, ret, errno, strerror(errno)); + __FUNCTION__, ret, errno, strerror(errno)); ret = -1; } else{ diff --git a/mobicore/daemon/Daemon/Android.mk b/mobicore/daemon/Daemon/Android.mk index 149305a..37d977a 100644 --- a/mobicore/daemon/Daemon/Android.mk +++ b/mobicore/daemon/Daemon/Android.mk @@ -3,41 +3,13 @@ # Module: mcDriverDaemon # # ============================================================================= -LOCAL_PATH := $(call my-dir) -MY_MCDRIVER_PATH := $(LOCAL_PATH) - -include $(CLEAR_VARS) - -LOCAL_MODULE := mcDriverDaemon -LOCAL_MODULE_TAGS := eng - -# Add new subdirectories containing code here -include $(LOCAL_PATH)/Device/Android.mk -include $(LOCAL_PATH)/Server/Android.mk - -LOCAL_C_INCLUDES += bionic \ - external/stlport/stlport - -# Add new folders with header files here -LOCAL_C_INCLUDES += \ - $(COMP_PATH_MobiCore)/inc \ - $(COMP_PATH_MobiCoreDriverMod)/Public \ - $(APP_PROJECT_PATH)/ClientLib/public \ - $(APP_PROJECT_PATH)/Kernel \ - $(APP_PROJECT_PATH)/Kernel/Platforms/Generic \ - $(APP_PROJECT_PATH)/Common \ - $(APP_PROJECT_PATH)/Registry/Public \ - $(MY_MCDRIVER_PATH)/public # Add new source files here -LOCAL_SRC_FILES += \ - MobiCoreDriverDaemon.cpp - -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions -# Modules this one depnds on (depending ones first) -LOCAL_STATIC_LIBRARIES = libstlport_static libMcKernel libMcCommon libMcRegistry - -include $(COMP_PATH_Logwrapper)/Android.mk +LOCAL_SRC_FILES += Daemon/MobiCoreDriverDaemon.cpp -include $(BUILD_EXECUTABLE) +# Includes required for the Daemon +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Daemon/public \ +# Internal components +include $(LOCAL_PATH)/Daemon/Device/Android.mk +include $(LOCAL_PATH)/Daemon/Server/Android.mk diff --git a/mobicore/daemon/Daemon/Device/Android.mk b/mobicore/daemon/Daemon/Device/Android.mk index 5ae55d8..2e8fc50 100644 --- a/mobicore/daemon/Daemon/Device/Android.mk +++ b/mobicore/daemon/Daemon/Device/Android.mk @@ -6,21 +6,19 @@ # This is not a separate module. # Only for inclusion by other modules. +# All paths are relative to APP_PROJECT_PATH -MY_MCDRV_DEVICE_PATH := $(call my-dir) -MY_MCDRV_DEVICE_PATH_REL := Device - -include $(MY_MCDRV_DEVICE_PATH)/Platforms/Android.mk +DEVICE_PATH := Daemon/Device +include $(LOCAL_PATH)/$(DEVICE_PATH)/Platforms/Android.mk # Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(MY_MCDRV_DEVICE_PATH)\ - $(MY_MCDRV_DEVICE_PATH)/public +# Include paths are absolute paths +LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(DEVICE_PATH) \ + $(LOCAL_PATH)/$(DEVICE_PATH)/public # Add new source files here -LOCAL_SRC_FILES +=\ - $(MY_MCDRV_DEVICE_PATH_REL)/DeviceIrqHandler.cpp\ - $(MY_MCDRV_DEVICE_PATH_REL)/DeviceScheduler.cpp\ - $(MY_MCDRV_DEVICE_PATH_REL)/MobiCoreDevice.cpp\ - $(MY_MCDRV_DEVICE_PATH_REL)/NotificationQueue.cpp\ - $(MY_MCDRV_DEVICE_PATH_REL)/TrustletSession.cpp\ +LOCAL_SRC_FILES += $(DEVICE_PATH)/DeviceIrqHandler.cpp \ + $(DEVICE_PATH)/DeviceScheduler.cpp \ + $(DEVICE_PATH)/MobiCoreDevice.cpp \ + $(DEVICE_PATH)/NotificationQueue.cpp \ + $(DEVICE_PATH)/TrustletSession.cpp \ diff --git a/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp b/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp index a5cfa71..eb729ec 100644 --- a/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp +++ b/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp @@ -45,7 +45,6 @@ #include "mcLoadFormat.h" -#define LOG_TAG "McDaemon" #include "log.h" #include "public/MobiCoreDevice.h" @@ -246,7 +245,7 @@ void MobiCoreDevice::openSession( mcpMessage->cmdOpen.ofsTciBuffer = 0; mcpMessage->cmdOpen.lenTciBuffer = pCmdOpenSessionPayload->len; - LOG_I("%s(): tciPhys=%p, len=%d,", __FUNCTION__, + LOG_I(" Using phys=%p, len=%d as TCI buffer", (addr_t)(pCmdOpenSessionPayload->tci), pCmdOpenSessionPayload->len); @@ -289,12 +288,12 @@ void MobiCoreDevice::openSession( if(MC_MCP_RET_OK != mcRet) { - LOG_E("%s: CMD_OPEN_SESSION error %d", __FUNCTION__, mcRet); + LOG_E("MCP OPEN returned code %d.", mcRet); break; } - LOG_I("%s: We have %d queued notifications after open session", - __FUNCTION__, notifications.size()); + LOG_I(" After MCP OPEN, we have %d queued notifications", + notifications.size()); // Read MC answer from MCP buffer TrustletSession *trustletSession = new TrustletSession( deviceConnection, @@ -322,9 +321,11 @@ TrustletSession *MobiCoreDevice::registerTrustletConnection( Connection *connection, mcDrvCmdNqConnectPayload_ptr pCmdNqConnectPayload ) { - LOG_I("%s(): searching sessionMagic %d and sessionId %d", __FUNCTION__, - pCmdNqConnectPayload->sessionMagic, - pCmdNqConnectPayload->sessionId); + LOG_I(" Registering notification socket with Service session %d.", + pCmdNqConnectPayload->sessionId); + LOG_V(" Searching sessionId %d with sessionMagic %d", + pCmdNqConnectPayload->sessionId, + pCmdNqConnectPayload->sessionMagic); for (trustletSessionIterator_t iterator = trustletSessions.begin(); iterator != trustletSessions.end(); @@ -340,10 +341,11 @@ TrustletSession *MobiCoreDevice::registerTrustletConnection( continue; } - LOG_I("%s(): found connection", __FUNCTION__); - ts->notificationConnection = connection; - return ts; + + LOG_I(" Found Service session, registered connection."); + + return ts; } LOG_I("registerTrustletConnection(): search failed"); @@ -386,7 +388,7 @@ bool MobiCoreDevice::closeSession( break; } - LOG_I("closeSession(): Write MCP close message to buffer and notify, wait"); + LOG_I(" Write MCP CLOSE message to MCI, notify and wait"); // Write MCP close message to buffer mcpMessage->cmdClose.cmdHeader.cmdId = MC_MCP_CMD_CLOSE_SESSION; @@ -463,6 +465,7 @@ void MobiCoreDevice::mapBulk( pRspMapBulkMemPayload->sessionId = pCmdMapBulkMemPayload->sessionId; if(MC_MCP_RET_OK != mcRet) { + //LOG_E("MCP MAP returned code %d.", mcRet); LOG_E("mapBulk(): CMD_MAP error %d",mcRet); break; } @@ -508,7 +511,7 @@ void MobiCoreDevice::unmapBulk( if(MC_MCP_RET_OK != mcRet) { - LOG_E("unmapBulk(): MC_MCP_CMD_UNMAP error %d",mcRet); + LOG_E("MCP MAP returned code %d.", mcRet); break; } diff --git a/mobicore/daemon/Daemon/Device/NotificationQueue.cpp b/mobicore/daemon/Daemon/Device/NotificationQueue.cpp index c9a79ff..52728e1 100644 --- a/mobicore/daemon/Daemon/Device/NotificationQueue.cpp +++ b/mobicore/daemon/Daemon/Device/NotificationQueue.cpp @@ -32,7 +32,6 @@ #include "NotificationQueue.h" #include <stddef.h> -#define LOG_TAG "McDaemon" #include "log.h" //------------------------------------------------------------------------------ diff --git a/mobicore/daemon/Daemon/Device/Platforms/Android.mk b/mobicore/daemon/Daemon/Device/Platforms/Android.mk index c367952..48dd98a 100644 --- a/mobicore/daemon/Daemon/Device/Platforms/Android.mk +++ b/mobicore/daemon/Daemon/Device/Platforms/Android.mk @@ -4,7 +4,7 @@ # # ============================================================================= -PLATFORMS_PATH := $(call my-dir) +PLATFORMS_PATH := $(LOCAL_PATH)/Daemon/Device/Platforms # Always include the Generic code include $(PLATFORMS_PATH)/Generic/Android.mk diff --git a/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk b/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk index 50cf589..a6607de 100644 --- a/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk +++ b/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk @@ -7,11 +7,10 @@ # This is not a separate module. # Only for inclusion by other modules. -GENERIC_PATH := $(call my-dir) -GENERIC_PATH_REL := Device/Platforms/Generic +GENERIC_PATH := Daemon/Device/Platforms/Generic # Add new source files here -LOCAL_SRC_FILES +=$(GENERIC_PATH_REL)/TrustZoneDevice.cpp +LOCAL_SRC_FILES += $(GENERIC_PATH)/TrustZoneDevice.cpp # Header files for components including this module -LOCAL_C_INCLUDES += $(call my-dir) +LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(GENERIC_PATH) diff --git a/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.cpp b/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.cpp index 51dfb69..8578305 100644 --- a/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.cpp +++ b/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.cpp @@ -4,7 +4,7 @@ * * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -31,12 +31,12 @@ */ #include <cstdlib> -#include <fstream> +#include <stdio.h> #include <inttypes.h> #include <list> +#include "mc_linux.h" #include "McTypes.h" -#include "mc_drv_module_api.h" #include "Mci/mci.h" #include "mcVersionHelper.h" @@ -98,30 +98,31 @@ static int loadMobiCoreImage( do { // Open MobiCore binary for reading only - fstream fs(mobicorePath, ios_base::in | ios_base::binary); - if (!fs) { + FILE *fs = fopen (mobicorePath, "rb"); + if(!fs) { LOG_E("MobiCore not found: %s", mobicorePath); break; } // Get the MobiCore file size - fs.seekg(0, ios::end); - int32_t fileSize = fs.tellg(); - fs.seekg(0, ios::beg); + fseek(fs, 0, SEEK_END); + int32_t fileSize = ftell(fs); + fseek(fs, 0, SEEK_SET); LOG_I("File size: %i", fileSize); // Check if file is too big if (fileSize > size) { LOG_E("MobiCore size exceeds expectations. Size is: %i", fileSize); + fclose(fs); break; } - fs.read((char*)virtAddr, fileSize); + fread((char*)virtAddr, 1, fileSize, fs); //Create an visible line with different content at the end memset((void*)((uint32_t)virtAddr+fileSize),0xff,4096); // Close file - fs.close(); + fclose(fs); ret = 0; } while (false); @@ -139,54 +140,52 @@ static int loadMobiCoreImage( bool TrustZoneDevice::initDevice( const char *devFile, bool loadMobiCore, - const char *mobicoreImage, - bool enableScheduler -) throw (ExcDevice) { - - notificationQueue_t* nqStartOut; + const char *mobicoreImage, + bool enableScheduler) +{ + notificationQueue_t* nqStartOut; notificationQueue_t* nqStartIn; addr_t mciBuffer; - pMcKMod = new CMcKMod(); - if (!pMcKMod->open(devFile)) - { - LOG_E("open() kernel module device failed"); - return false; - } - if (!pMcKMod->checkKmodVersionOk()) - { - LOG_E("kernel module version mismatch"); - return false; - } + pMcKMod = new CMcKMod(); + if (!pMcKMod->open(devFile)) + { + LOG_W(" Opening kernel module device failed"); + return false; + } + if (!pMcKMod->checkVersion()) { + LOG_E("kernel module version mismatch"); + return false; + } - // Start MobiCore from DDRAM - if (loadMobiCore) { - // 1. Allocate DDRAM as pseudo IRAM - mobicoreInDDR = allocateContiguousPersistentWsm(SIZE_DDRAM); - if (NULL == mobicoreInDDR) { - LOG_E("Allocation of additional RAM failed"); - return false; - } - memset(mobicoreInDDR->virtAddr,0xCC,SIZE_DDRAM); + // Start MobiCore from DDRAM + if (loadMobiCore) { + // 1. Allocate DDRAM as pseudo IRAM + mobicoreInDDR = allocateContiguousPersistentWsm(SIZE_DDRAM); + if (NULL == mobicoreInDDR) { + LOG_E("Allocation of additional RAM failed"); + return false; + } + memset(mobicoreInDDR->virtAddr,0xCC,SIZE_DDRAM); - int ret = loadMobiCoreImage(mobicoreInDDR->virtAddr, SIZE_DDRAM, - mobicoreImage); - if (0 != ret) { - LOG_E("loading Mobicore file failed: %d", ret); - return false; - } + int ret = loadMobiCoreImage(mobicoreInDDR->virtAddr, SIZE_DDRAM, + mobicoreImage); + if (0 != ret) { + LOG_E("loading Mobicore file failed: %d", ret); + return false; + } - ret = pMcKMod->fcExecute( - mobicoreInDDR->physAddr, - MCP_BUFFER_SIZE); - if (0 != ret) { - LOG_E("pMcKMod->fcExecute() failed : %d", ret); - return false; - } - } - this->schedulerEnabled = enableScheduler; + ret = pMcKMod->fcExecute( + mobicoreInDDR->physAddr, + MCP_BUFFER_SIZE); + if (0 != ret) { + LOG_E("pMcKMod->fcExecute() failed : %d", ret); + return false; + } + } + this->schedulerEnabled = enableScheduler; - // Init MC with NQ and MCP buffer addresses + // Init MC with NQ and MCP buffer addresses // Set up MCI buffer if(!getMciInstance(MCI_BUFFER_SIZE, &pWsmMcp, &mciReused)) { @@ -205,20 +204,14 @@ bool TrustZoneDevice::initDevice( bzero(mciBuffer, MCI_BUFFER_SIZE); // Init MC with NQ and MCP buffer addresses - int ret = pMcKMod->fcInit( - pWsmMcp->physAddr, - 0, - NQ_BUFFER_SIZE, - NQ_BUFFER_SIZE, - MCP_BUFFER_SIZE); - if (0 != ret) - { + int ret = pMcKMod->fcInit(0, NQ_BUFFER_SIZE, NQ_BUFFER_SIZE, MCP_BUFFER_SIZE); + if (ret != 0) { LOG_E("pMcKMod->fcInit() failed"); return false; } // First empty N-SIQ which results in set up of the MCI structure - if(!nsiq()) { + if (!nsiq()) { return false; } @@ -227,7 +220,7 @@ bool TrustZoneDevice::initDevice( while(1) { uint32_t status = getMobicoreStatus(); - + if (MC_STATUS_INITIALIZED == status) { break; @@ -270,7 +263,7 @@ bool TrustZoneDevice::initDevice( mcpMessage = &(mcpBuf->mcpMessage); // convert virtual address of mapping to physical address for the init. - LOG_I("MCP: virt=%p, phys=%p, reused=%s", + LOG_I("MCI established, at %p, phys=%p, reused=%s", pWsmMcp->virtAddr, pWsmMcp->physAddr, mciReused ? "true" : "false"); @@ -302,10 +295,10 @@ bool TrustZoneDevice::yield( bool TrustZoneDevice::nsiq( void ) { - // There is no need to set the NON-IDLE flag here. Sending an N-SIQ will - // make the MobiCore run until it could set itself to a state where it - // set the flag itself. IRQs and FIQs are disbaled for this period, so - // there is no way the NWd can interrupt here. + // There is no need to set the NON-IDLE flag here. Sending an N-SIQ will + // make the MobiCore run until it could set itself to a state where it + // set the flag itself. IRQs and FIQs are disbaled for this period, so + // there is no way the NWd can interrupt here. // not needed: mcFlags->schedule = MC_FLAG_SCHEDULE_NON_IDLE; @@ -324,73 +317,66 @@ bool TrustZoneDevice::nsiq( void TrustZoneDevice::notify( uint32_t sessionId ) { - do + // Check if it is MCP session - handle openSession() command + if (SID_MCP != sessionId) { - // Check if it is MCP session - handle openSession() command - if (SID_MCP != sessionId) - { - // Check if session ID exists to avoid flooding of nq by clients - TrustletSession* ts = getTrustletSession(sessionId); - if (NULL == ts) - { - LOG_E("notify(): no session with id=%d", sessionId); - break; - } - } + // Check if session ID exists to avoid flooding of nq by clients + TrustletSession* ts = getTrustletSession(sessionId); + if (NULL == ts) + { + LOG_E("notify(): no session with id=%d", sessionId); + return; + } - LOG_I("notify(): Send notification for id=%d", sessionId); - // Notify MobiCore about new data + LOG_I(" Sending notification for session %d to MobiCore", sessionId); + } else { + LOG_I(" Sending MCP notification to MobiCore"); + } - notification_t notification = { - // C++ does not support C99 designated initializers - /* .sessionId = */ sessionId, - /* .payload = */ 0 - }; + // Notify MobiCore about new data - nq->putNotification(¬ification); - //IMPROVEMENT-2012-03-07-maneaval What happens when/if nsiq fails? - //In the old days an exception would be thrown but it was uncertain - //where it was handled, some server(sock or Netlink). In that case - //the server would just die but never actually signaled to the client - //any error condition - nsiq(); + notification_t notification = { sessionId : sessionId, payload : 0}; - } while(0); + nq->putNotification(¬ification); + //IMPROVEMENT-2012-03-07-maneaval What happens when/if nsiq fails? + //In the old days an exception would be thrown but it was uncertain + //where it was handled, some server(sock or Netlink). In that case + //the server would just die but never actually signaled to the client + //any error condition + nsiq(); } //------------------------------------------------------------------------------ -uint32_t TrustZoneDevice::getMobicoreStatus( - void -) { +uint32_t TrustZoneDevice::getMobicoreStatus(void) +{ uint32_t status; //IMPROVEMENT-2012-03-07-maneaval Can fcInfo ever fail? Before it threw an //exception but the handler depended on the context. pMcKMod->fcInfo(0, &status, NULL); - + return status; } //------------------------------------------------------------------------------ -bool TrustZoneDevice::checkMciVersion( - void -) { - int ret; - uint32_t version = 0; +bool TrustZoneDevice::checkMciVersion(void) +{ + uint32_t version = 0; + int ret; + char* errmsg; - ret = pMcKMod->fcInfo(MC_EXT_INFO_ID_MCI_VERSION, NULL, &version); - if (ret != 0) { - LOG_E("pMcKMod->fcInfo() failed with %d", ret); - return false; - } + ret = pMcKMod->fcInfo(MC_EXT_INFO_ID_MCI_VERSION, NULL, &version); + if (ret != 0) { + LOG_E("pMcKMod->fcInfo() failed with %d", ret); + return false; + } - // Run-time check. - char* errmsg; - if (!checkVersionOkMCI(version, &errmsg)) { - LOG_E("%s", errmsg); - return false; - } - LOG_I("%s", errmsg); - return true; + // Run-time check. + if (!checkVersionOkMCI(version, &errmsg)) { + LOG_E("%s", errmsg); + return false; + } + LOG_I("%s", errmsg); + return true; } //------------------------------------------------------------------------------ @@ -401,168 +387,138 @@ void TrustZoneDevice::dumpMobicoreStatus( uint32_t status, info; // read additional info about exception-point and print LOG_E("MobiCore halted !!!"); - ret = pMcKMod->fcInfo(1, &status, &info); + ret = pMcKMod->fcInfo(1, &status, &info); LOG_W("MC_HALT: flags : 0x%8x", info); - ret = pMcKMod->fcInfo(2, &status, &info); + ret = pMcKMod->fcInfo(2, &status, &info); LOG_W("MC_HALT: haltCode : 0x%8x", info); - ret = pMcKMod->fcInfo(3, &status, &info); + ret = pMcKMod->fcInfo(3, &status, &info); LOG_W("MC_HALT: haltIp : 0x%8x", info); - ret = pMcKMod->fcInfo(4, &status, &info); + ret = pMcKMod->fcInfo(4, &status, &info); LOG_W("MC_HALT: faultRec.cnt : 0x%8x", info); - ret = pMcKMod->fcInfo(5, &status, &info); + ret = pMcKMod->fcInfo(5, &status, &info); LOG_W("MC_HALT: faultRec.cause : 0x%8x", info); - ret = pMcKMod->fcInfo(6, &status, &info); + ret = pMcKMod->fcInfo(6, &status, &info); LOG_W("MC_HALT: faultRec.meta : 0x%8x", info); - ret = pMcKMod->fcInfo(7, &status, &info); + ret = pMcKMod->fcInfo(7, &status, &info); LOG_W("MC_HALT: faultRec.thread : 0x%8x", info); - ret = pMcKMod->fcInfo(8, &status, &info); + ret = pMcKMod->fcInfo(8, &status, &info); LOG_W("MC_HALT: faultRec.ip : 0x%8x", info); - ret = pMcKMod->fcInfo(9, &status, &info); + ret = pMcKMod->fcInfo(9, &status, &info); LOG_W("MC_HALT: faultRec.sp : 0x%8x", info); - ret = pMcKMod->fcInfo(10, &status, &info); + ret = pMcKMod->fcInfo(10, &status, &info); LOG_W("MC_HALT: faultRec.arch.dfsr : 0x%8x", info); - ret = pMcKMod->fcInfo(11, &status, &info); + ret = pMcKMod->fcInfo(11, &status, &info); LOG_W("MC_HALT: faultRec.arch.adfsr : 0x%8x", info); - ret = pMcKMod->fcInfo(12, &status, &info); + ret = pMcKMod->fcInfo(12, &status, &info); LOG_W("MC_HALT: faultRec.arch.dfar : 0x%8x", info); - ret = pMcKMod->fcInfo(13, &status, &info); + ret = pMcKMod->fcInfo(13, &status, &info); LOG_W("MC_HALT: faultRec.arch.ifsr : 0x%8x", info); - ret = pMcKMod->fcInfo(14, &status, &info); + ret = pMcKMod->fcInfo(14, &status, &info); LOG_W("MC_HALT: faultRec.arch.aifsr : 0x%8x", info); - ret = pMcKMod->fcInfo(15, &status, &info); + ret = pMcKMod->fcInfo(15, &status, &info); LOG_W("MC_HALT: faultRec.arch.ifar : 0x%8x", info); - ret = pMcKMod->fcInfo(16, &status, &info); + ret = pMcKMod->fcInfo(16, &status, &info); LOG_W("MC_HALT: mcData.flags : 0x%8x", info); - ret = pMcKMod->fcInfo(19, &status, &info); - LOG_W("MC_HALT: mcExcep.partner : 0x%8x", info); - ret = pMcKMod->fcInfo(20, &status, &info); - LOG_W("MC_HALT: mcExcep.peer : 0x%8x", info); - ret = pMcKMod->fcInfo(21, &status, &info); - LOG_W("MC_HALT: mcExcep.message : 0x%8x", info); - ret = pMcKMod->fcInfo(22, &status, &info); - LOG_W("MC_HALT: mcExcep.data : 0x%8x", info); + ret = pMcKMod->fcInfo(19, &status, &info); + LOG_W("MC_HALT: mcExcep.partner : 0x%8x", info); + ret = pMcKMod->fcInfo(20, &status, &info); + LOG_W("MC_HALT: mcExcep.peer : 0x%8x", info); + ret = pMcKMod->fcInfo(21, &status, &info); + LOG_W("MC_HALT: mcExcep.message : 0x%8x", info); + ret = pMcKMod->fcInfo(22, &status, &info); + LOG_W("MC_HALT: mcExcep.data : 0x%8x", info); } //------------------------------------------------------------------------------ -bool TrustZoneDevice::waitSsiq( - void -) { - uint32_t cnt; - if (!pMcKMod->waitSSIQ(&cnt)) - { - LOG_E("pMcKMod->SSIQ() failed"); - return false; - } - LOG_I("SSIQ Received, COUNTER = %u", cnt); - return true; +bool TrustZoneDevice::waitSsiq(void) +{ + uint32_t cnt; + if (!pMcKMod->waitSSIQ(&cnt)) { + LOG_E("pMcKMod->SSIQ() failed"); + return false; + } + LOG_I(" Received SSIQ interrupt from MobiCore, counter=%u", cnt); + return true; } //------------------------------------------------------------------------------ -bool TrustZoneDevice::getMciInstance( - uint32_t len, - CWsm_ptr *mci, - bool *reused -) { - addr_t virtAddr; - uint32_t handle; - addr_t physAddr; - bool isMci = true; - if (0 == len) - { - LOG_E("allocateWsm() length is 0"); - return false; - } +bool TrustZoneDevice::getMciInstance(uint32_t len, CWsm_ptr *mci, bool *reused) +{ + addr_t virtAddr; + uint32_t handle; + addr_t physAddr; + bool isReused = true; + if (len == 0) { + LOG_E("allocateWsm() length is 0"); + return false; + } - int ret = pMcKMod->mmap( - len, - &handle, - &virtAddr, - &physAddr, - &isMci); - if (0 != ret) - { - LOG_E("pMcKMod->mmap() failed: %d", ret); - return false; - } - *mci = new CWsm(virtAddr, len, handle, physAddr); - // isMci will be set to true if buffer has been reused - *reused = isMci; - return true; + int ret = pMcKMod->mapMCI(len, &handle, &virtAddr, &physAddr, &isReused); + if (ret != 0) { + LOG_E("pMcKMod->mmap() failed: %d", ret); + return false; + } + + *mci = new CWsm(virtAddr, len, handle, physAddr); + *reused = isReused; + return true; } //------------------------------------------------------------------------------ -bool TrustZoneDevice::freeWsm( - CWsm_ptr pWsm -) { - - int ret = pMcKMod->free(pWsm->handle); - if (ret != 0) - { - LOG_E("pMcKMod->free() failed: %d", ret); - return false; - } - delete pWsm; - return true; +bool TrustZoneDevice::freeWsm(CWsm_ptr pWsm) +{ + int ret = pMcKMod->free(pWsm->handle, pWsm->virtAddr, pWsm->len); + if (ret != 0) { + LOG_E("pMcKMod->free() failed: %d", ret); + return false; + } + delete pWsm; + return true; } //------------------------------------------------------------------------------ -CWsm_ptr TrustZoneDevice::registerWsmL2( - addr_t buffer, - uint32_t len, - uint32_t pid -) { - addr_t physAddr; - uint32_t handle; - - int ret = pMcKMod->registerWsmL2( - buffer, - len, - pid, - &handle, - &physAddr); - if (ret != 0) - { - LOG_E("ipMcKMod->registerWsmL2() failed: %d", ret); - return NULL; - } +CWsm_ptr TrustZoneDevice::registerWsmL2(addr_t buffer, uint32_t len, uint32_t pid) +{ + addr_t physAddr; + uint32_t handle; + + int ret = pMcKMod->registerWsmL2( + buffer, + len, + pid, + &handle, + &physAddr); + if (ret != 0) { + LOG_E("ipMcKMod->registerWsmL2() failed: %d", ret); + return NULL; + } - return new CWsm(buffer,len,handle,physAddr); + return new CWsm(buffer,len,handle,physAddr); } //------------------------------------------------------------------------------ -CWsm_ptr TrustZoneDevice::allocateContiguousPersistentWsm( - uint32_t len -) { - CWsm_ptr pWsm = NULL; - do - { - if (0 == len) - { - break; - } +CWsm_ptr TrustZoneDevice::allocateContiguousPersistentWsm(uint32_t len) +{ + CWsm_ptr pWsm = NULL; + // Allocate shared memory + addr_t virtAddr; + uint32_t handle; + addr_t physAddr; + + if (len == 0 ) { + return NULL; + } + + if (!pMcKMod->mapPersistent(len, &handle, &virtAddr, &physAddr)) { + return NULL; + } - // Allocate shared memory - addr_t virtAddr; - uint32_t handle; - addr_t physAddr; - int ret = pMcKMod->mapPersistent( - len, - &handle, - &virtAddr, - &physAddr); - if (0 != ret) - { - break; - } - - // Register (vaddr,paddr) with device - pWsm = new CWsm(virtAddr,len,handle,physAddr); - - } while(0); + // Register (vaddr,paddr) with device + pWsm = new CWsm(virtAddr, len, handle, physAddr); // Return pointer to the allocated memory return pWsm; @@ -570,9 +526,8 @@ CWsm_ptr TrustZoneDevice::allocateContiguousPersistentWsm( //------------------------------------------------------------------------------ -bool TrustZoneDevice::unregisterWsmL2( - CWsm_ptr pWsm -) { +bool TrustZoneDevice::unregisterWsmL2(CWsm_ptr pWsm) +{ int ret = pMcKMod->unregisterWsmL2(pWsm->handle); if (ret != 0) { LOG_E("pMcKMod->unregisterWsmL2 failed: %d", ret); @@ -595,16 +550,13 @@ bool TrustZoneDevice::schedulerAvailable( //------------------------------------------------------------------------------ //TODO Schedulerthread to be switched off if MC is idle. Will be woken up when // driver is called again. -void TrustZoneDevice::schedule( - void -) { - uint32_t timeslice = SCHEDULING_FREQ; +void TrustZoneDevice::schedule(void) +{ + uint32_t timeslice = SCHEDULING_FREQ; // loop forever - for (;;) - { + for (;;) { // Scheduling decision - if (MC_FLAG_SCHEDULE_IDLE == mcFlags->schedule) - { + if (MC_FLAG_SCHEDULE_IDLE == mcFlags->schedule) { // MobiCore is IDLE // Prevent unnecessary consumption of CPU cycles -> Wait until S-SIQ received @@ -614,8 +566,7 @@ void TrustZoneDevice::schedule( // MobiCore is not IDLE (anymore) // Check timeslice - if (0 == timeslice) - { + if (timeslice == 0) { // Slice expired, so force MC internal scheduling decision timeslice = SCHEDULING_FREQ; if(!nsiq()) { @@ -629,21 +580,21 @@ void TrustZoneDevice::schedule( } } } - } + } //for (;;) } //------------------------------------------------------------------------------ void TrustZoneDevice::handleIrq( void ) { - LOG_I("Starting NQ IRQ handler..."); + LOG_I("Starting Notification Queue IRQ handler..."); for (;;) { - LOG_I("NQ empty now"); + LOG_I(" No notifications pending"); if(!waitSsiq()) { LOG_E("Waiting for SSIQ failed"); break; } - LOG_I("S-SIQ received"); + LOG_V("S-SIQ received"); // Save all the for (;;) @@ -652,18 +603,22 @@ void TrustZoneDevice::handleIrq( if (NULL == notification) { break; } - LOG_I("Received notification, sessionId=%d, payload=%d", - notification->sessionId, notification->payload); - + // check if the notification belongs to the MCP session if (notification->sessionId == SID_MCP) { - // Signal main thread of the driver to continue after MCP + LOG_I(" Found MCP notification, payload=%d", + notification->payload); + + // Signal main thread of the driver to continue after MCP // command has been processed by the MC signalMcpNotification(); } else { - // Get the NQ connection for the session ID + LOG_I(" Found notification for session %d, payload=%d", + notification->sessionId, notification->payload); + + // Get the NQ connection for the session ID Connection *connection = getSessionConnection(notification->sessionId, notification); if (connection == NULL) { /* Couldn't find the session for this notifications @@ -677,7 +632,7 @@ void TrustZoneDevice::handleIrq( } else { - LOG_I("Write notification!"); + LOG_I(" Forward notification to McClient."); // Forward session ID and additional payload of // notification to the TLC/Application layer connection->writeData((void *)notification, diff --git a/mobicore/daemon/Daemon/Device/TrustletSession.cpp b/mobicore/daemon/Daemon/Device/TrustletSession.cpp index c0dfe4e..4effa72 100644 --- a/mobicore/daemon/Daemon/Device/TrustletSession.cpp +++ b/mobicore/daemon/Daemon/Device/TrustletSession.cpp @@ -32,7 +32,6 @@ #include "TrustletSession.h" #include <cstdlib> -#define LOG_TAG "McDaemon" #include "log.h" diff --git a/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp b/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp index bde00f3..55ec0b4 100644 --- a/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp +++ b/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp @@ -5,7 +5,7 @@ * Entry of the MobiCore Driver. * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -34,13 +34,12 @@ #include <cstdlib> #include <signal.h> #include <fcntl.h> -#include <fstream> -#include <cassert> +#include <stdio.h> #include "MobiCoreDriverCmd.h" #include "mcVersion.h" #include "mcVersionHelper.h" -#include "mc_drv_module_api.h" +#include "mc_linux.h" #include "MobiCoreDriverDaemon.h" #include "MobiCoreRegistry.h" @@ -48,7 +47,6 @@ #include "NetlinkServer.h" -#define LOG_TAG "McDaemon" #include "log.h" #define DRIVER_TCI_LEN 100 @@ -58,7 +56,7 @@ MC_CHECK_VERSION(MCI, 0, 2); MC_CHECK_VERSION(SO, 2, 0); MC_CHECK_VERSION(MCLF, 2, 0); -MC_CHECK_VERSION(CONTAINER, 2, 0); +MC_CHECK_VERSION(CONTAINER, 2, 0); static void checkMobiCoreVersion(MobiCoreDevice* mobiCoreDevice); @@ -122,16 +120,18 @@ void MobiCoreDriverDaemon::run( mobiCoreDevice = getDeviceInstance(); LOG_I("Daemon scheduler is %s", enableScheduler? "enabled" : "disabled"); + LOG_I("Initializing MobiCore Device"); if(!mobiCoreDevice->initDevice( - MC_DRV_MOD_DEVNODE_FULLPATH, + "/dev/" MC_ADMIN_DEVNODE, loadMobicore, mobicoreImage.c_str(), enableScheduler)) { - LOG_E("%s: Failed to initialize MobiCore!", __FUNCTION__); + LOG_E("Could not initialize MobiCore!"); return; } mobiCoreDevice->start(); + LOG_I("Checking version of MobiCore"); checkMobiCoreVersion(mobiCoreDevice); if (donateRamSize > 0) { @@ -145,11 +145,11 @@ void MobiCoreDriverDaemon::run( loadDeviceDriver(driverPath); } - LOG_I("Servers will be created!"); + LOG_I("Creating socket servers"); // Start listening for incoming TLC connections servers[0] = new NetlinkServer(this); servers[1] = new Server(this, SOCK_PATH); - LOG_I("Servers created!"); + LOG_I("Successfully created servers"); // Start all the servers for (i = 0; i < MAX_SERVERS; i++) { @@ -195,7 +195,7 @@ size_t MobiCoreDriverDaemon::writeResult( mcDrvRsp_t code ) { if (0 != code) { - LOG_E("writeResult(): set error code %d",code); + LOG_V(" sending error code %d",code); } return connection->writeData(&code, sizeof(mcDrvRsp_t)); } @@ -210,18 +210,19 @@ bool MobiCoreDriverDaemon::loadDeviceDriver( Connection *conn = NULL; uint8_t *tci = NULL; mcDrvRspOpenSession_t rspOpenSession; - + do { //mobiCoreDevice - ifstream fs(driverPath.c_str(), ios_base::binary); + FILE *fs = fopen (driverPath.c_str(), "rb"); if (!fs) { - LOG_E("%s: failed: cannot open %s", __func__, driverPath.c_str()); + LOG_E("%s: failed: cannot open %s", __FUNCTION__, driverPath.c_str()); break; } - - LOG_I("%s: loading %s", __func__, driverPath.c_str()); - + fclose(fs); + + LOG_I("%s: loading %s", __FUNCTION__, driverPath.c_str()); + regObj = mcRegistryGetDriverBlob(driverPath.c_str()); if (regObj == NULL) { break;; @@ -229,7 +230,7 @@ bool MobiCoreDriverDaemon::loadDeviceDriver( LOG_I("registering L2 in kmod, p=%p, len=%i", regObj->value, regObj->len); - + // Prepare the interface structure for memory registration, then // register virtual memory in kernel module, create L2 table // TODO xgal: refactor naming of datatypes and WSM handling @@ -246,7 +247,7 @@ bool MobiCoreDriverDaemon::loadDeviceDriver( loadDataOpenSession.offs = ((uint32_t) regObj->value) & 0xFFF; loadDataOpenSession.len = regObj->len; loadDataOpenSession.tlHeader = (mclfHeader_ptr) regObj->value; - + mcDrvCmdOpenSessionPayload_t openSessionPayload; tci = (uint8_t*)malloc(DRIVER_TCI_LEN); pTciWsm = mobiCoreDevice->registerWsmL2( @@ -266,28 +267,28 @@ bool MobiCoreDriverDaemon::loadDeviceDriver( &loadDataOpenSession, &openSessionPayload, &(rspOpenSession.payload)); - + // Unregister physical memory from kernel module. // This will also destroy the WSM object. mobiCoreDevice->unregisterWsmL2(pWsm); pWsm = NULL; - + // Free memory occupied by Trustlet data free(regObj); regObj = NULL; - + if (rspOpenSession.payload.mcResult != MC_MCP_RET_OK) { - LOG_E("%s: rspOpenSession mcResult %d", __func__, + LOG_E("%s: rspOpenSession mcResult %d", __FUNCTION__, rspOpenSession.payload.mcResult); break; } - + ret = true; } while (false); // Free all allocated resources if (ret == false) { - LOG_I("%s: Freeing previously allocated resources!", __func__); + LOG_I("%s: Freeing previously allocated resources!", __FUNCTION__); if (pWsm != NULL) { if(!mobiCoreDevice->unregisterWsmL2(pWsm)) { // At least make sure we don't leak the WSM object @@ -296,7 +297,7 @@ bool MobiCoreDriverDaemon::loadDeviceDriver( } // No matter if we free NULL objects free(regObj); - + if (conn != NULL) { delete conn; } @@ -304,7 +305,7 @@ bool MobiCoreDriverDaemon::loadDeviceDriver( driverResources.push_back(new MobicoreDriverResources( conn, tci, pTciWsm, rspOpenSession.payload.sessionId)); } - + return ret; } @@ -335,7 +336,7 @@ void MobiCoreDriverDaemon::processOpenDevice( break; } - LOG_I("processOpenDevice(): deviceId is %d", + LOG_I(" Opening deviceId %d ", cmdOpenDevicePayload.deviceId); // Get device for device ID @@ -439,9 +440,7 @@ void MobiCoreDriverDaemon::processOpenSession( { // Trustlet retrieved from registry - LOG_I("registering L2 in kmod, p=%p, len=%i", - regObj->value, - regObj->len); + LOG_I(" Sharing Service loaded at %p with Secure World", (addr_t)(regObj->value)); // Prepare the interface structure for memory registration, then // register virtual memory in kernel module, create L2 table @@ -462,7 +461,7 @@ void MobiCoreDriverDaemon::processOpenSession( loadDataOpenSession.offs = ((uint32_t) regObj->value) & 0xFFF; loadDataOpenSession.len = regObj->len; loadDataOpenSession.tlHeader = (mclfHeader_ptr) regObj->value; - + device->openSession( connection, &loadDataOpenSession, @@ -470,8 +469,11 @@ void MobiCoreDriverDaemon::processOpenSession( &(rspOpenSession.payload)); // Unregister physical memory from kernel module. - // This will also destroy the WSM object. + LOG_I(" Service buffer was copied to Secure world and processed. Stop sharing of buffer."); + + // This will also destroy the WSM object. if(!device->unregisterWsmL2(pWsm)) { + // TODO-2012-07-02-haenellu: Can this ever happen? And if so, we should assert(), also TL would still be running. writeResult(connection, MC_DRV_RSP_FAILED); break; } @@ -484,7 +486,7 @@ void MobiCoreDriverDaemon::processOpenSession( mcDrvRsp_t responseId = MC_DRV_RSP_FAILED; - switch (mcResult) + switch (mcResult) { case MC_MCP_RET_OK: responseId = MC_DRV_RSP_OK; @@ -517,7 +519,7 @@ void MobiCoreDriverDaemon::processOpenSession( if (MC_MCP_RET_OK != mcResult) { - LOG_E("rspOpenSession mcResult %d", mcResult); + LOG_V("MCP OPEN returned code %d", mcResult); writeResult(connection, responseId); break; } @@ -626,7 +628,7 @@ void MobiCoreDriverDaemon::processNqConnect( writeResult(connection, MC_DRV_RSP_OK); ts->processQueuedNotifications(); - + } while (false); } @@ -757,7 +759,8 @@ void MobiCoreDriverDaemon::processUnmapBulkBuf( uint32_t mcResult = rspUnmpaBulk.payload.mcResult; if (MC_MCP_RET_OK != mcResult) { - LOG_E("processUnmapBulkBuf(): rspUnmpaBulk mcResult %d", mcResult); + LOG_V("MCP UNMAP returned code %d", mcResult); + // TODO-2012-08-03-haenellu: Think about better error codes here. writeResult(connection, MC_DRV_RSP_FAILED); break; } @@ -821,7 +824,7 @@ bool MobiCoreDriverDaemon::handleConnection( ) { bool ret = false; static CMutex mutex; - + /* In case of RTM fault do not try to signal anything to MobiCore * just answer NO to all incoming connections! */ if (mobiCoreDevice->getMcFault()) { @@ -839,11 +842,12 @@ bool MobiCoreDriverDaemon::handleConnection( if (0 == rlen) { - LOG_I("handleConnection(): Connection closed."); + LOG_V(" handleConnection(): Connection closed."); break; } if (sizeof(mcDrvCommandHeader) != rlen) { + //TODO-2012-07-30-haenellu: wrong log message, on error, rlen will more likely be -1 or -2 LOG_E("handleConnection(): Header length error: %d", rlen); break; } @@ -949,7 +953,7 @@ int main( MobiCoreDriverDaemon *mobiCoreDriverDaemon = NULL; // Process signal action struct sigaction action; - + // Read the Command line options extern char *optarg; extern int optopt; @@ -1012,7 +1016,7 @@ int main( else if (i > 0) { exit(0); } - + // obtain a new process group */ setsid(); /* close all descriptors */ @@ -1020,7 +1024,7 @@ int main( close(i); } // STDIN, STDOUT and STDERR should all point to /dev/null */ - i = open("/dev/null",O_RDWR); + i = open("/dev/null",O_RDWR); dup(i); dup(i); /* ignore tty signals */ @@ -1037,7 +1041,7 @@ int main( sigaction (SIGHUP, &action, NULL); sigaction (SIGTERM, &action, NULL); signal(SIGPIPE, SIG_IGN); - + mobiCoreDriverDaemon = new MobiCoreDriverDaemon( /* Scheduler status */ schedulerFlag, diff --git a/mobicore/daemon/Daemon/Server/Android.mk b/mobicore/daemon/Daemon/Server/Android.mk index 1831793..3f92d73 100644 --- a/mobicore/daemon/Daemon/Server/Android.mk +++ b/mobicore/daemon/Daemon/Server/Android.mk @@ -7,12 +7,11 @@ # This is not a separate module. # Only for inclusion by other modules. -MY_MCDRV_SERVER_PATH := $(call my-dir) -MY_MCDRV_SERVER_PATH_REL := Server +SERVER_PATH := Daemon/Server # Add new folders with header files here -LOCAL_C_INCLUDES += $(MY_MCDRV_SERVER_PATH)/public +LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(SERVER_PATH)/public # Add new source files here -LOCAL_SRC_FILES += $(MY_MCDRV_SERVER_PATH_REL)/Server.cpp \ - $(MY_MCDRV_SERVER_PATH_REL)/NetlinkServer.cpp +LOCAL_SRC_FILES += $(SERVER_PATH)/Server.cpp \ + $(SERVER_PATH)/NetlinkServer.cpp diff --git a/mobicore/daemon/Daemon/Server/NetlinkServer.cpp b/mobicore/daemon/Daemon/Server/NetlinkServer.cpp index 3e12dc8..7421a1f 100644 --- a/mobicore/daemon/Daemon/Server/NetlinkServer.cpp +++ b/mobicore/daemon/Daemon/Server/NetlinkServer.cpp @@ -57,13 +57,13 @@ void NetlinkServer::run( ) { do { - LOG_I("%s: start listening on netlink bus", __func__); + LOG_I("NetlinkServer: Starting to listen on netlink bus"); // Open a socket serverSock = socket(PF_NETLINK, SOCK_DGRAM, MC_DAEMON_NETLINK); if (serverSock < 0) { - LOG_E("run(): can't open socket, errno=%d", errno); + LOG_ERRNO("Opening socket"); break; } @@ -79,8 +79,7 @@ void NetlinkServer::run( src_addr.nl_pid = MC_DAEMON_PID; /* daemon pid */ src_addr.nl_groups = 0; /* not in mcast groups */ if(bind(serverSock, (struct sockaddr*)&src_addr, sizeof(src_addr)) < 0){ - LOG_E("bind() to server socket failed, errno=%d(%s)", - errno, strerror(errno)); + LOG_ERRNO("Binding to server socket failed, because bind"); close(serverSock); break; } @@ -105,8 +104,7 @@ void NetlinkServer::run( // Read the incomming message and route it to the connection based // on the incomming PID if ((len = recvmsg(serverSock, &msg, 0)) < 0) { - LOG_E("%s: recvmsg() failed, errno=%d(%s)", - __func__, errno, strerror(errno)); + LOG_ERRNO("recvmsg"); break; } @@ -118,8 +116,7 @@ void NetlinkServer::run( } } while(false); - LOG_E("%s: exiting due to error, errno=%d(%s)", - __func__, errno, strerror(errno)); + LOG_ERRNO("Exiting NetlinkServer! Because it"); } //------------------------------------------------------------------------------ @@ -128,7 +125,7 @@ void NetlinkServer::handleMessage( ) { uint32_t seq = nlh->nlmsg_seq; uint32_t pid = nlh->nlmsg_pid; - //LOG_I("%s: Handling NQ message for pid %u seq %u...", __func__, pid, seq); + //LOG_I("%s: Handling NQ message for pid %u seq %u...", __FUNCTION__, pid, seq); uint64_t hash = hashConnection(pid, seq); /* First cleanup the connection list */ cleanupConnections(); @@ -136,7 +133,7 @@ void NetlinkServer::handleMessage( NetlinkConnection *connection = findConnection(hash); // This is a message from a new client if (connection == NULL) { - //LOG_I("%s: Cound't find the connection, creating a new one", __func__); + //LOG_I("%s: Cound't find the connection, creating a new one", __FUNCTION__); connection = new NetlinkConnection(this, serverSock, pid, seq); // Add the new connection insertConnection(hash, connection); @@ -149,7 +146,7 @@ void NetlinkServer::handleMessage( { if (!connectionHandler->handleConnection(connection)) { - LOG_I("%s: No command processed.", __func__); + LOG_I("%s: No command processed.", __FUNCTION__); connection->socketDescriptor = -1; //Inform the driver connectionHandler->dropConnection(connection); @@ -240,7 +237,7 @@ void NetlinkServer::cleanupConnections( connection = i->second; // Only 16 bits are for the actual PID, the rest is session magic pid = connection->peerPid & 0xFFFF; - //LOG_I("%s: checking PID %u", __func__, pid); + //LOG_I("%s: checking PID %u", __FUNCTION__, pid); // Check if the peer pid is still alive if (pid == 0) { continue; @@ -248,7 +245,7 @@ void NetlinkServer::cleanupConnections( if (kill(pid, 0)) { bool detached = connection->detached; LOG_I("%s: PID %u has died, cleaning up session 0x%X", - __func__, pid, connection->peerPid); + __FUNCTION__, pid, connection->peerPid); connection->socketDescriptor = -1; //Inform the driver diff --git a/mobicore/daemon/Daemon/Server/Server.cpp b/mobicore/daemon/Daemon/Server/Server.cpp index e61a8b2..975c82b 100644 --- a/mobicore/daemon/Daemon/Server/Server.cpp +++ b/mobicore/daemon/Daemon/Server/Server.cpp @@ -37,10 +37,9 @@ #include <string.h> #include <errno.h> -#define LOG_TAG "McDaemon" +//#define LOG_VERBOSE #include "log.h" - //------------------------------------------------------------------------------ Server::Server( ConnectionHandler * connectionHandler, @@ -57,13 +56,13 @@ void Server::run( ) { do { - LOG_I("run(): start listening on socket %s", socketAddr.c_str()); + LOG_I("Server: start listening on socket %s", socketAddr.c_str()); // Open a socket (a UNIX domain stream socket) serverSock = socket(AF_UNIX, SOCK_STREAM, 0); if (serverSock < 0) { - LOG_E("run(): can't open stream socket, errno=%d", errno); + LOG_ERRNO("Can't open stream socket, because socket"); break; } @@ -77,17 +76,17 @@ void Server::run( serverAddr.sun_path[0] = 0; if (bind(serverSock, (struct sockaddr *) &serverAddr, len) < 0) { - LOG_E("bind() to server socket failed, errno=%d", errno); + LOG_ERRNO("Binding to server socket failed, because bind"); } // Start listening on the socket if (listen(serverSock, LISTEN_QUEUE_LEN) < 0) { - LOG_E("run(): listen() failed, errno=%d", errno); + LOG_ERRNO("listen"); break; } - LOG_I("\n********* successfully initialized *********\n"); + LOG_I("\n********* successfully initialized Daemon *********\n"); for (;;) { @@ -116,7 +115,7 @@ void Server::run( // Wait for activities, select() returns the number of sockets // which require processing - LOG_I("run(): waiting on sockets"); + LOG_V(" Server: waiting on sockets"); int numSockets = select( maxSocketDescriptor + 1, &fdReadSockets, @@ -125,25 +124,25 @@ void Server::run( // Check if select failed if (numSockets < 0) { - LOG_E("run(): select() failed, errno=%d", errno); + LOG_ERRNO("select"); break; } // actually, this should not happen. if (0 == numSockets) { - LOG_W("run(): select() returned 0, spurious event?."); + LOG_W(" Server: select() returned 0, spurious event?."); continue; } - LOG_I("run(): events on %d socket(s).", numSockets); + LOG_V(" Server: events on %d socket(s).", numSockets); // Check if a new client connected to the server socket if (FD_ISSET(serverSock, &fdReadSockets)) { do { - LOG_I("run(): new connection"); + LOG_V(" Server: new connection attempt."); numSockets--; struct sockaddr_un clientAddr; @@ -155,13 +154,13 @@ void Server::run( if (clientSock <= 0) { - LOG_E("run(): accept() failed, errno=%d", errno); + LOG_ERRNO("accept"); break; } Connection *connection = new Connection(clientSock, &clientAddr); peerConnections.push_back(connection); - LOG_I("run(): added new connection"); + LOG_I(" Server: new socket connection established and start listening."); } while (false); // we can ignore any errors from accepting a new connection. @@ -189,7 +188,7 @@ void Server::run( // fails if (!connectionHandler->handleConnection(connection)) { - LOG_I("run(): No command processed."); + LOG_I(" Server: dropping connection."); //Inform the driver connectionHandler->dropConnection(connection); @@ -206,7 +205,7 @@ void Server::run( } while (false); - LOG_E("run(): exiting due to error, errno=%d", errno); + LOG_ERRNO("Exiting Server, because"); } @@ -214,7 +213,7 @@ void Server::run( void Server::detachConnection( Connection *connection ) { - LOG_I("Detaching NQ connection..."); + LOG_V(" Stopping to listen on notification socket."); for (connectionIterator_t iterator = peerConnections.begin(); iterator != peerConnections.end(); @@ -224,7 +223,7 @@ void Server::detachConnection( if (tmpConnection == connection) { peerConnections.erase(iterator); - LOG_I("NQ connection detached"); + LOG_I(" Stopped listening on notification socket."); break; } } diff --git a/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h b/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h index 15be3a6..b329897 100644 --- a/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h +++ b/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h @@ -77,59 +77,64 @@ typedef enum { typedef struct { uint32_t commandId; -} mcDrvCommandHeader_t, *mcDrvCommandHeader_ptr; +} mcDrvCommandHeader_t; typedef struct { uint32_t responseId; -} mcDrvResponseHeader_t, *mcDrvResponseHeader_ptr; +} mcDrvResponseHeader_t; #define MC_DEVICE_ID_DEFAULT 0 /**< The default device ID */ //-------------------------------------------------------------- +struct MC_DRV_CMD_OPEN_DEVICE_struct { + uint32_t commandId; + uint32_t deviceId; +}; + typedef struct{ uint32_t deviceId; -} mcDrvCmdOpenDevicePayload_t, *mcDrvCmdOpenDevicePayload_ptr; +} mcDrvCmdOpenDevicePayload_t; typedef struct{ mcDrvCommandHeader_t header; mcDrvCmdOpenDevicePayload_t payload; -} mcDrvCmdOpenDevice_t, *mcDrvCmdOpenDevice_ptr; +} mcDrvCmdOpenDevice_t; typedef struct{ - // empty -} mcDrvRspOpenDevicePayload_t, *mcDrvRspOpenDevicePayload_ptr; - -typedef struct{ mcDrvResponseHeader_t header; - mcDrvRspOpenDevicePayload_t payload; -} mcDrvRspOpenDevice_t, *mcDrvRspOpenDevice_ptr; - +} mcDrvRspOpenDevice_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_CLOSE_DEVICE_struct { + uint32_t commandId; +}; + typedef struct{ mcDrvCommandHeader_t header; // no payload here because close has none. // If we use an empty struct, C++ will count it as 4 bytes. // This will write too much into the socket at write(cmd,sizeof(cmd)) -} mcDrvCmdCloseDevice_t, *mcDrvCmdCloseDevice_ptr; +} mcDrvCmdCloseDevice_t; typedef struct{ - // empty -} mcDrvRspCloseDevicePayload_t, *mcDrvRspCloseDevicePayload_ptr; - -typedef struct{ mcDrvResponseHeader_t header; - mcDrvRspCloseDevicePayload_t payload; -} mcDrvRspCloseDevice_t, *mcDrvRspCloseDevice_ptr; - +} mcDrvRspCloseDevice_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_OPEN_SESSION_struct { + uint32_t commandId; + uint32_t deviceId; + mcUuid_t uuid; + uint32_t tci; + uint32_t len; +}; + typedef struct{ uint32_t deviceId; - mcUuid_t uuid; + mcUuid_t uuid; uint32_t tci; uint32_t len; } mcDrvCmdOpenSessionPayload_t, *mcDrvCmdOpenSessionPayload_ptr; @@ -137,7 +142,7 @@ typedef struct{ typedef struct{ mcDrvCommandHeader_t header; mcDrvCmdOpenSessionPayload_t payload; -} mcDrvCmdOpenSession_t, *mcDrvCmdOpenSession_ptr; +} mcDrvCmdOpenSession_t; typedef struct{ @@ -151,52 +156,60 @@ typedef struct{ typedef struct{ mcDrvResponseHeader_t header; mcDrvRspOpenSessionPayload_t payload; -} mcDrvRspOpenSession_t, *mcDrvRspOpenSession_ptr; +} mcDrvRspOpenSession_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_CLOSE_SESSION_struct { + uint32_t commandId; + uint32_t sessionId; +}; + typedef struct{ uint32_t sessionId; -} mcDrvCmdCloseSessionPayload_t, *mcDrvCmdCloseSessionPayload_ptr; +} mcDrvCmdCloseSessionPayload_t; typedef struct{ mcDrvCommandHeader_t header; mcDrvCmdCloseSessionPayload_t payload; -} mcDrvCmdCloseSession_t, *mcDrvCmdCloseSession_ptr; - +} mcDrvCmdCloseSession_t; -typedef struct{ - // empty -} mcDrvRspCloseSessionPayload_t, *mcDrvRspCloseSessionPayload_ptr; typedef struct{ mcDrvResponseHeader_t header; - mcDrvRspCloseSessionPayload_t payload; -} mcDrvRspCloseSession_t, *mcDrvRspCloseSession_ptr; +} mcDrvRspCloseSession_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_NOTIFY_struct { + uint32_t commandId; + uint32_t sessionId; +}; + typedef struct{ uint32_t sessionId; -} mcDrvCmdNotifyPayload_t, *mcDrvCmdNotifyPayload_ptr; +} mcDrvCmdNotifyPayload_t; typedef struct{ mcDrvCommandHeader_t header; mcDrvCmdNotifyPayload_t payload; -} mcDrvCmdNotify_t, *mcDrvCmdNotify_ptr; - +} mcDrvCmdNotify_t; -typedef struct{ - // empty -} mcDrvRspNotifyPayload_t, *mcDrvRspNotifyPayload_ptr; typedef struct{ mcDrvResponseHeader_t header; - mcDrvRspNotifyPayload_t payload; -} mcDrvRspNotify_t, *mcDrvRspNotify_ptr; +} mcDrvRspNotify_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_MAP_BULK_BUF_struct { + uint32_t commandId; + uint32_t sessionId; + uint32_t pAddrL2; + uint32_t offsetPayload; + uint32_t lenBulkMem; +}; + typedef struct{ uint32_t sessionId; uint32_t pAddrL2; @@ -207,7 +220,7 @@ typedef struct{ typedef struct{ mcDrvCommandHeader_t header; mcDrvCmdMapBulkMemPayload_t payload; -} mcDrvCmdMapBulkMem_t, *mcDrvCmdMapBulkMem_ptr; +} mcDrvCmdMapBulkMem_t; typedef struct{ @@ -219,10 +232,17 @@ typedef struct{ typedef struct{ mcDrvResponseHeader_t header; mcDrvRspMapBulkMemPayload_t payload; -} mcDrvRspMapBulkMem_t, *mcDrvRspMapBulkMem_ptr; +} mcDrvRspMapBulkMem_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_UNMAP_BULK_BUF_struct { + uint32_t commandId; + uint32_t sessionId; + uint32_t secureVirtualAdr; + uint32_t lenBulkMem; +}; + typedef struct{ uint32_t sessionId; uint32_t secureVirtualAdr; @@ -232,7 +252,7 @@ typedef struct{ typedef struct{ mcDrvCommandHeader_t header; mcDrvCmdUnmapBulkMemPayload_t payload; -} mcDrvCmdUnmapBulkMem_t, *mcDrvCmdUnmapBulkMem_ptr; +} mcDrvCmdUnmapBulkMem_t; typedef struct{ @@ -244,10 +264,18 @@ typedef struct{ typedef struct{ mcDrvResponseHeader_t header; mcDrvRspUnmapBulkMemPayload_t payload; -} mcDrvRspUnmapBulkMem_t, *mcDrvRspUnmapBulkMem_ptr; +} mcDrvRspUnmapBulkMem_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_NQ_CONNECT_struct { + uint32_t commandId; + uint32_t deviceId; + uint32_t sessionId; + uint32_t deviceSessionId; + uint32_t sessionMagic; //Random data +}; + typedef struct { uint32_t deviceId; uint32_t sessionId; @@ -258,37 +286,40 @@ typedef struct { typedef struct { mcDrvCommandHeader_t header; mcDrvCmdNqConnectPayload_t payload; -} mcDrvCmdNqConnect_t, *mcDrvCmdNqConnect_ptr; - +} mcDrvCmdNqConnect_t; -typedef struct { - // empty; -} mcDrvRspNqConnectPayload_t, *mcDrvRspNqConnectPayload_ptr; typedef struct{ mcDrvResponseHeader_t header; - mcDrvRspNqConnectPayload_t payload; -} mcDrvRspNqConnect_t, *mcDrvRspNqConnect_ptr; +} mcDrvRspNqConnect_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_GET_VERSION_struct { + uint32_t commandId; +}; + typedef struct { mcDrvCommandHeader_t header; -} mcDrvCmdGetVersion_t, *mcDrvCmdGetVersion_ptr; +} mcDrvCmdGetVersion_t; typedef struct { uint32_t version; -} mcDrvRspGetVersionPayload_t, *mcDrvRspGetVersionPayload_ptr; +} mcDrvRspGetVersionPayload_t; typedef struct{ mcDrvResponseHeader_t header; mcDrvRspGetVersionPayload_t payload; -} mcDrvRspGetVersion_t, mcDrvRspGetVersion_ptr; +} mcDrvRspGetVersion_t; //-------------------------------------------------------------- +struct MC_DRV_CMD_GET_MOBICORE_VERSION_struct { + uint32_t commandId; +}; + typedef struct { mcDrvCommandHeader_t header; -} mcDrvCmdGetMobiCoreVersion_t, *mcDrvCmdGetMobiCoreVersion_ptr; +} mcDrvCmdGetMobiCoreVersion_t; typedef struct { @@ -299,7 +330,7 @@ typedef struct { typedef struct{ mcDrvResponseHeader_t header; mcDrvRspGetMobiCoreVersionPayload_t payload; -} mcDrvRspGetMobiCoreVersion_t, mcDrvRspGetMobiCoreVersion_ptr; +} mcDrvRspGetMobiCoreVersion_t; //-------------------------------------------------------------- typedef union { diff --git a/mobicore/daemon/Kernel/Android.mk b/mobicore/daemon/Kernel/Android.mk index 9caae0e..a01b410 100644 --- a/mobicore/daemon/Kernel/Android.mk +++ b/mobicore/daemon/Kernel/Android.mk @@ -1,38 +1,20 @@ # ============================================================================= # -# Module: libKernel.a - Kernel module access classes +# Module: Kernel Module access +# All paths are relative to application root! # # ============================================================================= -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) -LOCAL_MODULE := libMcKernel +include $(LOCAL_PATH)/Kernel/Platforms/Generic/Android.mk # Include platform specific sub-makefiles -ifdef PLATFORM - include $(LOCAL_PATH)/Platforms/Generic/Android.mk - include $(LOCAL_PATH)/Platforms/$(PLATFORM)/Android.mk -else - include $(LOCAL_PATH)/Platforms/Generic/Android.mk +ifdef $(PLATFORM) + include $(LOCAL_PATH)/Kernel/Platforms/$(PLATFORM)/Android.mk endif -# Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(COMP_PATH_MobiCoreDriverMod)/Public \ - $(APP_PROJECT_PATH)/Common \ - $(LOCAL_PATH) - # Add new source files here -LOCAL_SRC_FILES +=\ - CKMod.cpp +LOCAL_SRC_FILES += Kernel/CKMod.cpp # Header files for components including this module -LOCAL_EXPORT_C_INCLUDES +=\ - $(LOCAL_PATH) - -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions - -include $(COMP_PATH_Logwrapper)/Android.mk - -include $(BUILD_STATIC_LIBRARY) +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Kernel diff --git a/mobicore/daemon/Kernel/CKMod.cpp b/mobicore/daemon/Kernel/CKMod.cpp index a78b87d..d144b00 100644 --- a/mobicore/daemon/Kernel/CKMod.cpp +++ b/mobicore/daemon/Kernel/CKMod.cpp @@ -5,7 +5,7 @@ * Kernel Module Interface. * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -38,62 +38,51 @@ #include "CKMod.h" -#define LOG_TAG "McDaemon" #include "log.h" //------------------------------------------------------------------------------ -CKMod::CKMod( - void -) { +CKMod::CKMod(void) +{ fdKMod = ERROR_KMOD_NOT_OPEN; } //------------------------------------------------------------------------------ -CKMod::~CKMod( - void -) { +CKMod::~CKMod(void) +{ close(); } //------------------------------------------------------------------------------ -bool CKMod::isOpen( - void -) { +bool CKMod::isOpen(void) +{ return (ERROR_KMOD_NOT_OPEN == fdKMod) ? false : true; } //------------------------------------------------------------------------------ -bool CKMod::open( - const char *deviceName -) { +bool CKMod::open(const char *deviceName) +{ bool ret = true; + int openRet; - do - { - if (isOpen()) - { - LOG_W("already open"); - ret = false; - break; - } - - // open return -1 on error, "errno" is set with details - int openRet = ::open(deviceName, O_RDWR); - if (-1 == openRet) - { - LOG_E("open failed with errno: %d", errno); - ret = false; - break; - } + if (isOpen()) { + LOG_W("already open"); + return false; + } - fdKMod = openRet; + LOG_I(" Opening kernel module at %s.", deviceName); - } while(0); + // open return -1 on error, "errno" is set with details + openRet = ::open(deviceName, O_RDWR); + if (openRet ==-1) { + LOG_ERRNO("open"); + return false; + } + fdKMod = openRet; return ret; } @@ -102,20 +91,16 @@ bool CKMod::open( void CKMod::close( void ) { - if (isOpen()) - { - if (0 != ::close(fdKMod)) - { - LOG_E("close failed with errno: %d", errno); + if (isOpen()) { + if (::close(fdKMod) != 0) { + LOG_ERRNO("close"); } - else - { + else { fdKMod = ERROR_KMOD_NOT_OPEN; } } - else - { - LOG_W("not open"); + else { + LOG_W(" Kernel module device not open"); } } diff --git a/mobicore/daemon/Kernel/Platforms/Generic/Android.mk b/mobicore/daemon/Kernel/Platforms/Generic/Android.mk index ac816f1..8b4b8b4 100644 --- a/mobicore/daemon/Kernel/Platforms/Generic/Android.mk +++ b/mobicore/daemon/Kernel/Platforms/Generic/Android.mk @@ -5,23 +5,11 @@ # ============================================================================= # This is not a separate module. -# Only for inclusion by other modules. - -GENERIC_MODULE_PATH := $(call my-dir) -GENERIC_MODULE_PATH_REL := Platforms/Generic +# All paths are relative to APP_PROJECT_PATH! +KERNEL_PATH := Kernel/Platforms/Generic # Add new source files here -LOCAL_SRC_FILES +=\ - $(GENERIC_MODULE_PATH_REL)/CMcKMod.cpp - -# Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(GENERIC_MODULE_PATH)\ - $(COMP_PATH_MobiCore)/inc\ - $(COMP_PATH_MobiCoreDriverMod)/Public +LOCAL_SRC_FILES += $(KERNEL_PATH)/CMcKMod.cpp # Header files for components including this module -LOCAL_EXPORT_C_INCLUDES +=\ - $(GENERIC_MODULE_PATH)\ - $(COMP_PATH_MobiCoreDriverMod)/Public -
\ No newline at end of file +LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(KERNEL_PATH) diff --git a/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.cpp b/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.cpp index 1973ac1..fb81f07 100644 --- a/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.cpp +++ b/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.cpp @@ -5,7 +5,7 @@ * MobiCore Driver Kernel Module Interface. * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -39,368 +39,291 @@ #include <cstring> #include "McTypes.h" -#include "mc_drv_module_api.h" +#include "mc_linux.h" #include "mcVersionHelper.h" #include "CMcKMod.h" -#define LOG_TAG "McDaemon" #include "log.h" //------------------------------------------------------------------------------ MC_CHECK_VERSION(MCDRVMODULEAPI,0,1); -// TODO: rename this to mapWsm //------------------------------------------------------------------------------ -int CMcKMod::mmap( +int CMcKMod::mapWsm( uint32_t len, uint32_t *pHandle, addr_t *pVirtAddr, - addr_t *pPhysAddr, - bool *pMciReuse -) { + addr_t *pPhysAddr) +{ int ret = 0; - do + LOG_V(" mapWsm(): len=%d", len); + + if (!isOpen()) + { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + // mapping response data is in the buffer + struct mc_ioctl_map mapParams = { len: len}; + + ret = ioctl(fdKMod, MC_IO_MAP_WSM, &mapParams); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_MAP_WSM"); + return ERROR_MAPPING_FAILED; + } + + addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, + fdKMod, mapParams.phys_addr); + if (virtAddr == MAP_FAILED) { - LOG_I("mmap(): len=%d, mci_reuse=%x", len, *pMciReuse); - - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - // TODO: add type parameter to distinguish between non-freeing TCI, MCI and others - addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, - fdKMod, *pMciReuse ? MC_DRV_KMOD_MMAP_MCI - : MC_DRV_KMOD_MMAP_WSM); - if (MAP_FAILED == virtAddr) - { - LOG_E("mmap() failed with errno: %d", errno); - ret = ERROR_MAPPING_FAILED; - break; - } - - // mapping response data is in the buffer - struct mc_mmap_resp *pMmapResp = (struct mc_mmap_resp *) virtAddr; - - *pMciReuse = pMmapResp->is_reused; - - LOG_I("mmap(): virtAddr=%p, handle=%d, phys_addr=%p, is_reused=%s", - virtAddr, pMmapResp->handle, (addr_t) (pMmapResp->phys_addr), - pMmapResp->is_reused ? "true" : "false"); - - if (NULL != pVirtAddr) - { - *pVirtAddr = virtAddr; - } - - if (NULL != pHandle) - { - *pHandle = pMmapResp->handle; - } - - if (NULL != pPhysAddr) - { - *pPhysAddr = (addr_t) (pMmapResp->phys_addr); - } - - // clean memory - memset(pMmapResp, 0, sizeof(*pMmapResp)); - - } while (0); + LOG_ERRNO("mmap"); + return ERROR_MAPPING_FAILED; + } - return ret; -} + LOG_V(" mapped to %p, handle=%d, phys=%p ", virtAddr, + mapParams.handle, (addr_t) (mapParams.phys_addr)); + + if (pVirtAddr != NULL) { + *pVirtAddr = virtAddr; + } + + if (pHandle != NULL) { + *pHandle = mapParams.handle; + } + + if (pPhysAddr != NULL) { + *pPhysAddr = (addr_t) (mapParams.phys_addr); + } + + return 0; +} //------------------------------------------------------------------------------ -int CMcKMod::mapPersistent( +int CMcKMod::mapMCI( uint32_t len, uint32_t *pHandle, addr_t *pVirtAddr, - addr_t *pPhysAddr -) { + addr_t *pPhysAddr, + bool *pReuse) +{ int ret = 0; - do + LOG_I("Mapping MCI: len=%d", len); + // mapping response data is in the buffer + struct mc_ioctl_map mapParams = { len: len}; + + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + ret = ioctl(fdKMod, MC_IO_MAP_MCI, &mapParams); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_MAP_MCI"); + return ERROR_MAPPING_FAILED; + } + + addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, + fdKMod, 0); + if (virtAddr == MAP_FAILED) { - LOG_I("mapPersistent(): len=%d", len); - - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, - fdKMod, MC_DRV_KMOD_MMAP_PERSISTENTWSM); - - if (MAP_FAILED == virtAddr) - { - LOG_E("mmap() failed with errno: %d", errno); - ret = ERROR_MAPPING_FAILED; - break; - } + LOG_ERRNO("mmap"); + return ERROR_MAPPING_FAILED; + } + mapParams.addr = (unsigned long)virtAddr; + *pReuse = mapParams.reused; - // mapping response data is in the buffer - struct mc_mmap_resp *pMmapResp = (struct mc_mmap_resp *) virtAddr; + LOG_V(" MCI mapped to %p, handle=%d, phys=%p, reused=%s", + (void*)mapParams.addr, mapParams.handle, (addr_t) (mapParams.phys_addr), + mapParams.reused ? "true" : "false"); - LOG_I("mapPersistent(): virtAddr=%p, handle=%d, phys_addr=%p, is_reused=%s", - virtAddr, pMmapResp->handle, - (addr_t) (pMmapResp->phys_addr), - pMmapResp->is_reused ? "true" : "false"); + if (pVirtAddr != NULL) { + *pVirtAddr = (void*)mapParams.addr; + } - if (NULL != pVirtAddr) - { - *pVirtAddr = virtAddr; - } + if (pHandle != NULL) { + *pHandle = mapParams.handle; + } - if (NULL != pHandle) - { - *pHandle = pMmapResp->handle; - } + if (pPhysAddr != NULL) { + *pPhysAddr = (addr_t) (mapParams.phys_addr); + } - if (NULL != pPhysAddr) - { - *pPhysAddr = (addr_t) (pMmapResp->phys_addr); - } - - // clean memory - memset(pMmapResp, 0, sizeof(*pMmapResp)); - - } while (0); + // clean memory + //memset(pMmapResp, 0, sizeof(*pMmapResp)); return ret; } - //------------------------------------------------------------------------------ -int CMcKMod::read( - addr_t buffer, - uint32_t len -) { - int ret = 0; +int CMcKMod::mapPersistent( + uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + addr_t *pPhysAddr) +{ + // Not currently supported by the driver + LOG_E("MobiCore Driver does't support persistent buffers"); + return ERROR_MAPPING_FAILED; +} - do - { - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - ret = ::read(fdKMod, buffer, len); - if(-1 == ret) - { - LOG_E("read() failed with errno: %d", errno); - } +//------------------------------------------------------------------------------ +int CMcKMod::read(addr_t buffer, uint32_t len) +{ + int ret = 0; - } while (0); + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + ret = ::read(fdKMod, buffer, len); + if(ret == -1) { + LOG_ERRNO("read"); + } return ret; } //------------------------------------------------------------------------------ -bool CMcKMod::waitSSIQ( - uint32_t *pCnt -) { - int ret = true; - - do - { - uint32_t cnt; - int ret = read(&cnt, sizeof(cnt)); - if (sizeof(cnt) != ret) - { - ret = false; - } - - if (NULL != pCnt) - { - *pCnt = cnt; - } - - } while (0); - - return ret; +bool CMcKMod::waitSSIQ(uint32_t *pCnt) +{ + uint32_t cnt; + if (read(&cnt, sizeof(cnt)) != sizeof(cnt)) { + LOG_ERRNO("read"); + return false; + } + + if (pCnt != NULL) { + *pCnt = cnt; + } + + return true; } //------------------------------------------------------------------------------ -int CMcKMod::fcInit( - addr_t mciBuffer, - uint32_t nqOffset, - uint32_t nqLength, - uint32_t mcpOffset, - uint32_t mcpLength -) { +int CMcKMod::fcInit(uint32_t nqOffset, uint32_t nqLength, uint32_t mcpOffset, + uint32_t mcpLength) +{ int ret = 0; - do - { - if (!isOpen()) - { - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - // Init MC with NQ and MCP buffer addresses - union mc_ioctl_init_params fcInitParams = { - // C++ does not support C99 designated initializers - /* .in = */{ - /* .base = */(uint32_t) mciBuffer, - /* .nq_offset = */nqOffset, - /* .nq_length = */nqLength, - /* .mcp_offset = */mcpOffset, - /* .mcp_length = */mcpLength } }; - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_FC_INIT, &fcInitParams); - if (ret != 0) - { - LOG_E("IOCTL_FC_INIT failed with ret = %d and errno = %d", ret, errno); - break; - } - - } while (0); + if (!isOpen()) { + return ERROR_KMOD_NOT_OPEN; + } + + // Init MC with NQ and MCP buffer addresses + struct mc_ioctl_init fcInitParams = { + nq_offset : nqOffset, + nq_length : nqLength, + mcp_offset : mcpOffset, + mcp_length : mcpLength }; + ret = ioctl(fdKMod, MC_IO_INIT, &fcInitParams); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_INIT"); + LOG_E("ret = %d", ret); + } return ret; } - //------------------------------------------------------------------------------ -int CMcKMod::fcInfo( - uint32_t extInfoId, - uint32_t *pState, - uint32_t *pExtInfo -) { +int CMcKMod::fcInfo(uint32_t extInfoId, uint32_t *pState, uint32_t *pExtInfo) +{ int ret = 0; - do + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + // Init MC with NQ and MCP buffer addresses + struct mc_ioctl_info fcInfoParams = {ext_info_id : extInfoId }; + ret = ioctl(fdKMod, MC_IO_INFO, &fcInfoParams); + if (ret != 0) { - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - // Init MC with NQ and MCP buffer addresses - union mc_ioctl_info_params fcInfoParams = { - // C++ does not support C99 designated initializers - /* .in = */{ - /* .ext_info_id = */extInfoId } }; - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_FC_INFO, &fcInfoParams); - if (ret != 0) - { - LOG_E("IOCTL_FC_INFO failed with ret = %d and errno = %d", ret, errno); - break; - } - - if (NULL != pState) - { - *pState = fcInfoParams.out.state; - } - - if (NULL != pExtInfo) - { - *pExtInfo = fcInfoParams.out.ext_info; - } - - } while (0); + LOG_ERRNO("ioctl MC_IO_INFO"); + LOG_E("ret = %d", ret); + return ret; + } + + if (pState != NULL) { + *pState = fcInfoParams.state; + } + + if (pExtInfo != NULL) { + *pExtInfo = fcInfoParams.ext_info; + } return ret; } //------------------------------------------------------------------------------ -int CMcKMod::fcYield( - void -) { +int CMcKMod::fcYield(void) +{ int ret = 0; - do - { - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_FC_YIELD, NULL); - if (ret != 0) - { - LOG_E("IOCTL_FC_YIELD failed with ret = %d and errno = %d", ret, errno); - break; - } - - } while (0); + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + ret = ioctl(fdKMod, MC_IO_YIELD, NULL); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_YIELD"); + LOG_E("ret = %d", ret); + } return ret; } //------------------------------------------------------------------------------ -int CMcKMod::fcNSIQ( - void -) { +int CMcKMod::fcNSIQ(void) +{ int ret = 0; - do - { - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_FC_NSIQ, NULL); - if (ret != 0) - { - LOG_E("IOCTL_FC_NSIQ failed with ret = %d and errno = %d", ret, errno); - break; - } - - } while (0); + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + ret = ioctl(fdKMod, MC_IO_NSIQ, NULL); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_NSIQ"); + LOG_E("ret = %d", ret); + } return ret; } //------------------------------------------------------------------------------ -int CMcKMod::free( - uint32_t handle -) { +int CMcKMod::free(uint32_t handle, addr_t buffer, uint32_t len) +{ int ret = 0; - do - { - LOG_I("free(): handle=%d", handle); - - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } + LOG_V("free(): handle=%d", handle); - union mc_ioctl_free_params freeParams = { - // C++ does not support c99 designated initializers - /* .in = */{ - /* .handle = */(uint32_t) handle } }; + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_FREE, &freeParams); - if (0 != ret) - { - LOG_E("IOCTL_FREE failed with ret = %d and errno = %d", ret, errno); - break; - } + // Even if unmap fails we still go on with our request + if(::munmap(buffer, len)) { + LOG_I("buffer = %p, len = %d", buffer, len); + } - } while (0); + ret = ioctl(fdKMod, MC_IO_FREE, handle); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_FREE"); + LOG_E("ret = %d", ret); + } return ret; } @@ -412,155 +335,109 @@ int CMcKMod::registerWsmL2( uint32_t len, uint32_t pid, uint32_t *pHandle, - addr_t *pPhysWsmL2 -) { + addr_t *pPhysWsmL2) +{ int ret = 0; - do - { - LOG_I("registerWsmL2(): buffer=%p, len=%d, pid=%d", buffer, len, pid); - - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } - - union mc_ioctl_app_reg_wsm_l2_params params = { - // C++ does not support C99 designated initializers - /* .in = */{ - /* .buffer = */(uint32_t) buffer, - /* .len = */len, - /* .pid = */pid } }; - - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_APP_REGISTER_WSM_L2, ¶ms); - if (0 != ret) - { - LOG_E("IOCTL_APP_REGISTER_WSM_L2 failed with ret = %d and errno = %d", ret, errno); - break; - } - - LOG_I("WSM L2 phys=%x, handle=%d", params.out.phys_wsm_l2_table, - params.out.handle); - - if (NULL != pHandle) - { - *pHandle = params.out.handle; - } - - if (NULL != pPhysWsmL2) - { - *pPhysWsmL2 = (addr_t) params.out.phys_wsm_l2_table; - } - - } while (0); + LOG_I(" Registering virtual buffer at %p, len=%d as World Shared Memory", buffer, len); + + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + struct mc_ioctl_reg_wsm params = { + buffer : (uint32_t) buffer, + len : len, + pid : pid }; + + ret = ioctl(fdKMod, MC_IO_REG_WSM, ¶ms); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_REG_WSM"); + return ret; + } + + LOG_I(" Registered, handle=%d, L2 phys=0x%x ", params.handle, params.table_phys); + + if (pHandle != NULL) { + *pHandle = params.handle; + } + + if (pPhysWsmL2 != NULL) { + *pPhysWsmL2 = (addr_t) params.table_phys; + } return ret; } //------------------------------------------------------------------------------ -int CMcKMod::unregisterWsmL2( - uint32_t handle -) { +int CMcKMod::unregisterWsmL2(uint32_t handle) +{ int ret = 0; - do - { - LOG_I("unregisterWsmL2(): handle=%d", handle); + LOG_I(" Unregistering World Shared Memory with handle %d", handle); - if (!isOpen()) - { - LOG_E("no connection to kmod"); - ret = ERROR_KMOD_NOT_OPEN; - break; - } + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } - struct mc_ioctl_app_unreg_wsm_l2_params params = { - // C++ does not support c99 designated initializers - /* .in = */{ - /* .handle = */handle } }; - - int ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_APP_UNREGISTER_WSM_L2, ¶ms); - if (0 != ret) - { - LOG_E("IOCTL_APP_UNREGISTER_WSM_L2 failed with ret = %d and errno = %d", ret, errno); - break; - } - - } while (0); + ret = ioctl(fdKMod, MC_IO_UNREG_WSM, handle); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_UNREG_WSM"); + LOG_E("ret = %d", ret); + } return ret; } //------------------------------------------------------------------------------ -int CMcKMod::fcExecute( - addr_t startAddr, - uint32_t areaLength -) { - int ret = 0; - union mc_ioctl_fc_execute_params params = { - /*.in =*/ { - /*.phys_start_addr = */ (uint32_t)startAddr, - /*.length = */ areaLength - } - }; - do - { - if (!isOpen()) - { - LOG_E("no connection to kmod"); - break; - } - - ret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_FC_EXECUTE, ¶ms); - if (ret != 0) - { - LOG_E("IOCTL_FC_EXECUTE failed with ret = %d and errno = %d", ret, errno); - break; - } - - } while(0); - - return ret; +int CMcKMod::fcExecute(addr_t startAddr, uint32_t areaLength) +{ + int ret = 0; + struct mc_ioctl_execute params = { + phys_start_addr : (uint32_t)startAddr, + length : areaLength}; + + if (!isOpen()) { + LOG_E("no connection to kmod"); + return ERROR_KMOD_NOT_OPEN; + } + + ret = ioctl(fdKMod, MC_IO_EXECUTE, ¶ms); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_EXECUTE"); + LOG_E("ret = %d", ret); + } + + return ret; } //------------------------------------------------------------------------------ -bool CMcKMod::checkKmodVersionOk( - void -) { - bool ret = false; - - do - { - if (!isOpen()) - { - LOG_E("no connection to kmod"); - break; - } - - struct mc_ioctl_get_version_params params; - - int ioret = ioctl(fdKMod, MC_DRV_KMOD_IOCTL_GET_VERSION, ¶ms); - if (0 != ioret) - { - LOG_E("IOCTL_GET_VERSION failed with ret = %d and errno = %d", ret, errno); - break; - } - - // Run-time check. - char* errmsg; - if (!checkVersionOkMCDRVMODULEAPI(params.out.kernel_module_version, &errmsg)) { - LOG_E("%s", errmsg); - break; - } - LOG_I("%s", errmsg); - - ret = true; - - } while (0); - - return ret; +bool CMcKMod::checkVersion(void) +{ + uint32_t version; + if (!isOpen()) { + LOG_E("no connection to kmod"); + return false; + } + + int ret = ioctl(fdKMod, MC_IO_VERSION, &version); + if (ret != 0){ + LOG_ERRNO("ioctl MC_IO_VERSION"); + LOG_E("ret = %d", ret); + return false; + } + + // Run-time check. + char* errmsg; + if (!checkVersionOkMCDRVMODULEAPI(version, &errmsg)) { + LOG_E("%s", errmsg); + return false; + } + LOG_I("%s", errmsg); + + return true; } /** @} */ diff --git a/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.h b/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.h index fa04bf2..cbe739c 100644 --- a/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.h +++ b/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.h @@ -5,7 +5,7 @@ * MobiCore Driver Kernel Module Interface. * * <!-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -45,99 +45,88 @@ * As this is also used by the ClientLib, we do not use exceptions. */ class CMcKMod : public CKMod { - public: - - /** - * Map data. - * - * @param len - * @param pHandle - * @param pVirtAddr - * @param pPhysAddr - * @param pMciReuse [in|out] set to true [in] for reusing MCI buffer - * is set to true [out] if MCI buffer has been reused - * @return 0 if all went fine - * @return ERROR_KMOD_NOT_OPEN - * @return ERROR_MAPPING_FAILED - */ - int mmap( - uint32_t len, - uint32_t *pHandle, - addr_t *pVirtAddr, - addr_t *pPhysAddr, - bool *pMciReuse - ); - - /** - * Map persistent WSM which will not be freed up once the calling process dies. - */ - int mapPersistent( - uint32_t len, - uint32_t *pHandle, - addr_t *pVirtAddr, - addr_t *pPhysAddr - ); - - int read( - addr_t buffer, - uint32_t len - ); - - bool waitSSIQ( - uint32_t *pCnt - ); - - int fcInit( - addr_t mciBuffer, - uint32_t nqOffset, - uint32_t nqLength, - uint32_t mcpOffset, - uint32_t mcpLength - ); - - int fcInfo( - uint32_t extInfoId, - uint32_t *pState, - uint32_t *pExtInfo - ); - - int fcYield( - void - ); - - int fcNSIQ( - void - ); - - int free( - uint32_t handle - ); - - int registerWsmL2( - addr_t buffer, - uint32_t len, - uint32_t pid, - uint32_t *pHandle, - addr_t *pPhysWsmL2 - ); - - int unregisterWsmL2( - uint32_t handle - ); - - /** - * Tell stub to start MobiCore from given physical address - */ - int fcExecute( - addr_t startAddr, - uint32_t areaLength - ); - - bool checkKmodVersionOk( - void - ); - + /** + * Map data. + * + * @param len + * @param pHandle + * @param pVirtAddr + * @param pPhysAddr + * @param pMciReuse [in|out] set to true [in] for reusing MCI buffer + * is set to true [out] if MCI buffer has been reused + * @return 0 if all went fine + * @return ERROR_KMOD_NOT_OPEN + * @return ERROR_MAPPING_FAILED + */ + int mapWsm(uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + addr_t *pPhysAddr); + /** + * Map data. + * + * @param len + * @param pHandle + * @param pVirtAddr + * @param pPhysAddr + * @param pMciReuse [in|out] set to true [in] for reusing MCI buffer + * is set to true [out] if MCI buffer has been reused + * @return 0 if all went fine + * @return ERROR_KMOD_NOT_OPEN + * @return ERROR_MAPPING_FAILED + */ + int mapMCI( + uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + addr_t *pPhysAddr, + bool *pReuse); + + /** + * Map persistent WSM which will not be freed up once the calling process dies. + */ + int mapPersistent( + uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + addr_t *pPhysAddr); + + int read(addr_t buffer, uint32_t len); + + bool waitSSIQ(uint32_t *pCnt); + + int fcInit(uint32_t nqOffset, + uint32_t nqLength, + uint32_t mcpOffset, + uint32_t mcpLength); + + int fcInfo( + uint32_t extInfoId, + uint32_t *pState, + uint32_t *pExtInfo); + + int fcYield(void); + + int fcNSIQ(void); + + int free(uint32_t handle, addr_t buffer, uint32_t len); + + int registerWsmL2( + addr_t buffer, + uint32_t len, + uint32_t pid, + uint32_t *pHandle, + addr_t *pPhysWsmL2); + + int unregisterWsmL2(uint32_t handle); + + /** + * Tell stub to start MobiCore from given physical address + */ + int fcExecute(addr_t startAddr, uint32_t areaLength); + + bool checkVersion(void); }; typedef CMcKMod *CMcKMod_ptr; diff --git a/mobicore/daemon/PaApi/Android.mk b/mobicore/daemon/PaApi/Android.mk index 4630bbe..614d021 100644 --- a/mobicore/daemon/PaApi/Android.mk +++ b/mobicore/daemon/PaApi/Android.mk @@ -1,35 +1,11 @@ # ============================================================================= # -# Module: libPaApi(Static and Shared variant) +# Module: libPaApi # # ============================================================================= -LOCAL_PATH := $(call my-dir) - -#Now the Shared Object -include $(CLEAR_VARS) - -LOCAL_MODULE := libPaApi -LOCAL_MODULE_TAGS := eng -LOCAL_PRELINK_MODULE := false - -LOCAL_C_INCLUDES += bionic \ - external/stlport/stlport - # Add your folders with header files here (absolute paths) -LOCAL_C_INCLUDES += \ - $(LOCAL_PATH)/Public \ - $(COMP_PATH_MobiCore)/inc \ - $(COMP_PATH_MobiCore)/inc/TlCm \ - $(APP_PROJECT_PATH)/ClientLib/public +LOCAL_C_INCLUDES += $(LOCAL_PATH)/PaApi/Public # Add your source files here (relative paths) -LOCAL_SRC_FILES += tlcCmApi.cpp - -LOCAL_SHARED_LIBRARIES += libMcRegistry libMcClient -LOCAL_STATIC_LIBRARIES = libstlport_static -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions - -include $(COMP_PATH_Logwrapper)/Android.mk - -include $(BUILD_SHARED_LIBRARY) +LOCAL_SRC_FILES += PaApi/tlcCmApi.cpp diff --git a/mobicore/daemon/PaApi/tlcCmApi.cpp b/mobicore/daemon/PaApi/tlcCmApi.cpp index 86f213c..efd0ec1 100644 --- a/mobicore/daemon/PaApi/tlcCmApi.cpp +++ b/mobicore/daemon/PaApi/tlcCmApi.cpp @@ -33,7 +33,6 @@ #include "tlcCmApi.h" #include "tlCmUuid.h" -#define LOG_TAG "TlcCmApi" #include "log.h" #include <assert.h> diff --git a/mobicore/daemon/Registry/Android.mk b/mobicore/daemon/Registry/Android.mk index af396f7..d83160c 100644 --- a/mobicore/daemon/Registry/Android.mk +++ b/mobicore/daemon/Registry/Android.mk @@ -1,72 +1,11 @@ # ============================================================================= # -# Module: libMcRegistry.a - MobiCore driver registry +# Module: MobiCore driver registry # # ============================================================================= -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcRegistry - -# Prevent not-yet-used functions of being ignored by linker -LOCAL_LDLIBS := -Wl,-whole-archive - -LOCAL_C_INCLUDES += bionic \ - external/stlport/stlport - -# Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(LOCAL_PATH)/Public\ - $(MY_CLIENTLIB_PATH)/public\ - $(COMP_PATH_MobiCore)/inc - -# Add new source files here -LOCAL_SRC_FILES += Registry.cpp - -# Header files for components including this module -LOCAL_EXPORT_C_INCLUDES +=\ - $(LOCAL_PATH)/Public\ - $(MY_CLIENTLIB_PATH)/public - -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions -include $(COMP_PATH_Logwrapper)/Android.mk - -include $(BUILD_STATIC_LIBRARY) - -################################################## -## Shared Object -################################################## -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcRegistry -LOCAL_MODULE_TAGS := eng -LOCAL_PRELINK_MODULE := false - -# Prevent not-yet-used functions of being ignored by linker -LOCAL_LDLIBS := -Wl,-whole-archive - -LOCAL_C_INCLUDES += bionic \ - external/stlport/stlport - # Add new folders with header files here -LOCAL_C_INCLUDES +=\ - $(LOCAL_PATH)/Public\ - $(MY_CLIENTLIB_PATH)/public\ - $(COMP_PATH_MobiCore)/inc +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Registry/Public # Add new source files here -LOCAL_SRC_FILES += Registry.cpp - -# Header files for components including this module -LOCAL_EXPORT_C_INCLUDES +=\ - $(LOCAL_PATH)/Public\ - $(MY_CLIENTLIB_PATH)/public - -LOCAL_STATIC_LIBRARIES = libstlport_static -LOCAL_CPPFLAGS += -fno-rtti -fno-exceptions - -include $(COMP_PATH_Logwrapper)/Android.mk - -include $(BUILD_SHARED_LIBRARY) +LOCAL_SRC_FILES += Registry/Registry.cpp diff --git a/mobicore/daemon/Registry/Registry.cpp b/mobicore/daemon/Registry/Registry.cpp index 4d7fb8d..dd27476 100644 --- a/mobicore/daemon/Registry/Registry.cpp +++ b/mobicore/daemon/Registry/Registry.cpp @@ -31,11 +31,10 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "MobiCoreRegistry.h" #include <stdlib.h> #include <dirent.h> -#include <fstream> +#include <stdio.h> #include <sys/stat.h> #include <assert.h> #include <string> @@ -45,7 +44,6 @@ #include "mcSpid.h" #include "mcVersionHelper.h" -#define LOG_TAG "McDaemon" #include "log.h" MC_CHECK_DATA_OBJECT_VERSION(MCLF, 2, 0); @@ -96,15 +94,17 @@ mcResult_t mcRegistryStoreAuthToken( } const string& authTokenFilePath = getAuthTokenFilePath(); LOG_I("store AuthToken: %s", authTokenFilePath.c_str()); - fstream fs(authTokenFilePath.c_str(), ios_base::out | ios_base::binary); + + FILE *fs = fopen(authTokenFilePath.c_str(), "wb"); if (!fs) { LOG_E("mcRegistry store So.Soc failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::beg); - fs.write((char *)so, sizeof(mcSoAuthTokenCont_t)); - fs.flush(); - fs.close(); + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, sizeof(mcSoAuthTokenCont_t), fs); + fflush(fs); + fclose(fs); + return MC_DRV_OK; } @@ -119,21 +119,23 @@ mcResult_t mcRegistryReadAuthToken( } const string& authTokenFilePath = getAuthTokenFilePath(); LOG_I("read AuthToken: %s", authTokenFilePath.c_str()); - fstream fs(authTokenFilePath.c_str(), ios_base::in | ios_base::binary); + + FILE *fs = fopen(authTokenFilePath.c_str(), "rb"); if (!fs) { LOG_E("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::end); - int32_t filesize = fs.tellg(); + fseek(fs, 0, SEEK_END); + int32_t filesize = ftell(fs); if (sizeof(mcSoAuthTokenCont_t) != filesize) { - fs.close(); + fclose(fs); LOG_E("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); return MC_DRV_ERR_OUT_OF_RESOURCES; } - fs.seekg(0, ios::beg); - fs.read((char *)so, sizeof(mcSoAuthTokenCont_t)); - fs.close(); + fseek(fs, 0, SEEK_SET); + fread((char *)so, 1, sizeof(mcSoAuthTokenCont_t), fs); + fclose(fs); + return MC_DRV_OK; } @@ -161,15 +163,17 @@ mcResult_t mcRegistryStoreRoot( } const string& rootContFilePath = getRootContFilePath(); LOG_I("store Root: %s", rootContFilePath.c_str()); - fstream fs(rootContFilePath.c_str(), ios_base::out | ios_base::binary); + + FILE *fs = fopen(rootContFilePath.c_str(), "wb"); if (!fs) { LOG_E("mcRegistry store So.Root failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::beg); - fs.write((char *)so, sizeof(mcSoRootCont_t)); - fs.flush(); - fs.close(); + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, sizeof(mcSoRootCont_t), fs); + fflush(fs); + fclose(fs); + return MC_DRV_OK; } @@ -184,21 +188,23 @@ mcResult_t mcRegistryReadRoot( } const string& rootContFilePath = getRootContFilePath(); LOG_I("read Root: %s", rootContFilePath.c_str()); - fstream fs(rootContFilePath.c_str(), ios_base::in | ios_base::binary); + + FILE *fs = fopen(rootContFilePath.c_str(), "rb"); if (!fs) { LOG_E("mcRegistry read So.Root failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::end); - int32_t filesize = fs.tellg(); + fseek(fs, 0, SEEK_END); + int32_t filesize = ftell(fs); if (sizeof(mcSoRootCont_t) != filesize) { - fs.close(); + fclose(fs); LOG_E("mcRegistry read So.Root failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); return MC_DRV_ERR_OUT_OF_RESOURCES; } - fs.seekg(0, ios::beg); - fs.read((char *)so, sizeof(mcSoRootCont_t)); - fs.close(); + fseek(fs, 0, SEEK_SET); + fread((char *)so, 1, sizeof(mcSoRootCont_t), fs); + fclose(fs); + return MC_DRV_OK; } @@ -218,15 +224,17 @@ mcResult_t mcRegistryStoreSp( } const string& spContFilePath = getSpContFilePath(spid); LOG_I("store SP: %s", spContFilePath.c_str()); - fstream fs(spContFilePath.c_str(), ios_base::out | ios_base::binary); + + FILE *fs = fopen(spContFilePath.c_str(), "wb"); if (!fs) { LOG_E("mcRegistry store So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::beg); - fs.write((char *)so, sizeof(mcSoSpCont_t)); - fs.flush(); - fs.close(); + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, sizeof(mcSoSpCont_t), fs); + fflush(fs); + fclose(fs); + return MC_DRV_OK; } @@ -242,21 +250,23 @@ mcResult_t mcRegistryReadSp( } const string& spContFilePath = getSpContFilePath(spid); LOG_I("read SP: %s", spContFilePath.c_str()); - fstream fs(spContFilePath.c_str(), ios_base::in | ios_base::binary); + + FILE *fs = fopen(spContFilePath.c_str(), "rb"); if (!fs) { LOG_E("mcRegistry read So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::end); - int32_t filesize = fs.tellg(); + fseek(fs, 0, SEEK_END); + int32_t filesize = ftell(fs); if (sizeof(mcSoSpCont_t) != filesize) { - fs.close(); + fclose(fs); LOG_E("mcRegistry read So.Sp(SpId) failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); return MC_DRV_ERR_OUT_OF_RESOURCES; } - fs.seekg(0, ios::beg); - fs.read((char *)so, sizeof(mcSoSpCont_t)); - fs.close(); + fseek(fs, 0, SEEK_SET); + fread((char *)so, 1, sizeof(mcSoSpCont_t), fs); + fclose(fs); + return MC_DRV_OK; } @@ -276,15 +286,17 @@ mcResult_t mcRegistryStoreTrustletCon( } const string& tlContFilePath = getTlContFilePath(uuid); LOG_I("store TLc: %s", tlContFilePath.c_str()); - fstream fs(tlContFilePath.c_str(), ios_base::out | ios_base::binary); + + FILE *fs = fopen(tlContFilePath.c_str(), "wb"); if (!fs) { LOG_E("mcRegistry store So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::beg); - fs.write((char *)so, sizeof(mcSoTltCont_t)); - fs.flush(); - fs.close(); + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, sizeof(mcSoTltCont_t), fs); + fflush(fs); + fclose(fs); + return MC_DRV_OK; } @@ -300,21 +312,23 @@ mcResult_t mcRegistryReadTrustletCon( } const string& tlContFilePath = getTlContFilePath(uuid); LOG_I("read TLc: %s", tlContFilePath.c_str()); - fstream fs(tlContFilePath.c_str(), ios_base::in | ios_base::binary); + + FILE *fs = fopen(tlContFilePath.c_str(), "rb"); if (!fs) { LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::end); - int32_t filesize = fs.tellg(); + fseek(fs, 0, SEEK_END); + int32_t filesize = ftell(fs); if (sizeof(mcSoTltCont_t) != filesize) { - fs.close(); + fclose(fs); LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d. Size=%i, expected=%i", MC_DRV_ERR_OUT_OF_RESOURCES,filesize,sizeof(mcSoTltCont_t)); return MC_DRV_ERR_OUT_OF_RESOURCES; } - fs.seekg(0, ios::beg); - fs.read((char *)so, sizeof(mcSoTltCont_t)); - fs.close(); + fseek(fs, 0, SEEK_SET); + fread((char *)so, 1, sizeof(mcSoTltCont_t), fs); + fclose(fs); + return MC_DRV_OK; } @@ -345,15 +359,17 @@ mcResult_t mcRegistryStoreData( mkdir(pathname.c_str(), 0777); LOG_I("store DT: %s", filename.c_str()); - fstream fs(filename.c_str(), ios_base::out | ios_base::binary); + + FILE *fs = fopen(filename.c_str(), "wb"); if (!fs) { LOG_E("mcRegistry store So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::beg); - fs.write((char *)so, MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen)); - fs.flush(); - fs.close(); + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen), fs); + fflush(fs); + fclose(fs); + return MC_DRV_OK; } @@ -384,24 +400,26 @@ mcResult_t mcRegistryReadData( return MC_DRV_ERR_INVALID_PARAMETER; } LOG_I("read DT: %s", filename.c_str()); - fstream fs(filename.c_str(), ios_base::in | ios_base::binary); + + FILE *fs = fopen(filename.c_str(), "rb"); if (!fs) { LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - fs.seekg(0, ios::end); - uint32_t filesize = fs.tellg(); + fseek(fs, 0, SEEK_END); + uint32_t filesize = ftell(fs); if (maxLen < filesize) { - fs.close(); + fclose(fs); LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); return MC_DRV_ERR_OUT_OF_RESOURCES; } - fs.seekg(0, ios::beg); + fseek(fs, 0, SEEK_SET); char* p = (char*) so; - fs.read(p, sizeof(mcSoHeader_t)); + fread(p, 1, sizeof(mcSoHeader_t), fs); p += sizeof(mcSoHeader_t); - fs.read(p, MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen) - sizeof(mcSoHeader_t)); - fs.close(); + fread(p, 1, MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen) - sizeof(mcSoHeader_t), fs); + fclose(fs); + return MC_DRV_OK; } @@ -551,69 +569,78 @@ regObject_t *mcRegistryGetServiceBlob( // Ensure that a UUID is provided. if (NULL == uuid) { - LOG_E("mcRegistryGetServiceBlob() failed. No UUID given"); + LOG_E("No UUID given"); return NULL; } // Open service blob file. string tlBinFilePath = getTlBinFilePath(uuid); - LOG_I("mcRegistryGetServiceBlob() Loading service: %s", tlBinFilePath.c_str()); + LOG_I(" Loading %s", tlBinFilePath.c_str()); - ifstream fs(tlBinFilePath.c_str(), ios_base::binary); + FILE *fs = fopen(tlBinFilePath.c_str(), "rb"); if (!fs) { - LOG_E("mcRegistryGetServiceBlob() failed: cannot open %s", tlBinFilePath.c_str()); + LOG_E("Cannot open %s", tlBinFilePath.c_str()); return NULL; } // Determine and check service blob size. - fs.seekg(0, ios::end); - int32_t tlSize = fs.tellg(); - fs.seekg(0, ios::beg); + fseek(fs, 0, SEEK_END); + int32_t tlSize = ftell(fs); + fseek(fs, 0, SEEK_SET); if (MAX_TL_SIZE < tlSize) { LOG_E("mcRegistryGetServiceBlob() failed: service blob too big: %d", tlSize); return NULL; } // Check TL magic value. - fs.seekg(offsetof(mclfIntro_t, magic), ios::beg); + fseek(fs, offsetof(mclfIntro_t, magic), SEEK_SET); uint32_t magic; - fs.read((char*)&magic, sizeof(magic)); + fread((char*)&magic, 1, sizeof(magic), fs); if (magic != MC_SERVICE_HEADER_MAGIC_BE) { + fclose(fs); LOG_E("mcRegistryGetServiceBlob() failed: wrong header magic value: %d", magic); return NULL; } // Check header version. - fs.seekg(offsetof(mclfIntro_t, version), ios::beg); + fseek(fs, offsetof(mclfIntro_t, version), SEEK_SET); uint32_t version; - fs.read((char*)&version, sizeof(version)); + fread((char*)&version, 1, sizeof(version), fs); char* msg; if (!checkVersionOkDataObjectMCLF(version, &msg)) { - LOG_E("mcRegistryGetDriverBlob() failed: Trustlet header incompatible with MobiCore interface version. Check your SDK version!"); - // msg is null for release version - LOG_E("%s", msg); - return NULL; + fclose(fs); + LOG_E("%s", msg); + return NULL; } // Get service type. - fs.seekg(offsetof(mclfHeaderV1_t, serviceType), ios::beg); + fseek(fs, offsetof(mclfHeaderV1_t, serviceType), SEEK_SET); serviceType_t serviceType; - fs.read((char*)&serviceType, sizeof(serviceType)); - fs.seekg(0, ios::beg); + fread((char*)&serviceType, 1, sizeof(serviceType), fs); + fseek(fs, 0, SEEK_SET); - LOG_I("mcRegistryGetServiceBlob() Service is of type: %d", serviceType); +#ifndef NDEBUG + { + const char* service_types[] = { + "illegal","Driver","Trustlet","System Trustlet" + }; + int serviceType_safe = serviceType>SERVICE_TYPE_SYSTEM_TRUSTLET ? SERVICE_TYPE_ILLEGAL : serviceType; + LOG_I(" Service is a %s (service type %d)", service_types[serviceType_safe], serviceType); + } +#endif // If loadable driver or system trustlet. if (SERVICE_TYPE_DRIVER == serviceType || SERVICE_TYPE_SYSTEM_TRUSTLET == serviceType) { // Take trustlet blob 'as is'. if (NULL == (regobj = (regObject_t*) (malloc(sizeof(regObject_t) + tlSize)))) { + fclose(fs); LOG_E("mcRegistryGetServiceBlob() failed: Out of memory"); return NULL; } regobj->len = tlSize; - fs.read((char *)regobj->value, tlSize); - fs.close(); + fread((char *)regobj->value, 1, tlSize, fs); + fclose(fs); // If user trustlet. } else if (SERVICE_TYPE_SP_TRUSTLET == serviceType) { // Take trustlet blob and append root, sp, and tl container. @@ -621,14 +648,15 @@ regObject_t *mcRegistryGetServiceBlob( // Prepare registry object. if (NULL == (regobj = (regObject_t*) malloc(sizeof(regObject_t) + regObjValueSize))) { + fclose(fs); LOG_E("mcRegistryGetServiceBlob() failed: Out of memory"); return NULL; } regobj->len = regObjValueSize; // Read and fill in trustlet blob at beginning. - fs.read((char*)regobj->value, tlSize); - fs.close(); + fread((char*)regobj->value, 1, tlSize, fs); + fclose(fs); // Goto end of allocated space and fill in tl container, sp container, // and root container from back to front. Final registry object value @@ -697,6 +725,7 @@ regObject_t *mcRegistryGetServiceBlob( } // Any other service type. } else { + fclose(fs); LOG_E("mcRegistryGetServiceBlob() failed: Unsupported service type %u", serviceType); } @@ -708,50 +737,51 @@ regObject_t *mcRegistryGetDriverBlob( const char *driverFilename ) { regObject_t* regobj = NULL; - - // Open service blob file. - ifstream fs(driverFilename, ios_base::binary); + + // Open service blob file. + FILE *fs = fopen(driverFilename, "rb"); if (!fs) { LOG_E("mcRegistryGetDriverBlob() failed: cannot open %s", driverFilename); return NULL; } // Determine and check service blob size. - fs.seekg(0, ios::end); - int32_t tlSize = fs.tellg(); - fs.seekg(0, ios::beg); + fseek(fs, 0, SEEK_END); + int32_t tlSize = ftell(fs); + fseek(fs, 0, SEEK_SET); if (MAX_TL_SIZE < tlSize) { LOG_E("mcRegistryGetDriverBlob() failed: service blob too big: %d", tlSize); + fclose(fs); return NULL; } // Check TL magic value. - fs.seekg(offsetof(mclfIntro_t, magic), ios::beg); + fseek(fs, offsetof(mclfIntro_t, magic), SEEK_SET); uint32_t magic; - fs.read((char*)&magic, sizeof(magic)); + fread((char*)&magic, 1, sizeof(magic), fs); if (magic != MC_SERVICE_HEADER_MAGIC_BE) { LOG_E("mcRegistryGetDriverBlob() failed: wrong header magic value: %d", magic); + fclose(fs); return NULL; } // Check header version. - fs.seekg(offsetof(mclfIntro_t, version), ios::beg); + fseek(fs, offsetof(mclfIntro_t, version), SEEK_SET); uint32_t version; - fs.read((char*)&version, sizeof(version)); + fread((char*)&version, 1, sizeof(version), fs); char* msg; if (!checkVersionOkDataObjectMCLF(version, &msg)) { - LOG_E("mcRegistryGetDriverBlob() failed: Driver header incompatible with MobiCore interface version. Check your SDK version!"); - // msg is null for release version - LOG_E("%s", msg); - return NULL; + LOG_E("%s", msg); + fclose(fs); + return NULL; } // Get service type. - fs.seekg(offsetof(mclfHeaderV1_t, serviceType), ios::beg); + fseek(fs, offsetof(mclfHeaderV1_t, serviceType), SEEK_SET); serviceType_t serviceType; - fs.read((char*)&serviceType, sizeof(serviceType)); - fs.seekg(0, ios::beg); + fread((char*)&serviceType, 1, sizeof(serviceType), fs); + fseek(fs, 0, SEEK_SET); LOG_I("mcRegistryGetDriverBlob() Service is of type: %d", serviceType); @@ -760,16 +790,18 @@ regObject_t *mcRegistryGetDriverBlob( // Take trustlet blob 'as is'. if (NULL == (regobj = (regObject_t*) (malloc(sizeof(regObject_t) + tlSize)))) { LOG_E("mcRegistryGetDriverBlob() failed: Out of memory"); + fclose(fs); return NULL; } regobj->len = tlSize; - fs.read((char *)regobj->value, tlSize); - fs.close(); + fread((char *)regobj->value, 1, tlSize, fs); // Otherwise we are not interested } else { LOG_E("mcRegistryGetServiceBlob() failed: Unsupported service type %u", serviceType); } - + + fclose(fs); + return regobj; } @@ -795,7 +827,7 @@ static const string getRegistryPath() { // As a last resort, use the default registry path. if (registryPath.length() == 0) { registryPath = MC_REGISTRY_DEFAULT_PATH; - LOG_I("getRegistryPath(): Using default registry path %s", registryPath.c_str()); + LOG_I(" Using default registry path %s", registryPath.c_str()); } assert(registryPath.length() != 0); diff --git a/mobicore/daemon/buildTag.h b/mobicore/daemon/buildTag.h index dc1d4b9..50639e2 100644 --- a/mobicore/daemon/buildTag.h +++ b/mobicore/daemon/buildTag.h @@ -1 +1 @@ -#define MOBICORE_COMPONENT_BUILD_TAG "*** SAMSUNG Exynos 5250 MC1.2 V002 release ###" +#define MOBICORE_COMPONENT_BUILD_TAG "*** SAMSUNG Exynos 5250 MC1.2 V003 release ###" diff --git a/mobicore/include/Public/mc_kernel_api.h b/mobicore/include/Public/mc_kernel_api.h index fdfc618..168215d 100644 --- a/mobicore/include/Public/mc_kernel_api.h +++ b/mobicore/include/Public/mc_kernel_api.h @@ -23,18 +23,14 @@ struct mc_instance; * * @return Instance or NULL if no allocation was possible. */ -struct mc_instance *mobicore_open( - void -); +struct mc_instance *mobicore_open(void); /** * Release a mobicore instance object and all objects related to it * @param instance instance * @return 0 if Ok or -E ERROR */ -int mobicore_release( - struct mc_instance *instance -); +int mobicore_release(struct mc_instance *instance); /** * Free a WSM buffer allocated with mobicore_allocate_wsm @@ -49,8 +45,7 @@ int mobicore_allocate_wsm( unsigned long requested_size, uint32_t *handle, void **kernel_virt_addr, - void **phys_addr -); + void **phys_addr); /** * Free a WSM buffer allocated with mobicore_allocate_wsm @@ -60,10 +55,7 @@ int mobicore_allocate_wsm( * @return 0 if no error * */ -int mobicore_free( - struct mc_instance *instance, - uint32_t handle -); +int mobicore_free(struct mc_instance *instance, uint32_t handle); /** * Map a virtual memory buffer structure to Mobicore @@ -81,8 +73,7 @@ int mobicore_map_vmem( void *addr, uint32_t len, uint32_t *handle, - void **phys_wsm_l2_table -); + void **phys_wsm_l2_table); /** * Unmap a virtual memory buffer from mobicore @@ -92,9 +83,6 @@ int mobicore_map_vmem( * @return 0 if no error * */ -int mobicore_unmap_vmem( - struct mc_instance *instance, - uint32_t handle -); +int mobicore_unmap_vmem(struct mc_instance *instance, uint32_t handle); #endif /* _MOBICORE_KERNELMODULE_API_H_ */ /** @} */ diff --git a/mobicore/include/Public/mc_linux.h b/mobicore/include/Public/mc_linux.h new file mode 100644 index 0000000..506f30c --- /dev/null +++ b/mobicore/include/Public/mc_linux.h @@ -0,0 +1,197 @@ +/** @addtogroup MCD_MCDIMPL_KMOD_API Mobicore Driver Module API + * @ingroup MCD_MCDIMPL_KMOD + * @{ + * Interface to Mobicore Driver Kernel Module. + * @file + * + * <h2>Introduction</h2> + * The MobiCore Driver Kernel Module is a Linux device driver, which represents + * the command proxy on the lowest layer to the secure world (Swd). Additional + * services like memory allocation via mmap and generation of a L2 tables for + * given virtual memory are also supported. IRQ functionallity receives + * information from the SWd in the non secure world (NWd). + * As customary the driver is handled as linux device driver with "open", + * "close" and "ioctl" commands. Access to the driver is possible after the + * device "/dev/mobicore" has been opened. + * The MobiCore Driver Kernel Module must be installed via + * "insmod mcDrvModule.ko". + * + * + * <h2>Version history</h2> + * <table class="customtab"> + * <tr><td width="100px"><b>Date</b></td><td width="80px"><b>Version</b></td> + * <td><b>Changes</b></td></tr> + * <tr><td>2010-05-25</td><td>0.1</td><td>Initial Release</td></tr> + * </table> + * + * <!-- Copyright Giesecke & Devrient GmbH 2010-2012 --> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MC_LINUX_H_ +#define _MC_LINUX_H_ + +#include "version.h" + +#define MC_ADMIN_DEVNODE "mobicore" +#define MC_USER_DEVNODE "mobicore-user" + +/** + * Data exchange structure of the MC_DRV_MODULE_INIT ioctl command. + * INIT request data to SWD + */ +struct mc_ioctl_init { + /** notification buffer start/length [16:16] [start, length] */ + uint32_t nq_offset; + /** length of notification queue */ + uint32_t nq_length; + /** mcp buffer start/length [16:16] [start, length] */ + uint32_t mcp_offset; + /** length of mcp buffer */ + uint32_t mcp_length; +}; + + +/** + * Data exchange structure of the MC_DRV_MODULE_INFO ioctl command. + * INFO request data to the SWD + */ +struct mc_ioctl_info { + uint32_t ext_info_id; /**< extended info ID */ + uint32_t state; /**< state */ + uint32_t ext_info; /**< extended info */ +}; + +/** + * Mmap allocates and maps contiguous memory into a process. + * We use the third parameter, void *offset, to distinguish between some cases + * offset = MC_DRV_KMOD_MMAP_WSM usual operation, pages are registered in + * device structure and freed later. + * offset = MC_DRV_KMOD_MMAP_MCI get Instance of MCI, allocates or mmaps + * the MCI to daemon + * + * In mmap(), the offset specifies which of several device I/O pages is + * requested. Linux only transfers the page number, i.e. the upper 20 bits to + * kernel module. Therefore we define our special offsets as multiples of page + * size. + */ +struct mc_ioctl_map { + size_t len; /**< Buffer length */ + uint32_t handle; /**< WSM handle */ + unsigned long addr; /**< Virtual address */ + unsigned long phys_addr; /**< physical address of WSM (or NULL) */ + bool reused; /**< if WSM memory was reused, or new allocated */ +}; + +/** + * Data exchange structure of the MC_IO_REG_WSM command. + * + * Allocates a physical L2 table and maps the buffer into this page. + * Returns the physical address of the L2 table. + * The page alignment will be created and the appropriated pSize and pOffsetL2 + * will be modified to the used values. + */ +struct mc_ioctl_reg_wsm { + uint32_t buffer; /**< base address of the virtual address */ + uint32_t len; /**< size of the virtual address space */ + uint32_t pid; /**< process id */ + uint32_t handle; /**< driver handle for locked memory */ + uint32_t table_phys; /**< physical address of the L2 table */ +}; + + +/** + * Data exchange structure of the MC_DRV_MODULE_FC_EXECUTE ioctl command. + * internal, unsupported + */ +struct mc_ioctl_execute { + /**< base address of mobicore binary */ + uint32_t phys_start_addr; + /**< length of DDR area */ + uint32_t length; +}; + + +/* @defgroup Mobicore_Driver_Kernel_Module_Interface IOCTL */ + + +/** + * defines for the ioctl mobicore driver module function call from user space. + */ +/* MobiCore IOCTL magic number */ +#define MC_IOC_MAGIC 'M' + +#define MC_IO_INIT _IOWR(MC_IOC_MAGIC, 0, struct mc_ioctl_init) +#define MC_IO_INFO _IOWR(MC_IOC_MAGIC, 1, struct mc_ioctl_info) +#define MC_IO_VERSION _IOR(MC_IOC_MAGIC, 2, uint32_t) +/** + * ioctl parameter to send the YIELD command to the SWD. + * Only possible in Privileged Mode. + * ioctl(fd, MC_DRV_MODULE_YIELD) + */ +#define MC_IO_YIELD _IO(MC_IOC_MAGIC, 3) +/** + * ioctl parameter to send the NSIQ signal to the SWD. + * Only possible in Privileged Mode + * ioctl(fd, MC_DRV_MODULE_NSIQ) + */ +#define MC_IO_NSIQ _IO(MC_IOC_MAGIC, 4) +/** + * Free's memory which is formerly allocated by the driver's mmap + * command. The parameter must be this mmaped address. + * The internal instance data regarding to this address are deleted as + * well as each according memory page and its appropriated reserved bit + * is cleared (ClearPageReserved). + * Usage: ioctl(fd, MC_DRV_MODULE_FREE, &address) with address beeing of + * type long address + */ +#define MC_IO_FREE _IO(MC_IOC_MAGIC, 5) +/** + * Creates a L2 Table of the given base address and the size of the + * data. + * Parameter: mc_ioctl_app_reg_wsm_l2_params + */ +#define MC_IO_REG_WSM _IOWR(MC_IOC_MAGIC, 6, struct mc_ioctl_reg_wsm) +#define MC_IO_UNREG_WSM _IO(MC_IOC_MAGIC, 7) +#define MC_IO_LOCK_WSM _IOWR(MC_IOC_MAGIC, 8, uint32_t) +#define MC_IO_UNLOCK_WSM _IO(MC_IOC_MAGIC, 9) +#define MC_IO_EXECUTE _IOWR(MC_IOC_MAGIC, 10, struct mc_ioctl_execute) + +/** + * Mmap allocates and maps contiguous memory into a process. + * MC_DRV_KMOD_MMAP_WSM usual operation, pages are registered in + * device structure and freed later. + * MC_DRV_KMOD_MMAP_MCI get Instance of MCI, allocates or mmaps + * the MCI to daemon + * MC_DRV_KMOD_MMAP_PERSISTENTWSM special operation, without + * registration of pages + */ +#define MC_IO_MAP_WSM _IOWR(MC_IOC_MAGIC, 11, struct mc_ioctl_map) +#define MC_IO_MAP_MCI _IOWR(MC_IOC_MAGIC, 12, struct mc_ioctl_map) +#define MC_IO_MAP_PWSM _IOWR(MC_IOC_MAGIC, 13, struct mc_ioctl_map) + +#endif /* _MC_LINUX_H_ */ +/** @} */ diff --git a/mobicore/provlib/Android.mk b/mobicore/provlib/Android.mk deleted file mode 100644 index f269e80..0000000 --- a/mobicore/provlib/Android.mk +++ /dev/null @@ -1,10 +0,0 @@ -# ============================================================================= -# -# Makefile pointing to all makefiles within the project. -# -# ============================================================================= - -LOCAL_PATH := $(call my-dir) - -# Include the Scripts -include $(LOCAL_PATH)/src/Android.mk diff --git a/mobicore/provlib/Application.mk b/mobicore/provlib/Application.mk deleted file mode 100644 index 91ea85c..0000000 --- a/mobicore/provlib/Application.mk +++ /dev/null @@ -1,21 +0,0 @@ -# ============================================================================= -# -# Main build file defining the project modules and their global variables. -# -# ============================================================================= - -# Don't remove this - mandatory -APP_PROJECT_PATH := $(call my-dir) - -# Don't optimize for better debugging -APP_OPTIM := debug - -# Show all warnings -#APP_CFLAGS := -Wall - -MC_INCLUDE_DIR := $(COMP_PATH_MobiCore)/inc \ - $(COMP_PATH_MobiCore)/inc/TlCm \ - $(COMP_PATH_MobiCoreDriverLib)/Public -MC_DEBUG := _DEBUG -SYSTEM_LIB_DIR=/system/lib -GDM_PROVLIB_SHARED_LIBS=MobiCoreDriver
\ No newline at end of file diff --git a/mobicore/provlib/buildTag.h b/mobicore/provlib/buildTag.h deleted file mode 100644 index dc1d4b9..0000000 --- a/mobicore/provlib/buildTag.h +++ /dev/null @@ -1 +0,0 @@ -#define MOBICORE_COMPONENT_BUILD_TAG "*** SAMSUNG Exynos 5250 MC1.2 V002 release ###" diff --git a/mobicore/provlib/inc_private/gdmcdevicebinding.h b/mobicore/provlib/inc_private/gdmcdevicebinding.h deleted file mode 100644 index c466a18..0000000 --- a/mobicore/provlib/inc_private/gdmcdevicebinding.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef _INC_GDMCDEVICEBINDING_H -#define _INC_GDMCDEVICEBINDING_H - -#include <gdmcprovlib.h> -#include <gdmcprovprotocol.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct _KSoCAuthSNTS KSoCAuthSNTS; - -struct _KSoCAuthSNTS -{ - mcSymmetricKey_t kSoCAuth; - _u64 serialNumber; - _u64 timeStamp; -}; - -#ifdef __cplusplus -} -#endif - -gderror GDMCComposeErrorMessage ( gdmcinst *inst, - gderror error, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size, - const char *pszmsg, ... ); - -gderror GDPROVAPI GDMCValidateProvMessage ( const _u8 *msg, - _u32 msgsize, - gdmc_msgheader **ppheader, - _u8 **ppbody, - gdmc_msgtrailer **pptrailer ); - -gderror GDPROVAPI GDMCHandleGetSUID ( gdmcinst *inst, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size ); - -gderror GDPROVAPI GDMCHandleGenAuthToken ( gdmcinst *inst, - gdmc_actmsg_req *req, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size ); - -gderror GDPROVAPI GDMCHandleValidateAuthToken ( gdmcinst *inst, - gdmc_so_authtok *validateSoAuthTok, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size ); - -#define ERRMSG_0001 "Unable to access memory region at %p (size: %u byte(s)) for READ." -#define ERRMSG_0002 "Unable to access memory region at %p (size: %u byte(s)) for WRITE." -#define ERRMSG_0003 "First in-message must be empty." -#define ERRMSG_0004 "Insufficient memory available." -#define ERRMSG_0005 "Message output buffer too small (%u but %u required to store message)." -#define ERRMSG_0006 "Message validation failed." -#define ERRMSG_0007 "Unexpected message received. Cannot evaluate message (ignored)." -#define ERRMSG_0008 "SUID of returned SO.AuthToken mismatches (my) internal SUID. SO.AuthToken discarded." -#define ERRMSG_0009 "Unable to generate SD.Receipt." -#define ERRMSG_000A "Expecting MC_GETSUID_REQ message from Production Station." -#define ERRMSG_000B "Unable to retrieve SUID from SoC (MobiCore)." -#define ERRMSG_000C "Unable to dump SO.AuthToken (MobiCore)." -#define ERRMSG_000D "Unable to retrieve SUID from SoC." -#define ERRMSG_000E "Unable to generate SO.AuthToken." -#define ERRMSG_000F "Validation of SO.AuthToken failed because no SO.AuthToken available." - -#endif // _INC_GDMCDEVICEBINDING_H diff --git a/mobicore/provlib/inc_private/gdmcinstance.h b/mobicore/provlib/inc_private/gdmcinstance.h deleted file mode 100644 index 0369f62..0000000 --- a/mobicore/provlib/inc_private/gdmcinstance.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef _INC_GDMCINSTANCE_H -#define _INC_GDMCINSTANCE_H - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct _gdmcinst gdmcinst; - -#define GDMC_STATE_INITIAL ((_u32)0) ///< initial state -#define GDMC_STATE_HAVE_SUID ((_u32)1) ///< SUID retrieved from MobiCore -#define GDMC_STATE_HAVE_AUTHTOK ((_u32)2) ///< SO.AuthToken generated by MobiCore - -#define MAX_RESEND_TRIES 64 - -struct _gdmcinst -{ - _u32 state; ///< internal state of this instance - _u8 suid[SUID_LENGTH]; ///< SUID as retrieved from MobiCore - _u8 kSoCAuth[K_SOC_AUTH_LENGTH]; ///< the K.SoC.Auth delivered by KPH - gdmc_so_authtok authTok; ///< generated SO.AuthToken -}; - -#ifdef __cplusplus -} -#endif - -#endif // _INC_GDMCINSTANCE_H diff --git a/mobicore/provlib/inc_private/gdmcprovprotocol.h b/mobicore/provlib/inc_private/gdmcprovprotocol.h deleted file mode 100644 index bd2686d..0000000 --- a/mobicore/provlib/inc_private/gdmcprovprotocol.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef _INC_GDMCPROVPROTOCOL_H_ -#define _INC_GDMCPROVPROTOCOL_H_ - -#include <gdmcprovlib.h> -#include <mobicore.h> - -#ifdef WIN32 - -#pragma warning ( disable : 4200 ) - -#pragma pack(push,1) - -#ifndef PACK_ATTR -#define PACK_ATTR -#endif // PACK_ATTR - -#else - -#ifndef PACK_ATTR -#define PACK_ATTR __attribute__((packed)) -#endif // PACK_ATTR - -#define IsBadReadPtr(p,c) (NULL==p) -#define IsBadWritePtr(p,c) (NULL==p) - -#endif - -#define AUTHENTICATION_TOKEN MC_SO_TYPE_REGULAR -#define CONTEXT_SYSTEM MC_SO_CONTEXT_TLT -#define SUID_LENGTH MC_SUID_LEN // 16 -#define K_SOC_AUTH_LENGTH MC_CONT_SYMMETRIC_KEY_SIZE // 32 -#define SHA256_HASH_LENGTH MC_SO_HASH_SIZE // 32 - -#undef AES_BLOCK_SIZE - -#define AES_BLOCK_SIZE MC_SO_ENCRYPT_BLOCK_SIZE // 16 - -typedef struct _gdmc_actmsg_req gdmc_actmsg_req; -typedef struct _gdmc_actmsg_resp gdmc_actmsg_resp; -typedef struct _gdmc_so_authtok gdmc_so_authtok; -typedef struct _gdmc_error_msg gdmc_error_msg; - -#define MC_GETSUID_REQ ((_u32)0x0100434D) -#define MC_GETSUID_RESP ((_u32)0x0200434D) -#define MC_GENAUTHTOKEN_REQ ((_u32)0x0300434D) -#define MC_GENAUTHTOKEN_RESP ((_u32)0x0400434D) -#define MC_VALIDATEAUTHTOKEN_REQ ((_u32)0x0500434D) -#define MC_ERROR ((_u32)0x0600434D) - -#ifndef CMP_GEN_AUTH_TOKEN_PSS_SIZE -#define CMP_GEN_AUTH_TOKEN_PSS_SIZE 256 -#endif - -/// G&D MobiCore error message -struct _gdmc_error_msg -{ - _u32 errorcode; ///< error code; you can safely cast this to gderror. - _u32 errmsg_length; ///< length of error message, may be 0 - _u8 errmsg[]; ///< error message (variable) -} PACK_ATTR; - -/// G&D MobiCore SO.AuthToken (authentication token) -struct _gdmc_so_authtok -{ - // Header - - _u32 type; - _u32 version; - _u32 context; - _u32 lifetime; // NEW2 -> ignore - _u32 producer_spid; // NEW2 -> ignore - _u8 producer_uuid[16]; // NEW2 -> ignore - _u32 plain_length; // OLD: 16 (SUID_LENGTH), NEW: 24 (two additional ints) - // NEW2: 28 (version is new) - _u32 encrypted_length; // here: K_SOC_AUTH_LENGTH - - // Plaintext Data - - _u32 contType; // NEW: contType_t = CONT_TYPE_SOC - _u32 contVersion; // NEW2: version - _u32 contState; // NEW: mcContainerState_t = MC_CONT_STATE_UNREGISTERED - _u8 suid[SUID_LENGTH]; - - // Encrypted Data (encrypted with K.Device.Ctxt) - - _u8 kSoCAuth[K_SOC_AUTH_LENGTH]; - _u8 md[SHA256_HASH_LENGTH]; - _u8 padding[AES_BLOCK_SIZE]; - -} PACK_ATTR; - -/// MobiCore activation message (request) -struct _gdmc_actmsg_req -{ - _u32 msg_type; ///< type of message = MC_CMP_CMD_GENERATE_AUTH_TOKEN - _u8 suid[SUID_LENGTH]; ///< SoC SUID - _u8 kSoCAuth[K_SOC_AUTH_LENGTH]; ///< K.SoC.Auth (AES-256bit key) - _u32 kid; ///< NEW: key id (currently: 1) - //_u8 md[SHA256_HASH_LENGTH]; ///< SHA-256 hash - _u8 dsig[CMP_GEN_AUTH_TOKEN_PSS_SIZE]; ///< new: hash substituted by PSS-SIG -} PACK_ATTR; - -/// MobiCore activation response -struct _gdmc_actmsg_resp -{ - _u32 msg_type; ///< type of message = MC_CMP_CMD_GENERATE_AUTH_TOKEN | 0x80000000 - _u32 retcode; ///< NEW: return code (status of operation) - gdmc_so_authtok authtok; ///< SO.AuthToken (124 bytes) -} PACK_ATTR; - -#ifdef WIN32 -#pragma pack(pop) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -_u32 GDPROVAPI CalcCRC32 ( const _u8 *data, _u32 length ); - -void GDPROVAPI InitCRCTable ( void ); - -#ifdef __cplusplus -} -#endif - -#endif // _INC_GDMCPROVPROTOCOL_H_ diff --git a/mobicore/provlib/inc_private/mobicore.h b/mobicore/provlib/inc_private/mobicore.h deleted file mode 100644 index 1806f2b..0000000 --- a/mobicore/provlib/inc_private/mobicore.h +++ /dev/null @@ -1,174 +0,0 @@ -/// @file mobicore.h -/// @author secunet AG (IKU) -/// -/// This file is a convenience header file (top-level) including -/// all MobiCore-related and platform-specific stuff. - -#ifndef _INC_MOBICORE_H_ -#define _INC_MOBICORE_H_ - -#if !defined(LINUX) && !defined(ANDROID_ARM) && !defined(WIN32) -#error "You MUST define either LINUX or ANDROID_ARM or WIN32" -#endif - -// standard C stuff... - -#if defined(__cplusplus) && !defined(ANDROID_ARM) -#include <string> -#include <vector> -#include <map> -#endif - -#include <stdlib.h> -#include <string.h> -#include <stdio.h> -#include <stdarg.h> -#include <stdbool.h> -#include <stdint.h> - -#ifdef LINUX -#include <safemem.h> -#endif - -#if defined(WIN32) && defined(_DEBUG) // enable memory leak detection -#define _CRTDBG_MAP_ALLOC -#define _CRTDBG_MAP_ALLOC_NEW -#include <windows.h> -#include <crtdbg.h> -#define MYDEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__) -#define new MYDEBUG_NEW -#endif - -#ifndef _NO_OPENSSL_INCLUDES - -// OpenSSL stuff... - -#include <openssl/rand.h> -#include <openssl/sha.h> -#include <openssl/aes.h> -#include <openssl/rsa.h> -#include <openssl/bn.h> -#include <openssl/objects.h> -#include <openssl/err.h> - -#endif - -#ifdef WIN32 - -#define WIN32_LEAN_AND_MEAN -#include <windows.h> - -#pragma pack(push,4) - -#pragma warning ( disable : 4200 4996 ) - -#define GDPUBLIC -#define GDAPI __fastcall -#define PACK_ATTR -#define likely(cond) cond -#define unlikely(cond) cond - -#define bad_read_ptr(_p,_c) IsBadReadPtr((const void *)(_p),(UINT_PTR)(_c)) -#define bad_write_ptr(_p,_c) IsBadWritePtr((void *)(_p),(UINT_PTR)(_c)) - -#define PATH_SEPARATOR "\\" -#define PATH_SEP_CHAR '\\' -#define DYNLIB_PREFIX "" -#define DYNLIB_EXTENSION ".dll" - -#else - -#define GDPUBLIC __attribute__((visibility("default"))) -#define GDAPI -#define PACK_ATTR __attribute__((packed)) -#define likely(x) __builtin_expect((x),1) -#define unlikely(x) __builtin_expect((x),0) - -#define bad_read_ptr(_p,_c) (NULL==(_p)) -#define bad_write_ptr(_p,_c) (NULL==(_p)) - -#define PATH_SEPARATOR "/" -#define PATH_SEP_CHAR '/' -#define DYNLIB_PREFIX "lib" -#define DYNLIB_EXTENSION ".so" - -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/file.h> -#include <sys/wait.h> -#include <fcntl.h> -#include <pthread.h> -#include <errno.h> -#include <time.h> -#include <sys/socket.h> -#include <arpa/inet.h> -#include <sched.h> -#include <dlfcn.h> -#include <signal.h> -#include <ctype.h> -#ifndef LINUX -#include <android/log.h> -#else -#include <syslog.h> -#endif - -#endif - -#include <stdbool.h> -#include <stdint.h> - -// MobiCore stuff... - -#ifdef WIN32 -#undef UUID -#undef uuid_t -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#include <MobiCoreDriverApi.h> -#include <mcContainer.h> -#include <tlCmApi.h> -#include <tlCmUuid.h> -#include <mcVersionHelper.h> -#include <mcVersionInfo.h> - -enum _mcAuthState -{ - AUTH_NONE = 0, - AUTH_SOC, - AUTH_ROOT, - AUTH_SP -}; - -typedef enum _mcAuthState mcAuthState; - -#ifdef __cplusplus -} -#endif - -#ifdef WIN32 -#pragma pack(pop) -#endif - -#include <MobiCoreRegistry.h> - -#define IS_VALID_SPID(_x) ((0xFFFFFFFF!=(_x)) && (0xFFFFFFFE!=(_x))) -#define IS_VALID_ROOTID(_x) IS_VALID_SPID(_x) -#define IS_VALID_UUID(_x) ( ((_x).value[ 0]!=0xFF) && ((_x).value[ 1]!=0xFF) &&\ - ((_x).value[ 2]!=0xFF) && ((_x).value[ 3]!=0xFF) &&\ - ((_x).value[ 4]!=0xFF) && ((_x).value[ 5]!=0xFF) &&\ - ((_x).value[ 6]!=0xFF) && ((_x).value[ 7]!=0xFF) &&\ - ((_x).value[ 8]!=0xFF) && ((_x).value[ 9]!=0xFF) &&\ - ((_x).value[10]!=0xFF) && ((_x).value[11]!=0xFF) &&\ - ((_x).value[12]!=0xFF) && ((_x).value[13]!=0xFF) &&\ - ((_x).value[14]!=0xFF) && ((_x).value[15]!=0xFF) && ((_x).value[15]!=0xFE) ) - -#define MC_SO_PLAIN_SIZE(_struct) offsetof(_struct,co) -#define MC_SO_ENC_SIZE(_struct) sizeof(_struct.co) - -#endif // _INC_MOBICORE_H_ - diff --git a/mobicore/provlib/inc_public/gdmcprovlib.h b/mobicore/provlib/inc_public/gdmcprovlib.h deleted file mode 100644 index 71196ca..0000000 --- a/mobicore/provlib/inc_public/gdmcprovlib.h +++ /dev/null @@ -1,424 +0,0 @@ -/// -/// @file gdmcprovlib.h -/// @author Giesecke & Devrient GmbH, Munich, Germany -/// -/// This header file declares simple data types and functions -/// comprising the G&D Provisioning API. -/// - -#ifndef _INC_GDPROVLIB_H_ -#define _INC_GDPROVLIB_H_ - -#include <stdlib.h> - -#ifdef __cplusplus -extern "C" { -#endif - -// Check defines (macros)... - -#if !defined(WIN32) && !defined(LINUX) && !defined(ARM) -#error "You MUST define one of WIN32, LINUX, and ARM (platform)." -#endif - -#if !defined(_32BIT) && !defined(_64BIT) -#error "You MUST define either _32BIT or _64BIT." -#endif - -#if !defined(_LENDIAN) && !defined(_BENDIAN) -#error "You MUST define either _LENDIAN or _BENDIAN." -#endif - -// Declare simple signed and unsigned integer types - -/// a byte (octet), unsigned, 0..255 -typedef unsigned char _u8; - -/// a signed byte, -128..+127 -typedef signed char _i8; - -/// an unsigned 16bit integer, 0..65.535 -typedef unsigned short _u16; - -/// a signed 16bit integer, -32.768..+32.767 -typedef signed short _i16; - -/// an unsigned 32bit integer, 0..4.294.967.295 -typedef unsigned int _u32; - -/// a signed 32bit integer, -2.147.483.648..+2.147.483.647 -typedef signed int _i32; - -#ifdef WIN32 - -#define GDPUBLIC -#define GDPROVAPI __fastcall - -/// an unsigned 64bit integer, 0..18.446.744.073.709.551.615 -typedef unsigned __int64 _u64; - -/// a signed 64bit integer, -9.223.372.036.854.775.808..+9.223.372.036.854.775.807 -typedef signed __int64 _i64; - -#else - -#define GDPUBLIC __attribute__((visibility("default"))) -#define GDPROVAPI - -#ifdef _32BIT - -/// an unsigned 64bit integer, 0..18.446.744.073.709.551.615 -typedef unsigned long long _u64; - -/// a signed 64bit integer, -9.223.372.036.854.775.808..+9.223.372.036.854.775.807 -typedef signed long long _i64; - -#else // 64bit - -/// an unsigned 64bit integer, 0..18.446.744.073.709.551.615 -typedef unsigned long _u64; - -/// a signed 64bit integer, -9.223.372.036.854.775.808..+9.223.372.036.854.775.807 -typedef signed long _i64; - -#endif // _32BIT - -#endif // WIN32 - -////////////////////////////////////////////////////////////////////////////// - -/// G&D error codes, which are unsigned 32bit integers -typedef _u32 gderror; - -/// everything okay, operation successful -#define GDERROR_OK ((gderror)0x00000000) - -/// one or more of the input parameters to a function is/are invalid -#define GDERROR_PARAMETER ((gderror)0x00000001) - -/// connection problem occured, unable to establish a connection to the -/// Key Provisioning Host (KPH) -#define GDERROR_CONNECTION ((gderror)0x00000002) - -/// communication problem occured, unable to communicate with the -/// Key Provisioning Host (KPH) -#define GDERROR_COMMUNICATION ((gderror)0x00000003) - -/// GDMCProvShutdownLibrary was called without calling GDMCProvInitializeLibrary -#define GDERROR_NOT_INITIALIZED ((gderror)0x00000004) - -/// GDMCProvBeginProvisioning called but no more handles available -#define GDERROR_NO_MORE_HANDLES ((gderror)0x00000005) - -/// An unknown or invalid gdhandle was passed to a function -#define GDERROR_INVALID_HANDLE ((gderror)0x00000006) - -/// A so called structured exception occured, which is a severe error -/// (MS Windows only) -#define GDERROR_CPU_EXCEPTION ((gderror)0x00000007) - -/// Unable to retrieve the SUID of the SoC -#define GDERROR_CANT_GET_SUID ((gderror)0x00000008) - -/// Unable to generate the authentication token SO.AuthToken -#define GDERROR_CANT_BUILD_AUTHTOKEN ((gderror)0x00000009) - -/// Unable to dump the authentication token SO.AuthToken -#define GDERROR_CANT_DUMP_AUTHTOKEN ((gderror)0x0000000A) - -/// Unable to generate the receipt SD.Receipt -#define GDERROR_CANT_BUILD_RECEIPT ((gderror)0x0000000B) - -/// (only product version): Authentication KPH Connector <-> Key Provisioning Host (KPH) failed -#define GDERROR_AUTH_FAILED ((gderror)0x0000000C) - -/// validation of the device binding failed -#define GDERROR_VALIDATION_FAILURE ((gderror)0x0000000D) - -/// insufficient memory available -#define GDERROR_INSUFFICIENT_MEMORY ((gderror)0x0000000E) - -/// synchronization error occurred (thread concurrency) -#define GDERROR_SYNCHRONIZATION ((gderror)0x0000000F) - -/// the Key Provisioning Host (KPH) was not able to generate a random key (TRNG) -#define GDERROR_CANT_GENERATE_KEY ((gderror)0x00000010) - -/// the received cryptographic message format is erroneous -#define GDERROR_MESSAGE_FORMAT ((gderror)0x00000011) - -/// CRC32 checksum error -#define GDERROR_CRC32 ((gderror)0x00000012) - -/// Hash value (message digest) validation error -#define GDERROR_MESSAGE_DIGEST ((gderror)0x00000013) - -/// SUID comparison failed -#define GDERROR_SUID_MISMATCH ((gderror)0x00000014) - -/// the Device could not generate the authentication token SO.AuthToken for any reason -#define GDERROR_GENAUTHTOK_FAILED ((gderror)0x00000015) - -/// the Device could not wrap the authentication token in a secure object (SO) -#define GDERROR_WRAPOBJECT_FAILED ((gderror)0x00000016) - -/// the Device could not store SO.AuthToken for any reason -#define GDERROR_STORE_SO_FAILED ((gderror)0x00000017) - -/// the Key Provisioning Host (KPH) could not generate the receipt SD.Receipt for any reason -#define GDERROR_GENRECEIPT_FAILED ((gderror)0x00000018) - -/// the Key Provisioning Host (KPH) triggered a SO.AuthToken validation in the Device but no SO.AuthToken is available -#define GDERROR_NO_AUTHTOK_AVAILABLE ((gderror)0x00000019) - -/// the Device could not perform a read-back of the recently stored SO.AuthToken -#define GDERROR_AUTHTOK_RB_FAILED ((gderror)0x0000001A) - -/// the called API function is not implemented -#define GDERROR_NOT_IMPLEMENTED ((gderror)0x0000001B) - -/// generic (unspecified) error -#define GDERROR_UNKNOWN ((gderror)0x0000001C) - -/// MobiCore library initialization or cleanup failed -#define GDERROR_MOBICORE_LIBRARY ((gderror)0x0000001D) - -/// supplied (output) buffer too small -#define GDERROR_BUFFER_TOO_SMALL ((gderror)0x0000001E) - -/// cryptographic-related error occured, e.g. loading of RSA keys, etc. -#define GDERROR_CRYPTO_FAILURE ((gderror)0x0000001F) - -/// no error code: device binding completed successfully -#define GDERROR_PROVISIONING_DONE ((gderror)0x10000001) - -////////////////////////////////////////////////////////////////////////////// - -/// G&D handle (to one instance of the Provisioning API) -typedef _u32 gdhandle; - -/// Returns the current version of the Provisioning API. -/// -/// @return an unsigned 32bit integer consisting of four bytes aa|bb|cc|dd -/// with major version (aa), minor version (bb), patch level (cc), and -/// OEM (dd), which denotes the numeric ID of an OEM. -GDPUBLIC _u32 GDPROVAPI GDMCProvGetVersion ( void ); - -/// [PRODUCTION STATION ONLY] Formats an error message for an error code, -/// possibly containing more detailed information about the error. This function -/// is NOT implemented in the ARM version of the library because no diagnostic -/// messages can be displayed during the production. -/// -/// @param[in] provhandle the handle returned by GDMCProvBeginProvisioning; -/// can be null (0) to format a message for a global -/// error code (not context-specific) -/// @param[in] errorcode the G&D error code -/// @param[in/out] msgbuf pointer to buffer receiving the UTF-8 encoded -/// error message (in), buffer filled with error -/// message (out) -/// @param[in/out] size size of buffer pointed to by msgbuf specified -/// as wide characters (in), number of wide -/// characters copied into msgbuf (out) -/// -/// @return result code (e.g. buffer too small) -GDPUBLIC gderror GDPROVAPI GDMCProvFormatErrorMessage ( gdhandle provhandle, - gderror errorcode, - char *msgbuf, - _u32 *size ); - -/// Initializes the G&D Provisioning API (library) globally. If called -/// by the Production Software Station, then a TLS-secured channel to -/// the Key Provisioning Host (KPH) is established. -/// In a multithreaded environment, this function has to be called from -/// the primary thread (LWP 0). -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvInitializeLibrary ( void ); - -/// Performs a global shutdown of the G&D Provisioning API (library). -/// After this call, all resources are cleaned up and all handles are -/// closed. No functions except for GDMCProvInitializeLibrary may be -/// called anymore. -/// In a multithread environment, this function has to be called from -/// the primary thread (LWP 0). -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvShutdownLibrary ( void ); - -/// Creates one instance of the key provisioning (aka "device binding") -/// -/// @param[in/out] provhandle pointer to memory location receiving the -/// handle (in), the handle or 0 (out) -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvBeginProvisioning ( gdhandle *provhandle ); - -/// Destroys one instance of the key provisioning (aka "device binding") -/// -/// @param[in] provhandle the handle returned by GDMCProvBeginProvisioning -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvEndProvisioning ( gdhandle provhandle ); - -/// Executes one provisioning step of the full sequence. The caller has to -/// call this function in a loop until either an error is reported or the -/// error code GDERROR_PROVISIONING_DONE is returned (meaning successful -/// provisioning). Please refer to the MobiCore Provisioning API documentation -/// for details. -/// -/// @param[in] provhandle the handle returned by -/// GDMCProvBeginProvisioning -/// @param[in] msgin pointer to buffer containing the -/// input message; may be NULL if no message -/// available -/// @param[in] msgin_size size of buffer pointed to by msgin in bytes -/// @param[in/out] msgout pointer to buffer receiving the output -/// message (in); output message (out) -/// @param[in/out] msgout_size size of buffer pointed to by msgout in -/// bytes (in); number of bytes copied to msgout -/// (out) -/// -/// @return G&D error code; GDERROR_PROVISIONING_DONE -/// if provisioning successfully completed. -GDPUBLIC gderror GDPROVAPI GDMCProvExecuteProvisioningStep ( - gdhandle provhandle, - const _u8 *msgin, - _u32 msgin_size, - _u8 *msgout, - _u32 *msgout_size ); - -/// [PRODUCTION STATION ONLY] Convenience function to format an SD.Receipt -/// -/// @param[in] receipt pointer to buffer containing the -/// binary SD.Receipt -/// @param[in] receipt_size size of binary data pointed to by -/// receipt in bytes -/// @param[in/out] fmt_receipt pointer to buffer receiving the receipt as -/// a BASE64-encoded string (in); the string (out) -/// @param[in/out] fmt_receipt_size size of buffer pointed to by fmt_receipt in -/// bytes (in); number of bytes copied to -/// fmt_receipt (out) -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvFormatReceipt ( - const _u8 *receipt, - _u32 receipt_size, - _u8 *fmt_receipt, - _u32 *fmt_receipt_size ); - -/// [PRODUCTION STATION ONLY] Convenience function to query the SUID of -/// the currently provisioned device (e.g. can be used as primary key in -/// a production database) -/// -/// @param[in] provhandle the handle returned by -/// GDMCProvBeginProvisioning -/// @param[in/out] suid pointer to buffer (16 octets, in) receiving the -/// SUID of the current mobile device (out) -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvGetSUID ( - gdhandle provhandle, - _u8 *suid ); - -/// [DEVICE ONLY] Callback function called by the Provisioning API when -/// GDMCProvExecuteProvisioningStep is executed in the Device. This function -/// shall store the authentication token SO.AuthToken in a secure location. -/// -/// @param[in] authtok pointer to buffer containing SO.AuthToken -/// @param[in] authtok_size size of buffer pointed to be authtok; -/// shall be 124 octets -/// -/// @return G&D error code -typedef gderror (*authtok_writecb)( const _u8 *authtok, - _u32 authtok_size ); - -/// [DEVICE ONLY] Callback function called by the Provisioning API when -/// GDMCProvExecuteValidationStep is executed in the Device. This function -/// shall perform a read-back of the stored authentication token SO.AuthToken -/// -/// @param[in/out] authtok pointer to buffer receiving SO.AuthToken -/// (in); buffer filled with SO.AuthToken (out) -/// @param[in/out] authtok_size size of buffer pointed to be authtok (in); -/// number of bytes copied to authtok (out); -/// shall be 124 octets -/// -/// @return G&D error code -typedef gderror (*authtok_readcb)( _u8 *authtok, - _u32 *authtok_size ); - -/// [DEVICE ONLY] The OEM must provide two hook functions (callbacks) for the -/// reading and writing of the authentication token SO.AuthToken in the device. -/// -/// @param[in] writefunc callback function called by the Provisioning API -/// when an authentication token SO.AuthToken has to be -/// stored -/// @param[in] readfunc callback function called by the Provisioning API -/// when an authentication token SO.AuthToken has to be -/// read back (for validation purposes) -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvSetAuthTokenCallbacks ( - authtok_writecb writefunc, - authtok_readcb readfunc ); - -/// [PRODUCTION STATION ONLY] The configuration of the provisioning library -/// can be patched into the library binary file. If the OEM decided to perform -/// the configuration e.g. by providing the configuration information via the -/// production database, then this function can be called to configure the -/// provisioning library. -/// -/// @param[in] config_string a zero-terminated configuration string containing -/// the entire configuration information in a format -/// that will be defined by G&D; the exact format of -/// this configuration information can be OEM-specific -/// and will be specified in a separate document -/// -/// @return G&D error code -GDPUBLIC gderror GDPROVAPI GDMCProvSetConfigurationString ( - const char *config_string ); - -////////////////////////////////////////////////////////////////////////////// -// Declaration of message header and trailer -////////////////////////////////////////////////////////////////////////////// - -#ifdef WIN32 - -#pragma warning ( disable : 4200 ) - -#pragma pack(push,1) - -#define PACK_ATTR - -#else // Linux - -#define PACK_ATTR __attribute__((packed)) - -#endif - -typedef struct _gdmc_msgheader gdmc_msgheader; -typedef struct _gdmc_msgtrailer gdmc_msgtrailer; - -/// the G&D MobiCore message header -struct _gdmc_msgheader -{ - _u32 msg_type; ///< message type - _u32 body_size; ///< size of body (may be 0) -} PACK_ATTR; - -/// the G&D MobiCore message trailer -struct _gdmc_msgtrailer -{ - _u32 magic; /// message type (one's complement) - _u32 crc32; /// CRC32 checksum -} PACK_ATTR; - -#ifdef WIN32 -#pragma pack(pop) -#endif - -#ifdef __cplusplus -} -#endif - -#endif // _INC_GDPROVLIB_H_ - diff --git a/mobicore/provlib/src/Android.mk b/mobicore/provlib/src/Android.mk deleted file mode 100644 index db2bd01..0000000 --- a/mobicore/provlib/src/Android.mk +++ /dev/null @@ -1,32 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := gdmcprov -LOCAL_MODULE_TAGS := optional - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../inc_private \ - $(LOCAL_PATH)/../inc_public \ - $(MC_INCLUDE_DIR) - -LOCAL_SRC_FILES := gdmcprovlib.cpp \ - crc32.c \ - mobicore.c \ - gdmcdevicebinding.cpp - -LOCAL_CFLAGS := -O2 -Wall -fomit-frame-pointer -DANDROID_ARM -DARM -D_LENDIAN -D_32BIT \ - -fvisibility=hidden -I$(OPENSSL_INC_DIR) \ - -DGDMCPROVLIB_VERSION=0x01000001 -D$(MC_DEBUG) \ - -D_NO_OPENSSL_INCLUDES - -LOCAL_CXXFLAGS := -O2 -Wall -fomit-frame-pointer -DANDROID_ARM -DARM -D_LENDIAN -D_32BIT \ - -fvisibility-inlines-hidden -fvisibility=hidden \ - -DGDMCPROVLIB_VERSION=0x01000001 -D$(MC_DEBUG) - -LOCAL_CPPFLAGS := -O2 -Wall -fomit-frame-pointer -DANDROID_ARM -DARM -D_LENDIAN -D_32BIT \ - -fvisibility-inlines-hidden -fvisibility=hidden \ - -DGDMCPROVLIB_VERSION=0x01000001 -D$(MC_DEBUG) - -LOCAL_SHARED_LIBRARIES := libMcClient - -include $(BUILD_SHARED_LIBRARY) diff --git a/mobicore/provlib/src/crc32.c b/mobicore/provlib/src/crc32.c deleted file mode 100644 index 37ac0c6..0000000 --- a/mobicore/provlib/src/crc32.c +++ /dev/null @@ -1,49 +0,0 @@ -#include <gdmcprovlib.h> -#include <string.h> - -static _u32 crctable[256]; - -_u32 GDPROVAPI CalcCRC32 ( const _u8 *data, _u32 length ) -{ - _u32 crc = 0xFFFFFFFF; - - while (length--) - crc = (crc>>8) ^ crctable[(crc&0xFF) ^ *data++]; - - return crc ^ 0xFFFFFFFF; -} - -static _u32 GDPROVAPI reflect ( _u32 refl, _u8 c ) -{ - int i; - _u32 value = 0; - - // Swap bit 0 for bit 7, bit 1 For bit 6, etc.... - for (i = 1; i < (c + 1); i++) - { - if (refl & 1) - value |= (1 << (c - i)); - refl >>= 1; - } - - return value; -} - -void GDPROVAPI InitCRCTable ( void ) -{ - int i,j; - - memset(crctable,0,sizeof(crctable)); - - for (i = 0; i <= 0xFF; i++) - { - crctable[i] = reflect(i, 8) << 24; - - for (j = 0; j < 8; j++) - crctable[i] = (crctable[i] << 1) - ^ ((crctable[i] & (1 << 31)) ? 0x04C11DB7 : 0); - - crctable[i] = reflect(crctable[i], 32); - } -} - diff --git a/mobicore/provlib/src/gdmcdevicebinding.cpp b/mobicore/provlib/src/gdmcdevicebinding.cpp deleted file mode 100644 index 27cd667..0000000 --- a/mobicore/provlib/src/gdmcdevicebinding.cpp +++ /dev/null @@ -1,458 +0,0 @@ -/// -/// @file gdmcdevicebinding.cpp -/// @author Giesecke & Devrient GmbH, Munich, Germany -/// -/// Implementation of the (internal) device binding -/// - -#include <stdio.h> -#include <stdarg.h> -#include <string.h> -#include <gdmcprovlib.h> -#include <gdmcprovprotocol.h> -#include <gdmcinstance.h> - -extern "C" -{ - gderror MCGetSUID ( _u8 *suid ); - - gderror MCGenerateAuthToken ( gdmcinst *inst, const gdmc_actmsg_req *req, gdmc_so_authtok *authtok ); -} - -////////////////////////////////////////////////////////////////////////////// -// MS Windows-specific includes -////////////////////////////////////////////////////////////////////////////// - -#if defined(WIN32) - -#define WIN32_LEAN_AND_MEAN -#include <windows.h> - -#ifdef _DEBUG -#include <crtdbg.h> -#endif - -////////////////////////////////////////////////////////////////////////////// -// Linux-specific includes -////////////////////////////////////////////////////////////////////////////// - -#elif defined(LINUX) - -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/file.h> -#include <sys/wait.h> -#include <fcntl.h> -#include <pthread.h> -#include <syslog.h> -#include <errno.h> -#include <time.h> -#include <sys/socket.h> -#include <arpa/inet.h> - -////////////////////////////////////////////////////////////////////////////// -// ARM-specific includes -////////////////////////////////////////////////////////////////////////////// - -#else // ARM - -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/file.h> -#include <sys/wait.h> -#include <fcntl.h> -#include <pthread.h> -#include <errno.h> -#include <time.h> -#include <sys/socket.h> -#include <arpa/inet.h> - -#endif - -#include <gdmcprovprotocol.h> -#include <gdmcinstance.h> -#include <gdmcdevicebinding.h> - -#define MAX_MSGSIZE 4096 - -extern authtok_writecb g_authtok_writecb; -extern authtok_readcb g_authtok_readcb; - -#ifdef WIN32 -#define vsnprintf _vsnprintf - -#pragma warning ( disable : 4996 ) - -#endif - -gderror GDMCComposeErrorMessage ( gdmcinst *inst, gderror error, _u8 *msgout, _u32 *msgout_size, _u32 initial_msgout_size, const char *pszmsg, ... ) -{ - _u32 msgsize = 0; - gdmc_msgheader *header; - gdmc_error_msg *body; - gdmc_msgtrailer *trailer; - va_list ap; - char *buffer = NULL; - _u32 errmsgsize = 0; - _u32 errmsgsize_aligned; - - if (NULL!=pszmsg) - { - buffer = (char*)malloc(MAX_MSGSIZE); - - if (NULL!=buffer) - { - memset(buffer,0,MAX_MSGSIZE); - va_start(ap,pszmsg); - vsnprintf(buffer,MAX_MSGSIZE,pszmsg,ap); - va_end(ap); - - errmsgsize = ((_u32)strlen(buffer))+1; - if (1==errmsgsize) - errmsgsize--; // if empty message, then do not send anything - } - } - - errmsgsize_aligned = (errmsgsize+3)&(~3); - - // compose MC_ERROR message - - msgsize = sizeof(gdmc_msgheader)+sizeof(gdmc_error_msg)+errmsgsize_aligned+sizeof(gdmc_msgtrailer); - - if (msgsize>initial_msgout_size) - { - if (NULL!=buffer) - free(buffer); - return GDERROR_BUFFER_TOO_SMALL; - } - - header = (gdmc_msgheader*)msgout; - body = (gdmc_error_msg*)(msgout+sizeof(gdmc_msgheader)); - trailer = (gdmc_msgtrailer*)(msgout+sizeof(gdmc_msgheader)+sizeof(gdmc_error_msg)+errmsgsize_aligned); - - header->msg_type = MC_ERROR; - header->body_size = sizeof(gdmc_error_msg)+errmsgsize; - - body->errorcode = error; - body->errmsg_length = errmsgsize_aligned; - - if ((NULL!=buffer) && (0!=errmsgsize)) - { - memset(body->errmsg,0,errmsgsize_aligned); - memcpy(body->errmsg,buffer,errmsgsize); - } - - if (NULL!=buffer) - free(buffer); - - trailer->magic = ~MC_ERROR; - trailer->crc32 = CalcCRC32(msgout,msgsize-sizeof(_u32)); - - *msgout_size = msgsize; - - return GDERROR_OK; -} - -gderror GDPROVAPI GDMCValidateProvMessage ( const _u8 *msg, - _u32 msgsize, - gdmc_msgheader **ppheader, - _u8 **ppbody, - gdmc_msgtrailer **pptrailer ) -{ - _u32 expected_msgsize, aligned_body_size; - _u32 crc32; - gdmc_error_msg *errmsg; - gdmc_actmsg_resp *actmsg; - - *ppheader = NULL; - *ppbody = NULL; - *pptrailer = NULL; - - if (msgsize<(sizeof(gdmc_msgheader)+sizeof(gdmc_msgtrailer))) - return GDERROR_MESSAGE_FORMAT; - - if (msgsize&3) - return GDERROR_MESSAGE_FORMAT; - - if (IsBadReadPtr(msg,sizeof(gdmc_msgheader)+sizeof(gdmc_msgtrailer))) - return GDERROR_PARAMETER; - - *ppheader = (gdmc_msgheader*)msg; - - aligned_body_size = ((*ppheader)->body_size+3)&(~3); - - expected_msgsize = sizeof(gdmc_msgheader)+sizeof(gdmc_msgtrailer)+aligned_body_size; - - if (msgsize!=expected_msgsize) - return GDERROR_MESSAGE_FORMAT; - - if (IsBadReadPtr(msg,expected_msgsize)) - return GDERROR_PARAMETER; - - *ppbody = (_u8*)(msg+sizeof(gdmc_msgheader)); - *pptrailer = (gdmc_msgtrailer*)((*ppbody)+aligned_body_size); - - if ( (*ppheader)->msg_type != (~((*pptrailer)->magic)) ) - return GDERROR_MESSAGE_FORMAT; - - crc32 = CalcCRC32(msg,msgsize-sizeof(_u32)); - - if ( crc32 != (*pptrailer)->crc32 ) - return GDERROR_CRC32; - - switch((*ppheader)->msg_type) - { - case MC_GETSUID_REQ: - if ( 0!=(*ppheader)->body_size) - return GDERROR_MESSAGE_FORMAT; - break; - - case MC_GETSUID_RESP: - if ( SUID_LENGTH!=(*ppheader)->body_size) - return GDERROR_MESSAGE_FORMAT; - break; - - case MC_GENAUTHTOKEN_REQ: - if ( sizeof(gdmc_actmsg_req)!=(*ppheader)->body_size) - return GDERROR_MESSAGE_FORMAT; - if ( MC_CMP_CMD_GENERATE_AUTH_TOKEN != ((gdmc_actmsg_req*)(*ppbody))->msg_type ) - return GDERROR_MESSAGE_FORMAT; - break; - - case MC_GENAUTHTOKEN_RESP: - if ( sizeof(gdmc_actmsg_resp)!=(*ppheader)->body_size) - return GDERROR_MESSAGE_FORMAT; - actmsg = (gdmc_actmsg_resp*)*ppbody; - if ( (MC_CMP_CMD_GENERATE_AUTH_TOKEN|0x80000000) != actmsg->msg_type ) - return GDERROR_MESSAGE_FORMAT; - if ( (SUID_LENGTH+(sizeof(_u32)*3)) != actmsg->authtok.plain_length) - return GDERROR_MESSAGE_FORMAT; - if ( (K_SOC_AUTH_LENGTH/*+SHA256_HASH_LENGTH+AES_BLOCK_SIZE*/) != actmsg->authtok.encrypted_length ) - return GDERROR_MESSAGE_FORMAT; - if ( AUTHENTICATION_TOKEN != actmsg->authtok.type ) - return GDERROR_MESSAGE_FORMAT; - if ( CONTEXT_SYSTEM != actmsg->authtok.context ) - return GDERROR_MESSAGE_FORMAT; - if ( CONT_TYPE_SOC != actmsg->authtok.contType ) - return GDERROR_MESSAGE_FORMAT; - if ( MC_CONT_STATE_ACTIVATED != actmsg->authtok.contState ) - return GDERROR_MESSAGE_FORMAT; - break; - - case MC_VALIDATEAUTHTOKEN_REQ: - if ( sizeof(gdmc_so_authtok)!=(*ppheader)->body_size) - return GDERROR_MESSAGE_FORMAT; - break; - - case MC_ERROR: - if ( (*ppheader)->body_size<sizeof(gdmc_error_msg)) - return GDERROR_MESSAGE_FORMAT; - errmsg = (gdmc_error_msg*)*ppbody; - if ( (*ppheader)->body_size!=(errmsg->errmsg_length+sizeof(gdmc_error_msg)) ) - return GDERROR_MESSAGE_FORMAT; - break; - - default: - return GDERROR_MESSAGE_FORMAT; - } - - return GDERROR_OK; -} - -gderror GDPROVAPI GDMCHandleGetSUID ( gdmcinst *inst, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size ) -{ - _u32 msgsize = sizeof(gdmc_msgheader)+SUID_LENGTH+sizeof(gdmc_msgtrailer); - gdmc_msgheader *header = (gdmc_msgheader*)msgout; - _u8 *body = msgout+sizeof(gdmc_msgheader); - gdmc_msgtrailer *trailer = (gdmc_msgtrailer*)(msgout+sizeof(gdmc_msgheader)+SUID_LENGTH); - gderror error; - - if (msgsize>initial_msgout_size) - return GDMCComposeErrorMessage(inst,GDERROR_BUFFER_TOO_SMALL,msgout,msgout_size,initial_msgout_size, - ERRMSG_0005,initial_msgout_size,msgsize); - - if (inst->state<GDMC_STATE_HAVE_SUID) // request SUID from MobiCore - { - error = MCGetSUID(inst->suid); - - if (GDERROR_OK!=error) - return GDMCComposeErrorMessage(inst,error,msgout,msgout_size,initial_msgout_size, - ERRMSG_000D); - - inst->state = GDMC_STATE_HAVE_SUID; - } - - // We have the SUID, so return the message to the caller - - header->msg_type = MC_GETSUID_RESP; - header->body_size = SUID_LENGTH; - - memcpy(body,inst->suid,SUID_LENGTH); - - trailer->magic = ~MC_GETSUID_RESP; - trailer->crc32 = CalcCRC32(msgout,msgsize-sizeof(_u32)); - - *msgout_size = msgsize; - - return GDERROR_OK; -} - -gderror GDPROVAPI GDMCHandleGenAuthToken ( gdmcinst *inst, - gdmc_actmsg_req *req, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size ) -{ - _u32 msgsize = sizeof(gdmc_msgheader)+sizeof(gdmc_actmsg_resp)+sizeof(gdmc_msgtrailer); - gdmc_msgheader *header = (gdmc_msgheader*)msgout; - gdmc_actmsg_resp *body = (gdmc_actmsg_resp*)(msgout+sizeof(gdmc_msgheader)); - gdmc_msgtrailer *trailer = (gdmc_msgtrailer*)(msgout+sizeof(gdmc_msgheader)+sizeof(gdmc_actmsg_resp)); - gderror error; - - if (msgsize>initial_msgout_size) - return GDMCComposeErrorMessage(inst,GDERROR_BUFFER_TOO_SMALL,msgout,msgout_size,initial_msgout_size, - ERRMSG_0005,initial_msgout_size,msgsize); - - switch(inst->state) - { - case GDMC_STATE_INITIAL: // We do not have the SUID, so get it... - error = GDMCHandleGetSUID(inst,msgout,msgout_size,initial_msgout_size); - if (GDERROR_OK!=error) - return error; - - // discard this message... - - memset(msgout,0,initial_msgout_size); - *msgout_size = 0; - - // fall through... - - case GDMC_STATE_HAVE_SUID: // We have the SUID but no SO.AuthToken (yet) - - GenerateAuthToken: - - memcpy(inst->kSoCAuth,req->kSoCAuth,sizeof(inst->kSoCAuth)); // save K.SoC.Auth - - error = MCGenerateAuthToken(inst,req,&inst->authTok); - - if (GDERROR_OK!=error) - return GDMCComposeErrorMessage(inst,error,msgout,msgout_size,initial_msgout_size,ERRMSG_000E); - - if (NULL!=g_authtok_writecb) - { - error = g_authtok_writecb((const _u8 *)&inst->authTok,sizeof(gdmc_so_authtok)); - if (GDERROR_OK!=error) - return GDMCComposeErrorMessage(inst,error,msgout,msgout_size,initial_msgout_size,ERRMSG_000C); - } - - header->msg_type = MC_GENAUTHTOKEN_RESP; - header->body_size = sizeof(gdmc_actmsg_resp); - - body->msg_type = MC_CMP_CMD_GENERATE_AUTH_TOKEN|0x80000000; - memcpy(&body->authtok,&inst->authTok,sizeof(gdmc_so_authtok)); - - trailer->magic = ~MC_GENAUTHTOKEN_RESP; - trailer->crc32 = CalcCRC32(msgout,msgsize-sizeof(_u32)); - - *msgout_size = msgsize; - - if (inst->state<GDMC_STATE_HAVE_AUTHTOK) - inst->state = GDMC_STATE_HAVE_AUTHTOK; - - return GDERROR_OK; - - default: //case GDMC_STATE_HAVE_AUTHTOK: -> We have already the SO.AuthTok, check if K.SoC.Auth still matches!!! - - if (memcmp(inst->kSoCAuth,req->kSoCAuth,sizeof(inst->kSoCAuth))) - { - // Oh oh... the KPH generated a new K.SoC.Auth and our SO.AuthToken is invalid now... (generate new one) - - memset(&inst->authTok,0,sizeof(inst->authTok)); - inst->state = GDMC_STATE_HAVE_SUID; - goto GenerateAuthToken; - } - - // Okay, K.SoC.Auth still matches and we still have the SO.AuthToken - - header->msg_type = MC_GENAUTHTOKEN_RESP; - header->body_size = sizeof(gdmc_actmsg_resp); - - body->msg_type = MC_CMP_CMD_GENERATE_AUTH_TOKEN|0x80000000; - memcpy(&body->authtok,&inst->authTok,sizeof(gdmc_so_authtok)); - - trailer->magic = ~MC_GENAUTHTOKEN_RESP; - trailer->crc32 = CalcCRC32(msgout,msgsize-sizeof(_u32)); - - *msgout_size = msgsize; - - return GDERROR_OK; - } -} - -gderror GDPROVAPI GDMCHandleValidateAuthToken ( gdmcinst *inst, - gdmc_so_authtok *validateSoAuthTok, - _u8 *msgout, - _u32 *msgout_size, - _u32 initial_msgout_size ) -{ - _u32 msgsize = sizeof(gdmc_msgheader)+sizeof(gdmc_error_msg)+sizeof(gdmc_msgtrailer); - gdmc_msgheader *header = (gdmc_msgheader*)msgout; - gdmc_error_msg *body = (gdmc_error_msg*)(msgout+sizeof(gdmc_msgheader)); - gdmc_msgtrailer *trailer = (gdmc_msgtrailer*)(msgout+sizeof(gdmc_msgheader)+sizeof(gdmc_error_msg)); - gderror error; - gdmc_so_authtok rb_authtok; - _u32 rb_authtok_size; - - if (msgsize>initial_msgout_size) - return GDMCComposeErrorMessage(inst,GDERROR_BUFFER_TOO_SMALL,msgout,msgout_size,initial_msgout_size, - ERRMSG_0005,initial_msgout_size,msgsize); - - if (GDMC_STATE_HAVE_AUTHTOK!=inst->state) // Too early call: We do not have an SO.AuthToken to be validated! - return GDMCComposeErrorMessage(inst,GDERROR_VALIDATION_FAILURE,msgout,msgout_size,initial_msgout_size, - ERRMSG_000F,initial_msgout_size,msgsize); - - header->msg_type = MC_ERROR; - header->body_size = sizeof(gdmc_error_msg); - - body->errorcode = GDERROR_PROVISIONING_DONE; - - // 1.) First of all, compare the delivered SO.AuthToken with the one we have stored in our instance - - if (memcmp(validateSoAuthTok,&inst->authTok,sizeof(gdmc_so_authtok))) - { - body->errorcode = GDERROR_VALIDATION_FAILURE; - } - else - { - // 2.) Perform readback (if available) and re-check auth token - - if (NULL!=g_authtok_readcb) - { - rb_authtok_size = sizeof(rb_authtok); - - error = g_authtok_readcb((_u8*)&rb_authtok,&rb_authtok_size); - - if (GDERROR_OK!=error) - body->errorcode = error; - else - { - if ( (rb_authtok_size!=sizeof(gdmc_so_authtok)) || - (memcmp(validateSoAuthTok,&rb_authtok,sizeof(gdmc_so_authtok))) ) - body->errorcode = GDERROR_VALIDATION_FAILURE; - } - } - } - - trailer->magic = ~MC_ERROR; - trailer->crc32 = CalcCRC32(msgout,msgsize-sizeof(_u32)); - - *msgout_size = msgsize; - - return GDERROR_PROVISIONING_DONE; -} - diff --git a/mobicore/provlib/src/gdmcprovlib.cpp b/mobicore/provlib/src/gdmcprovlib.cpp deleted file mode 100644 index 9c6dae7..0000000 --- a/mobicore/provlib/src/gdmcprovlib.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/// -/// @file gdmcprovlib.cpp -/// @author Giesecke & Devrient GmbH, Munich, Germany -/// -/// Implementation of the API functions (Provisioning -/// Library) -/// - -#include <gdmcprovlib.h> -#include <stdio.h> -#include <stdarg.h> -#include <string.h> - -////////////////////////////////////////////////////////////////////////////// -// MS Windows-specific includes -////////////////////////////////////////////////////////////////////////////// - -#if defined(WIN32) - -#define WIN32_LEAN_AND_MEAN -#include <windows.h> -static HMODULE g_hInstance = NULL; - -////////////////////////////////////////////////////////////////////////////// -// Linux-specific includes -////////////////////////////////////////////////////////////////////////////// - -#elif defined(LINUX) - -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/file.h> -#include <sys/wait.h> -#include <fcntl.h> -#include <pthread.h> -#include <syslog.h> -#include <errno.h> -#include <time.h> -#include <sys/socket.h> -#include <arpa/inet.h> - -////////////////////////////////////////////////////////////////////////////// -// ARM-specific includes -////////////////////////////////////////////////////////////////////////////// - -#else // ARM - -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/file.h> -#include <sys/wait.h> -#include <fcntl.h> -#include <pthread.h> -#include <errno.h> -#include <time.h> -#include <sys/socket.h> -#include <arpa/inet.h> - -#endif - -#include <gdmcprovprotocol.h> -#include <gdmcinstance.h> -#include <gdmcdevicebinding.h> - -extern "C" { -extern bool mccmOpen ( void ); -extern void mccmClose ( void ); -} - -authtok_writecb g_authtok_writecb = NULL; -authtok_readcb g_authtok_readcb = NULL; - -////////////////////////////////////////////////////////////////////////////// -// API functions (implementation) -////////////////////////////////////////////////////////////////////////////// - -// this API function is not available on ARM -static gderror GDPROVAPI _GDMCProvFormatErrorMessage ( - gdhandle provhandle, - gderror errorcode, - char *msgbuf, - _u32 *size ) -{ - return GDERROR_NOT_IMPLEMENTED; -} - -static gderror GDPROVAPI _GDMCProvInitializeLibrary ( void ) -{ - if (unlikely( !mccmOpen() )) - return GDERROR_MOBICORE_LIBRARY; - - return GDERROR_OK; -} - -static gderror GDPROVAPI _GDMCProvShutdownLibrary ( void ) -{ - mccmClose(); - return GDERROR_OK; -} - -static gderror GDPROVAPI _GDMCProvBeginProvisioning ( gdhandle *provhandle ) -{ - gdmcinst *inst; - - if (IsBadWritePtr(provhandle,sizeof(gdhandle))) - return GDERROR_PARAMETER; - - inst = (gdmcinst*)malloc(sizeof(gdmcinst)); - - if (NULL==inst) - { - *provhandle = 0; - return GDERROR_INSUFFICIENT_MEMORY; - } - - memset(inst,0,sizeof(gdmcinst)); - - *provhandle = (gdhandle)inst; - - return GDERROR_OK; -} - -static gderror GDPROVAPI _GDMCProvEndProvisioning ( gdhandle provhandle ) -{ - gdmcinst *inst = (gdmcinst*)provhandle; - - if (IsBadWritePtr(inst,sizeof(gdmcinst))) - return GDERROR_PARAMETER; - - free(inst); - - return GDERROR_OK; -} - -static gderror GDPROVAPI _GDMCProvExecuteProvisioningStep ( - gdhandle provhandle, - const _u8 *msgin, - _u32 msgin_size, - _u8 *msgout, - _u32 *msgout_size ) -{ - gderror error = GDERROR_OK; - gdmcinst *inst = (gdmcinst*)provhandle; - gdmc_msgheader *header = NULL; - _u8 *body = NULL; - gdmc_msgtrailer *trailer = NULL; - _u32 initial_msgout_size; - - // 1.) Prolog: Check parameters... - - if (IsBadWritePtr(inst,sizeof(gdmcinst))) - return GDERROR_PARAMETER; - - if ((0!=msgin_size) && (IsBadReadPtr(msgin,msgin_size))) - return GDERROR_PARAMETER; - - if (IsBadWritePtr(msgout_size,sizeof(_u32))) - return GDERROR_PARAMETER; - - initial_msgout_size = *msgout_size; - - if (0!=*msgout_size) - { - if (IsBadWritePtr(msgout,*msgout_size)) - return GDERROR_PARAMETER; - memset(msgout,0,*msgout_size); - } - - *msgout_size = 0; - - // 2.) Evaluate the message that has been received - - error = GDMCValidateProvMessage(msgin,msgin_size,&header,&body,&trailer); - - if (GDERROR_OK!=error) // something is wrong with the received message - return GDMCComposeErrorMessage(inst,error,msgout,msgout_size,initial_msgout_size,ERRMSG_0006); - - // 3.) Check which message has been received - - switch(header->msg_type) - { - case MC_GETSUID_REQ: - return GDMCHandleGetSUID(inst,msgout,msgout_size,initial_msgout_size); - - case MC_GENAUTHTOKEN_REQ: - return GDMCHandleGenAuthToken(inst,(gdmc_actmsg_req*)body,msgout,msgout_size,initial_msgout_size); - - case MC_VALIDATEAUTHTOKEN_REQ: - return GDMCHandleValidateAuthToken(inst,(gdmc_so_authtok*)body,msgout,msgout_size,initial_msgout_size); - - default: - return GDMCComposeErrorMessage(inst,GDERROR_UNKNOWN,msgout,msgout_size,initial_msgout_size,ERRMSG_0007); - } -} - -////////////////////////////////////////////////////////////////////////////// -// Structured Exception Handling (Windows only) -////////////////////////////////////////////////////////////////////////////// - -#if defined(WIN32) && !defined(_NO_STRUCTURED_EXCEPTIONS) - -static DWORD GDPROVAPI HandleStructuredException ( DWORD dwExcepCode ) -{ -#ifndef _DEBUG - return EXCEPTION_EXECUTE_HANDLER; -#else // _DEBUG - switch(dwExcepCode) - { - case EXCEPTION_BREAKPOINT: - case EXCEPTION_SINGLE_STEP: - return EXCEPTION_CONTINUE_SEARCH; - default: - return EXCEPTION_EXECUTE_HANDLER; - } -#endif -} - -#define SE_TRY __try { -#define SE_CATCH } __except(HandleStructuredException(GetExceptionCode())) { return GDERROR_CPU_EXCEPTION; } - -#else // !WIN32 || _NO_STRUCTURED_EXCEPTIONS - -#define SE_TRY -#define SE_CATCH - -#endif // WIN32 - -////////////////////////////////////////////////////////////////////////////// -// API functions (exported) -////////////////////////////////////////////////////////////////////////////// - -extern "C" _u32 GDPROVAPI GDMCProvGetVersion ( void ) -{ - return GDMCPROVLIB_VERSION; -} - -extern "C" gderror GDPROVAPI GDMCProvFormatErrorMessage ( - gdhandle provhandle, - gderror errorcode, - char *msgbuf, - _u32 *size ) -{ - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return _GDMCProvFormatErrorMessage(provhandle,errorcode,msgbuf,size); - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// -} - -extern "C" gderror GDPROVAPI GDMCProvInitializeLibrary ( void ) -{ - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return _GDMCProvInitializeLibrary(); - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// -} - -extern "C" gderror GDPROVAPI GDMCProvShutdownLibrary ( void ) -{ - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return _GDMCProvShutdownLibrary(); - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// -} - -extern "C" gderror GDPROVAPI GDMCProvBeginProvisioning ( gdhandle *provhandle ) -{ - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return _GDMCProvBeginProvisioning(provhandle); - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// -} - -extern "C" gderror GDPROVAPI GDMCProvEndProvisioning ( gdhandle provhandle ) -{ - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return _GDMCProvEndProvisioning(provhandle); - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// -} - -extern "C" gderror GDPROVAPI GDMCProvExecuteProvisioningStep ( - gdhandle provhandle, - const _u8 *msgin, - _u32 msgin_size, - _u8 *msgout, - _u32 *msgout_size ) -{ - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return _GDMCProvExecuteProvisioningStep(provhandle,msgin,msgin_size, - msgout,msgout_size); - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// -} - -extern "C" gderror GDPROVAPI GDMCProvFormatReceipt ( - const _u8 *receipt, - _u32 receipt_size, - _u8 *fmt_receipt, - _u32 *fmt_receipt_size ) -{ - return GDERROR_NOT_IMPLEMENTED; -} - -extern "C" gderror GDPROVAPI GDMCProvGetSUID ( - gdhandle provhandle, - _u8 *suid ) -{ - return GDERROR_NOT_IMPLEMENTED; -} - -extern "C" gderror GDPROVAPI GDMCProvSetAuthTokenCallbacks ( - authtok_writecb writefunc, - authtok_readcb readfunc ) -{ - g_authtok_writecb = writefunc; - g_authtok_readcb = readfunc; - - return GDERROR_OK; -} - -extern "C" gderror GDPROVAPI GDMCProvSetConfigurationString ( - const char *config_string ) -{ -#ifdef ARM - - return GDERROR_NOT_IMPLEMENTED; - -#else - - SE_TRY // MUST BE FIRST INSTRUCTION //////////////////////////////////////// - - return GDERROR_OK; - - SE_CATCH // MUST BE LAST INSTRUCTION /////////////////////////////////////// - -#endif -} - -#ifdef WIN32 - -/// DLL main function required by MS Windows DLLs -/// -/// @param[in] hinstDLL instance handle (module) -/// @param[in] fdwReason reason for calling (attach, detach, ...) -/// @param[in] lpvReserved reserved -/// -/// @return TRUE if DLL loading/unloading successful, FALSE otherwise -BOOL WINAPI DllMain ( HINSTANCE hinstDLL, - DWORD fdwReason, - LPVOID lpvReserved ) -{ - switch(fdwReason) - { - case DLL_PROCESS_ATTACH: - // We don't need additional calls with DLL_THREAD_ATTACH. - g_hInstance = (HMODULE)hinstDLL; - DisableThreadLibraryCalls(hinstDLL); - InitCRCTable(); - return TRUE; - case DLL_PROCESS_DETACH: // fall through - case DLL_THREAD_ATTACH: // fall through - case DLL_THREAD_DETACH: - return TRUE; - default: - break; - } - return FALSE; -} - -#else // library initialization and cleanup (Linux/ARM) - -void gdmcprovlib_init ( void ) __attribute__((constructor)); -void gdmcprovlib_fini ( void ) __attribute__((destructor)); - -/// shared object global initialization function; gets automatically -/// called when library is loaded -void gdmcprovlib_init ( void ) -{ - InitCRCTable(); -} - -/// shared object global cleanup function; gets automatically -/// called when library is unloaded -void gdmcprovlib_fini ( void ) -{ - -} - -#endif // WIN32 - - diff --git a/mobicore/provlib/src/mobicore.c b/mobicore/provlib/src/mobicore.c deleted file mode 100644 index 2f4e419..0000000 --- a/mobicore/provlib/src/mobicore.c +++ /dev/null @@ -1,587 +0,0 @@ -#ifndef _SBL_VERSION // SBL = Secondary Bootloader Version - -#include <stdio.h> -#include <stdarg.h> -#include <string.h> -#include <gdmcprovlib.h> -#include <gdmcprovprotocol.h> -#include <gdmcinstance.h> - -typedef struct tagMCCM MCCM; - -struct tagMCCM -{ - cmp_t *cmp; ///< World Shared Memory (WSM) to the TCI buffer - mcSessionHandle_t sess; ///< session handle - mcResult_t lasterror; ///< last MC driver error - cmpReturnCode_t lastcmperr; ///< last Content Management Protocol error - uint32_t lastmccmerr; ///< error code from MCCM (MobiCore Content Management) library -}; - -static MCCM g_mccm; - -// Copied from MCCM library not to have this additional dependency! - -// returns 1 if successful, 0 otherwise -bool mccmOpen ( void ) -{ - const mcUuid_t UUID = TL_CM_UUID; - mcResult_t result; - - memset(&g_mccm,0,sizeof(MCCM)); - - result = mcOpenDevice(MC_DEVICE_ID_DEFAULT); - - if (MC_DRV_OK != result) - return false; - - result = mcMallocWsm(MC_DEVICE_ID_DEFAULT, 0, sizeof(cmp_t), (uint8_t **)&g_mccm.cmp, 0); - if (MC_DRV_OK != result) - { - mcCloseDevice(MC_DEVICE_ID_DEFAULT); - return false; - } - - result = mcOpenSession(&g_mccm.sess,(const mcUuid_t *)&UUID,(uint8_t *)g_mccm.cmp,(uint32_t)sizeof(cmp_t)); - if (MC_DRV_OK != result) - { - mcFreeWsm(MC_DEVICE_ID_DEFAULT,(uint8_t*)g_mccm.cmp); - mcCloseDevice(MC_DEVICE_ID_DEFAULT); - return false; - } - - return true; -} - -void mccmClose ( void ) -{ - mcCloseSession(&g_mccm.sess); - - if (NULL!=g_mccm.cmp) - mcFreeWsm(MC_DEVICE_ID_DEFAULT,(uint8_t*)g_mccm.cmp); - - mcCloseDevice(MC_DEVICE_ID_DEFAULT); - - memset(&g_mccm,0,sizeof(MCCM)); -} - -static bool mccmTransmit ( int32_t timeout ) -{ - // Send CMP message to content management trustlet. - - g_mccm.lasterror = mcNotify(&g_mccm.sess); - - if (unlikely( MC_DRV_OK!=g_mccm.lasterror )) - return false; - - // Wait for trustlet response. - - g_mccm.lasterror = mcWaitNotification(&g_mccm.sess, timeout); - - if (unlikely( MC_DRV_OK!=g_mccm.lasterror )) - return false; - - return true; -} - -static bool mccmGetSuid ( mcSuid_t *suid ) -{ - g_mccm.lastcmperr = SUCCESSFUL; - - memset(g_mccm.cmp,0,sizeof(cmp_t)); - g_mccm.cmp->msg.cmpCmdGetSuid.cmdHeader.commandId = MC_CMP_CMD_GET_SUID; - - if (unlikely( !mccmTransmit(MC_INFINITE_TIMEOUT) )) - return false; - - if (unlikely( (MC_CMP_CMD_GET_SUID|RSP_ID_MASK)!=g_mccm.cmp->msg.cmpRspGetSuid.rspHeader.responseId )) - { - g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; - return false; - } - - g_mccm.lastcmperr = g_mccm.cmp->msg.cmpRspGetSuid.rspHeader.returnCode; - - if (unlikely( SUCCESSFUL!=g_mccm.lastcmperr )) - { - g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; - return false; - } - - memcpy(suid,&g_mccm.cmp->msg.cmpRspGetSuid.suid,sizeof(mcSuid_t)); - - return true; -} - -static bool mccmGenerateAuthToken ( - const cmpCmdGenAuthToken_t *cmd, - cmpRspGenAuthToken_t *rsp ) -{ - g_mccm.lastcmperr = SUCCESSFUL; - - memset(g_mccm.cmp,0,sizeof(cmp_t)); - - memcpy(g_mccm.cmp,cmd,sizeof(*cmd)); - - if (unlikely( !mccmTransmit(MC_INFINITE_TIMEOUT) )) - return false; - - if (unlikely( (cmd->cmd.sdata.cmdHeader.commandId|RSP_ID_MASK)!=g_mccm.cmp->msg.cmpRspGenAuthToken.rsp.rspHeader.responseId )) - { - g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; - return false; - } - - g_mccm.lastcmperr = g_mccm.cmp->msg.cmpRspGenAuthToken.rsp.rspHeader.returnCode; - - if (unlikely( SUCCESSFUL!=g_mccm.lastcmperr )) - { - g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; - return false; - } - - memcpy(rsp,g_mccm.cmp,sizeof(*rsp)); - - return true; -} - -/////////////////////////////////////////////////////////////////////////////////////////// -// Convenience functions -/////////////////////////////////////////////////////////////////////////////////////////// - -gderror MCGetSUID ( _u8 *suid ) -{ - if (unlikely( NULL==suid )) - return GDERROR_PARAMETER; - - memset(suid,0,SUID_LENGTH); - - if (!mccmGetSuid((mcSuid_t*)suid)) - return GDERROR_CANT_GET_SUID; - - return GDERROR_OK; -} - -gderror MCGenerateAuthToken ( gdmcinst *inst, const gdmc_actmsg_req *req, gdmc_so_authtok *authtok ) -{ - cmpRspGenAuthToken_t rsp; - - if (unlikely( NULL==inst || NULL==req || NULL==authtok )) - return GDERROR_PARAMETER; - - memset(authtok,0,sizeof(gdmc_so_authtok)); - - if (MC_CMP_CMD_GENERATE_AUTH_TOKEN!=req->msg_type) - return GDERROR_MESSAGE_FORMAT; - - if (!mccmGenerateAuthToken((const cmpCmdGenAuthToken_t *)req,&rsp)) - return GDERROR_CANT_BUILD_AUTHTOKEN; - - memcpy(authtok,&rsp.soAuthCont,sizeof(*authtok)); - - return GDERROR_OK; -} - -#else // Secondary Bootloader Version - -#define _NO_OPENSSL_INCLUDES - -#include <stdio.h> -#include <stdarg.h> -#include <string.h> -#include <gdmcprovlib.h> -#include <gdmcprovprotocol.h> -#include <gdmcinstance.h> - -#define SHA256_BLOCK_LENGTH 64 -#define SHA256_DIGEST_LENGTH 32 -#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) - -typedef unsigned char u_int8_t; /* 1-byte (8-bits) */ -typedef unsigned int u_int32_t; /* 4-bytes (32-bits) */ -typedef unsigned long long u_int64_t; /* 8-bytes (64-bits) */ - -typedef unsigned char sha2_byte; /* Exactly 1 byte */ -typedef unsigned int sha2_word32; /* Exactly 4 bytes */ -typedef unsigned long long sha2_word64; /* Exactly 8 bytes */ - -typedef struct _SHA256_CTX { - u_int32_t state[8]; - u_int64_t bitcount; - u_int8_t buffer[SHA256_BLOCK_LENGTH]; -} SHA256_CTX; - -static void SHA256(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]); - -gderror MCGetSUID ( gdmcinst *inst, _u8 suid[SUID_LENGTH] ) -{ - inst->suid[ 0] = 0x11; - inst->suid[ 1] = 0x22; - inst->suid[ 2] = 0x33; - inst->suid[ 3] = 0x44; - inst->suid[ 4] = 0x55; - inst->suid[ 5] = 0x66; - inst->suid[ 6] = 0x77; - inst->suid[ 7] = 0x88; - inst->suid[ 8] = 0x99; - inst->suid[ 9] = 0xAA; - inst->suid[10] = 0xBB; - inst->suid[11] = 0xCC; - inst->suid[12] = 0xDD; - inst->suid[13] = 0xEE; - inst->suid[14] = 0xFF; - inst->suid[15] = 0xFE; - - memcpy(suid,inst->suid,SUID_LENGTH); - - return GDERROR_OK; -} - -gderror MCGenerateAuthToken ( gdmcinst *inst, const gdmc_actmsg_req *req, gdmc_so_authtok *authtok ) -{ - _u8 md[SHA256_DIGEST_LENGTH]; - mcSoAuthTokenCont_t tok; - - memset(&tok,0,sizeof(tok)); - memset(authtok,0,sizeof(gdmc_so_authtok)); - - if (MC_CMP_CMD_GENERATE_AUTH_TOKEN!=req->msg_type) - return GDERROR_MESSAGE_FORMAT; - - SHA256((const unsigned char *)req,offsetof(gdmc_actmsg_req,md),md); // hash it... - - if (memcmp(md,req->md,SHA256_DIGEST_LENGTH)) - return GDERROR_MESSAGE_DIGEST; - - if (memcmp(inst->suid,req->suid,SUID_LENGTH)) - return GDERROR_SUID_MISMATCH; - - // Header: - - tok.soHeader.type = MC_SO_TYPE_REGULAR; - tok.soHeader.version = 1; - tok.soHeader.context = MC_SO_CONTEXT_DEVICE; - tok.soHeader.plainLen = sizeof(tok.coSoc.type)+ - sizeof(tok.coSoc.attribs)+ - sizeof(tok.coSoc.suid); - tok.soHeader.encryptedLen = sizeof(tok.coSoc.co); - - // Plain data: - - tok.coSoc.type = CONT_TYPE_SOC; - tok.coSoc.attribs.state = MC_CONT_STATE_ACTIVATED; - - memcpy(&tok.coSoc.suid,inst->suid,sizeof(tok.coSoc.suid)); - - // Secret: - - memcpy(&tok.coSoc.co.kSocAuth,&inst->kSoCAuth,sizeof(tok.coSoc.co.kSocAuth)); - - SHA256((const unsigned char *)&tok, - offsetof(mcSoAuthTokenCont_t,hashAndPad), - (char *)&tok.hashAndPad); - - tok.hashAndPad[MC_SO_HASH_SIZE] = 0x80; // ISO-padding - - memcpy(authtok,&tok,sizeof(gdmc_so_authtok)); - - return GDERROR_OK; -} - -#undef SHA2_UNROLL_TRANSFORM - -#define LITTLE_ENDIAN 1234 -#define BYTE_ORDER LITTLE_ENDIAN - -#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN) -#error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN -#endif - -#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) -#define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16) -#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) - - -/*** ENDIAN REVERSAL MACROS *******************************************/ -#if BYTE_ORDER == LITTLE_ENDIAN -#define REVERSE32(w,x) { \ - sha2_word32 tmp = (w); \ - tmp = (tmp >> 16) | (tmp << 16); \ - (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ -} -#define REVERSE64(w,x) { \ - sha2_word64 tmp = (w); \ - tmp = (tmp >> 32) | (tmp << 32); \ - tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \ - ((tmp & 0x00ff00ff00ff00ffULL) << 8); \ - (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \ - ((tmp & 0x0000ffff0000ffffULL) << 16); \ -} -#endif /* BYTE_ORDER == LITTLE_ENDIAN */ - -/* - * Macro for incrementally adding the unsigned 64-bit integer n to the - * unsigned 128-bit integer (represented using a two-element array of - * 64-bit words): - */ -#define ADDINC128(w,n) { \ - (w)[0] += (sha2_word64)(n); \ - if ((w)[0] < (n)) { \ - (w)[1]++; \ - } \ -} - -#define R(b,x) ((x) >> (b)) -#define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) - -/* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */ -#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) -#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) - -/* Four of six logical functions used in SHA-256: */ -#define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) -#define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) -#define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) -#define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) - -void SHA256_Transform(SHA256_CTX*, const sha2_word32*); - -const static sha2_word32 K256[64] = { - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, - 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, - 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, - 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, - 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, - 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, - 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, - 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, - 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, - 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, - 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, - 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, - 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL -}; - -/* Initial hash value H for SHA-256: */ -const static sha2_word32 sha256_initial_hash_value[8] = { - 0x6a09e667UL, - 0xbb67ae85UL, - 0x3c6ef372UL, - 0xa54ff53aUL, - 0x510e527fUL, - 0x9b05688cUL, - 0x1f83d9abUL, - 0x5be0cd19UL -}; - -static void SHA256_Init(SHA256_CTX* context) -{ - if (context == (SHA256_CTX*)0) - { - return; - } - memcpy(context->state,sha256_initial_hash_value, SHA256_DIGEST_LENGTH); - memset(context->buffer, 0,SHA256_BLOCK_LENGTH); - context->bitcount = 0; -} - -static void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, T2, *W256; - int j; - - W256 = (sha2_word32*)context->buffer; - - /* Initialize registers with the prev. intermediate value */ - a = context->state[0]; - b = context->state[1]; - c = context->state[2]; - d = context->state[3]; - e = context->state[4]; - f = context->state[5]; - g = context->state[6]; - h = context->state[7]; - - j = 0; - do { -#if BYTE_ORDER == LITTLE_ENDIAN - /* Copy data while converting to host byte order */ - REVERSE32(*data++,W256[j]); - /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; -#else /* BYTE_ORDER == LITTLE_ENDIAN */ - /* Apply the SHA-256 compression function to update a..h with copy */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); -#endif /* BYTE_ORDER == LITTLE_ENDIAN */ - T2 = Sigma0_256(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - j++; - } while (j < 16); - - do { - /* Part of the message block expansion: */ - s0 = W256[(j+1)&0x0f]; - s0 = sigma0_256(s0); - s1 = W256[(j+14)&0x0f]; - s1 = sigma1_256(s1); - - /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); - T2 = Sigma0_256(a) + Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - j++; - } while (j < 64); - - /* Compute the current intermediate hash value */ - context->state[0] += a; - context->state[1] += b; - context->state[2] += c; - context->state[3] += d; - context->state[4] += e; - context->state[5] += f; - context->state[6] += g; - context->state[7] += h; - - /* Clean up */ - a = b = c = d = e = f = g = h = T1 = T2 = 0; -} - -#define bcopy(s,d,len) memcpy(d,s,len) -#define bzero(d,len) memset(d,0,len) - -static void SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; - - if (len == 0) { - /* Calling with no data is valid - we do nothing */ - return; - } - - usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; - if (usedspace > 0) { - /* Calculate how much free space is available in the buffer */ - freespace = SHA256_BLOCK_LENGTH - usedspace; - - if (len >= freespace) { - /* Fill the buffer completely and process it */ - - bcopy(data, &context->buffer[usedspace], freespace); - context->bitcount += freespace << 3; - len -= freespace; - data += freespace; - SHA256_Transform(context, (sha2_word32*)context->buffer); - } else { - /* The buffer is not yet full */ - bcopy(data, &context->buffer[usedspace], len); - context->bitcount += len << 3; - /* Clean up: */ - usedspace = freespace = 0; - return; - } - } - while (len >= SHA256_BLOCK_LENGTH) { - /* Process as many complete blocks as we can */ - SHA256_Transform(context, (const sha2_word32*)data); - context->bitcount += SHA256_BLOCK_LENGTH << 3; - len -= SHA256_BLOCK_LENGTH; - data += SHA256_BLOCK_LENGTH; - } - if (len > 0) { - /* There's left-overs, so save 'em */ - bcopy(data, context->buffer, len); - context->bitcount += len << 3; - } - /* Clean up: */ - usedspace = freespace = 0; -} - -static void SHA256_Final(sha2_byte digest[], SHA256_CTX* context) { - sha2_word32 *d = (sha2_word32*)digest; - unsigned int usedspace; - - /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; -#if BYTE_ORDER == LITTLE_ENDIAN - /* Convert FROM host byte order */ - REVERSE64(context->bitcount,context->bitcount); -#endif - if (usedspace > 0) { - /* Begin padding with a 1 bit: */ - context->buffer[usedspace++] = 0x80; - - if (usedspace < SHA256_SHORT_BLOCK_LENGTH) { - /* Set-up for the last transform: */ - bzero(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); - } else { - if (usedspace < SHA256_BLOCK_LENGTH) { - bzero(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); - } - /* Do second-to-last transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); - - /* And set-up for the last transform: */ - bzero(context->buffer, SHA256_SHORT_BLOCK_LENGTH); - } - } else { - /* Set-up for the last transform: */ - bzero(context->buffer, SHA256_SHORT_BLOCK_LENGTH); - - /* Begin padding with a 1 bit: */ - *context->buffer = 0x80; - } - /* Set the bit count: */ - *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount; - - /* Final transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); - -#if BYTE_ORDER == LITTLE_ENDIAN - { - /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE32(context->state[j],context->state[j]); - *d++ = context->state[j]; - } - } -#else - bcopy(context->state, d, SHA256_DIGEST_LENGTH); -#endif - } - - /* Clean up state data: */ - bzero(context, sizeof(context)); - usedspace = 0; -} - -static void SHA256(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) -{ - SHA256_CTX context; - - SHA256_Init(&context); - SHA256_Update(&context, data, len); - SHA256_Final(digest,&context); -} - -#endif
\ No newline at end of file |