From 15e8442fff901c61b22c4141cdff337839f9e0b8 Mon Sep 17 00:00:00 2001 From: Jan Altensen Date: Sun, 5 Apr 2020 00:38:26 +0200 Subject: [PATCH] import old mobicore * code taken from https://github.com/LineageOS/android_hardware_samsung_slsi-cm_exynos7420/tree/lineage-15.1/mobicore Change-Id: I4de9a50d7aeeab0956bf33480c2a63b1ebdccdec --- mobicore/Android.mk | 56 +- mobicore/CleanSpec.mk | 61 + mobicore/ClientLib/Android.mk | 163 - mobicore/ClientLib/NOTICE | 30 - .../ClientLib/include/GP/tee_client_error.h | 145 - .../ClientLib/include/GP/tee_client_types.h | 68 - mobicore/ClientLib/include/log.h | 250 - mobicore/ClientLib/include/mcDriverId.h | 68 - mobicore/ClientLib/include/mcRootid.h | 63 - mobicore/ClientLib/include/mcSpid.h | 67 - mobicore/ClientLib/include/mcSuid.h | 50 - mobicore/ClientLib/include/mcUuid.h | 92 - mobicore/ClientLib/include/mcVersionInfo.h | 51 - mobicore/ClientLib/include/proxy_server.h | 46 - mobicore/ClientLib/src/buildTag.h | 34 - mobicore/ClientLib/src/common_client.cpp | 259 - mobicore/ClientLib/src/common_client.h | 76 - mobicore/ClientLib/src/driver_client.cpp | 274 - mobicore/ClientLib/src/driver_client.h | 61 - mobicore/ClientLib/src/iclient.h | 62 - mobicore/ClientLib/src/mc.pb.cpp | 5695 ----------------- mobicore/ClientLib/src/mc.pb.h | 4365 ------------- mobicore/ClientLib/src/mc_client_api.cpp | 794 --- mobicore/ClientLib/src/mc_user.h | 195 - mobicore/ClientLib/src/proxy_client.cpp | 812 --- mobicore/ClientLib/src/proxy_client.h | 61 - mobicore/ClientLib/src/proxy_common.h | 354 - mobicore/ClientLib/src/proxy_server.cpp | 905 --- mobicore/ClientLib/src/tee_client_api.cpp | 972 --- mobicore/Daemon/Android.mk | 145 - mobicore/Daemon/NOTICE | 30 - mobicore/Daemon/src/FSD2.cpp | 691 -- mobicore/Daemon/src/FSD2.h | 60 - mobicore/Daemon/src/MobiCoreDriverCmd.h | 110 - mobicore/Daemon/src/MobiCoreDriverDaemon.cpp | 608 -- mobicore/Daemon/src/MobiCoreDriverDaemon.h | 130 - mobicore/Daemon/src/Registry.cpp | 335 - mobicore/Daemon/src/SecureWorld.cpp | 452 -- mobicore/Daemon/src/SecureWorld.h | 62 - mobicore/Daemon/src/Server.cpp | 229 - mobicore/Daemon/src/buildTag.h | 34 - mobicore/Daemon/src/drSecureFS_Api.h | 112 - mobicore/Daemon/src/mc_admin.h | 99 - mobicore/Daemon/src/mc_user.h | 195 - .../Daemon/src/service_delegation_protocol.h | 103 - mobicore/Daemon/src/sfs_error.h | 96 - mobicore/Daemon/src/sfs_type.h | 142 - mobicore/Daemon/src/sth2ProxyApi.h | 49 - mobicore/{ClientLib => }/MODULE_LICENSE_BSD | 0 mobicore/NOTICE | 25 + mobicore/README.android | 64 + mobicore/TuiService/Android.mk | 55 - mobicore/TuiService/AndroidManifest.xml | 51 - mobicore/TuiService/NOTICE | 30 - mobicore/TuiService/ant.properties | 12 - mobicore/TuiService/build.xml | 97 - .../TuiService/google_certificate.keystore | Bin 2549 -> 0 bytes mobicore/TuiService/jni/tlcTui.cpp | 221 - mobicore/TuiService/jni/tlcTui.h | 43 - mobicore/TuiService/jni/tlcTuiJni.cpp | 267 - mobicore/TuiService/jni/tlcTuiJni.h | 41 - mobicore/TuiService/jni/tui_ioctl.h | 69 - mobicore/TuiService/proguard-project.txt | 20 - mobicore/TuiService/project.properties | 14 - .../res/drawable-hdpi/sym_def_app_icon.png | Bin 9397 -> 0 bytes .../res/drawable-ldpi/sym_def_app_icon.png | Bin 1709 -> 0 bytes .../res/drawable-mdpi/sym_def_app_icon.png | Bin 5237 -> 0 bytes .../res/drawable-xhdpi/sym_def_app_icon.png | Bin 14383 -> 0 bytes .../res/drawable-xxhdpi/sym_def_app_icon.png | Bin 23909 -> 0 bytes .../TuiService/res/layout/activity_tui.xml | 11 - mobicore/TuiService/res/menu/tui_manager.xml | 9 - mobicore/TuiService/res/values-v11/styles.xml | 24 - mobicore/TuiService/res/values-v14/styles.xml | 12 - mobicore/TuiService/res/values/attrs.xml | 14 - mobicore/TuiService/res/values/colors.xml | 28 - mobicore/TuiService/res/values/dimens.xml | 12 - mobicore/TuiService/res/values/strings.xml | 16 - mobicore/TuiService/res/values/styles.xml | 46 - .../com/trustonic/tuiservice/BuildTag.java | 34 - .../com/trustonic/tuiservice/TuiActivity.java | 141 - .../com/trustonic/tuiservice/TuiService.java | 121 - .../tuiservice/TuiServiceAutoStart.java | 69 - .../trustonic/tuiservice/TuiTlcWrapper.java | 200 - mobicore/common/DrSecureStorage/dci.h | 57 + mobicore/common/DrSecureStorage/drError.h | 34 + .../DrSecureStorage/drSecureStorage_Api.h | 101 + .../common/DrSecureStorage/tee_internal_api.h | 1109 ++++ mobicore/common/DrSecureStorage/tlDriverApi.h | 96 + mobicore/common/LogWrapper/log.h | 237 + mobicore/common/MobiCore/inc/DrApi/DrApi.h | 28 + .../common/MobiCore/inc/DrApi/DrApiCommon.h | 84 + .../common/MobiCore/inc/DrApi/DrApiError.h | 67 + .../common/MobiCore/inc/DrApi/DrApiFastCall.h | 117 + .../common/MobiCore/inc/DrApi/DrApiHeap.h | 78 + .../common/MobiCore/inc/DrApi/DrApiIpcMsg.h | 280 + .../common/MobiCore/inc/DrApi/DrApiLogging.h | 71 + .../common/MobiCore/inc/DrApi/DrApiMcSystem.h | 49 + mobicore/common/MobiCore/inc/DrApi/DrApiMm.h | 305 + .../common/MobiCore/inc/DrApi/DrApiThread.h | 265 + mobicore/common/MobiCore/inc/DrApi/version.h | 17 + .../common/MobiCore/inc/FwDrv/DrApiFastCall.h | 117 + mobicore/common/MobiCore/inc/GP/tee_type.h | 143 + .../common/MobiCore/inc/GP/uuid_attestation.h | 60 + .../MobiCore/inc/McLib}/GpTci.h | 16 +- .../MobiCore/inc/McLib/TlApiCryptoMarshal.h | 388 ++ .../MobiCore/inc/McLib/TlApiStorageMarshal.h | 88 + .../MobiCore/inc/McLib/TlApiTuiMarshal.h | 64 + mobicore/common/MobiCore/inc/McLib/mcLibWB.h | 16 + .../common/MobiCore/inc/McLib/mclib_size.h | 18 + .../common/MobiCore/inc/McLib/tplay_marshal.h | 72 + mobicore/common/MobiCore/inc/Mci/mci.h | 97 + mobicore/common/MobiCore/inc/Mci/mcifc.h | 142 + mobicore/common/MobiCore/inc/Mci/mcifcfunc.h | 193 + .../MobiCore/inc}/Mci/mcimcp.h | 174 +- .../MobiCore/inc}/Mci/mcinq.h | 68 +- mobicore/common/MobiCore/inc/Mci/version.h | 37 + .../MobiCore/inc}/TlCm/2.0/cmp.h | 57 +- .../MobiCore/inc}/TlCm/2.0/tlCmApi.h | 57 +- .../MobiCore/inc}/TlCm/3.0/cmp.h | 93 +- .../MobiCore/inc}/TlCm/3.0/cmpMap.h | 69 +- .../MobiCore/inc}/TlCm/3.0/tlCmApi.h | 61 +- .../MobiCore/inc}/TlCm/cmpCommon.h | 132 +- .../MobiCore/inc}/TlCm/tlCmApiCommon.h | 60 +- .../MobiCore/inc}/TlCm/tlCmError.h | 55 +- mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h | 42 + mobicore/common/MobiCore/inc/TlCm/version.h | 44 + .../MobiCore/inc}/mcContainer.h | 60 +- mobicore/common/MobiCore/inc/mcDriverId.h | 49 + .../MobiCore/inc}/mcLoadFormat.h | 140 +- mobicore/common/MobiCore/inc/mcRootid.h | 36 + .../include => common/MobiCore/inc}/mcSo.h | 50 +- mobicore/common/MobiCore/inc/mcSpid.h | 38 + mobicore/common/MobiCore/inc/mcSuid.h | 36 + mobicore/common/MobiCore/inc/mcUuid.h | 57 + .../MobiCore/inc}/mcVersionHelper.h | 66 +- mobicore/common/MobiCore/inc/mcVersionInfo.h | 35 + mobicore/daemon/Android.mk | 115 + mobicore/daemon/Application.mk | 26 + mobicore/daemon/CleanSpec.mk | 61 + mobicore/daemon/ClientLib/Android.mk | 7 + mobicore/daemon/ClientLib/ClientLib.cpp | 1492 +++++ mobicore/daemon/ClientLib/Device.cpp | 264 + mobicore/daemon/ClientLib/Device.h | 173 + .../daemon/ClientLib/GP/tee_client_api.cpp | 835 +++ mobicore/daemon/ClientLib/Session.cpp | 208 + mobicore/daemon/ClientLib/Session.h | 187 + .../ClientLib/public}/GP/tee_client_api.h | 70 +- .../ClientLib/public}/GP/tee_client_api_imp.h | 37 +- .../daemon/ClientLib/public/GP/tee_error.h | 177 + .../public/GP/tee_internal_api_impl.h | 35 + .../daemon/ClientLib/public/GP/tee_type.h | 143 + .../ClientLib/public/GP}/uuid_attestation.h | 40 +- .../ClientLib/public}/MobiCoreDriverApi.h | 137 +- .../public/Windows/t-base_client_api.def | 25 + .../public/Windows/t-base_client_api.sln | 20 + .../public/Windows/t-base_client_api.vcxproj | 109 + mobicore/daemon/Common/Android.mk | 31 + .../CThread.cpp => daemon/Common/CMutex.cpp} | 76 +- mobicore/daemon/Common/CMutex.h | 67 + mobicore/daemon/Common/CSemaphore.cpp | 116 + mobicore/daemon/Common/CSemaphore.h | 74 + mobicore/daemon/Common/CThread.cpp | 166 + .../{Daemon/src => daemon/Common}/CThread.h | 64 +- mobicore/daemon/Common/CWsm.h | 71 + .../src => daemon/Common}/Connection.cpp | 242 +- .../src => daemon/Common}/Connection.h | 68 +- .../Common/McTypes.h} | 19 +- mobicore/daemon/Common/NetlinkConnection.cpp | 295 + mobicore/daemon/Common/NetlinkConnection.h | 223 + mobicore/daemon/Daemon/Android.mk | 19 + mobicore/daemon/Daemon/Device/Android.mk | 25 + .../Daemon/Device/DeviceIrqHandler.cpp} | 31 +- .../Daemon/Device/DeviceIrqHandler.h} | 34 +- .../Daemon/Device/DeviceScheduler.cpp} | 25 +- .../daemon/Daemon/Device/DeviceScheduler.h | 56 + .../daemon/Daemon/Device/MobiCoreDevice.cpp | 931 +++ .../Daemon/Device/NotificationQueue.cpp} | 75 +- .../daemon/Daemon/Device/NotificationQueue.h | 90 + .../daemon/Daemon/Device/Platforms/Android.mk | 15 + .../Device/Platforms/Generic/Android.mk | 16 + .../Platforms/Generic/TrustZoneDevice.cpp | 725 +++ .../Platforms/Generic/TrustZoneDevice.h | 148 + .../daemon/Daemon/Device/TAExitHandler.cpp | 48 + .../Daemon/Device/TAExitHandler.h} | 38 +- .../daemon/Daemon/Device/TrustletSession.cpp | 161 + .../daemon/Daemon/Device/TrustletSession.h | 86 + .../daemon/Daemon/Device/public/ExcDevice.h | 72 + .../Daemon/Device/public/MobiCoreDevice.h | 253 + mobicore/daemon/Daemon/FSD/Android.mk | 17 + mobicore/daemon/Daemon/FSD/FSD.cpp | 584 ++ mobicore/daemon/Daemon/FSD/public/FSD.h | 169 + mobicore/daemon/Daemon/FSD/public/dci.h | 57 + .../Daemon/FSD/public/drSecureStorage_Api.h | 101 + .../daemon/Daemon/MobiCoreDriverDaemon.cpp | 1484 +++++ mobicore/daemon/Daemon/MobiCoreDriverDaemon.h | 271 + mobicore/daemon/Daemon/Server/Android.mk | 17 + .../daemon/Daemon/Server/NetlinkServer.cpp | 287 + mobicore/daemon/Daemon/Server/Server.cpp | 255 + .../Daemon/Server/public}/ConnectionHandler.h | 28 +- .../Daemon/Server/public/NetlinkServer.h | 161 + .../Daemon/Server/public}/Server.h | 77 +- .../daemon/Daemon/public/MobiCoreDriverCmd.h | 292 + .../src => daemon/Daemon/public}/mcVersion.h | 7 +- mobicore/daemon/Kernel/Android.mk | 20 + mobicore/daemon/Kernel/CKMod.cpp | 108 + .../wrapper.h => daemon/Kernel/CKMod.h} | 69 +- .../Kernel/Platforms/Generic/Android.mk | 15 + .../Kernel/Platforms/Generic/CMcKMod.cpp | 561 ++ .../daemon/Kernel/Platforms/Generic/CMcKMod.h | 142 + .../{Daemon => daemon}/MODULE_LICENSE_BSD | 0 mobicore/daemon/NOTICE | 25 + mobicore/daemon/README.android | 64 + mobicore/daemon/Registry/Android.mk | 11 + .../Registry}/PrivateRegistry.cpp | 1027 ++- .../src => daemon/Registry}/PrivateRegistry.h | 99 +- .../Registry/Public}/MobiCoreRegistry.h | 22 +- mobicore/daemon/Registry/Registry.cpp | 398 ++ mobicore/daemon/build.sh | 28 + mobicore/daemon/buildTag.h | 28 + mobicore/include/Public/mc_linux.h | 217 + mobicore/include/Public/version.h | 36 + mobicore/provlib/Android.mk | 16 + mobicore/provlib/Application.mk | 23 + mobicore/provlib/buildTag.h | 28 + .../provlib/inc_private/gdmcdevicebinding.h | 101 + mobicore/provlib/inc_private/gdmcinstance.h | 28 + .../provlib/inc_private/gdmcprovprotocol.h | 127 + mobicore/provlib/inc_private/mobicore.h | 174 + mobicore/provlib/inc_public/gdmcprovlib.h | 424 ++ mobicore/provlib/jni/Android.mk | 37 + mobicore/provlib/src/crc32.c | 49 + mobicore/provlib/src/gdmcdevicebinding.cpp | 533 ++ mobicore/provlib/src/gdmcprovlib.cpp | 408 ++ mobicore/provlib/src/mobicore.c | 294 + mobicore/rootpa/Android.mk | 7 - mobicore/rootpa/Code/Android/app/Android.mk | 6 +- .../Code/Android/app/AndroidManifest.xml | 8 +- mobicore/rootpa/Code/Android/app/NOTICE | 30 - .../rootpa/Code/Android/app/ant.properties | 7 +- mobicore/rootpa/Code/Android/app/build.xml | 52 - .../rootpa/Code/Android/app/jni/Android.mk | 3 +- .../{ => Android/app/jni}/Common/Android.mk | 84 +- .../app/jni/CommonPAWrapper/Android.mk | 57 +- .../app/jni/CommonPAWrapper/CmpBase.cpp | 67 +- .../Android/app/jni/CommonPAWrapper/CmpBase.h | 62 +- .../app/jni/CommonPAWrapper/CmpCommands.cpp | 82 +- .../app/jni/CommonPAWrapper/CmpCommands.h | 62 +- .../app/jni/CommonPAWrapper/CmpResponses.cpp | 64 +- .../app/jni/CommonPAWrapper/CmpResponses.h | 62 +- .../app/jni/CommonPAWrapper/JniHelpers.cpp | 62 +- .../app/jni/CommonPAWrapper/JniHelpers.h | 58 +- .../Android/app/jni/CommonPAWrapper/NOTICE | 30 - .../com_gd_mobicore_pa_jni_CommonPAWrapper.h | 63 +- .../app/jni/CommonPAWrapper/commonwrapper.cpp | 113 +- .../Code/Android/app/jni/McStub/Android.mk | 4 +- .../rootpa/Code/Android/app/jni/McStub/NOTICE | 30 - .../Code/Android/app/res/values/version.xml | 4 +- .../gd/mobicore/pa/jni/CommonPAWrapper.java | 70 +- .../gd/mobicore/pa/service/BaseService.java | 71 +- .../mobicore/pa/service/DeveloperService.java | 60 +- .../src/com/gd/mobicore/pa/service/Log.java | 98 +- .../gd/mobicore/pa/service/OemService.java | 62 +- .../pa/service/ProvisioningService.java | 96 +- mobicore/rootpa/Code/Android/lib/Android.mk | 7 +- mobicore/rootpa/Code/Android/lib/NOTICE | 30 - .../mobicore/pa/ifc/AbstractEnumParcel.java | 58 +- .../com/gd/mobicore/pa/ifc/BooleanResult.aidl | 58 +- .../com/gd/mobicore/pa/ifc/BooleanResult.java | 58 +- .../com/gd/mobicore/pa/ifc/CmpCommand.aidl | 58 +- .../com/gd/mobicore/pa/ifc/CmpCommand.java | 82 +- .../src/com/gd/mobicore/pa/ifc/CmpMsg.java | 106 +- .../com/gd/mobicore/pa/ifc/CmpResponse.aidl | 58 +- .../com/gd/mobicore/pa/ifc/CmpResponse.java | 82 +- .../com/gd/mobicore/pa/ifc/CommandResult.aidl | 58 +- .../com/gd/mobicore/pa/ifc/CommandResult.java | 58 +- .../com/gd/mobicore/pa/ifc/IfcVersion.java | 63 +- .../lib/src/com/gd/mobicore/pa/ifc/README.txt | 28 + .../mobicore/pa/ifc/RootPADeveloperIfc.aidl | 106 +- .../com/gd/mobicore/pa/ifc/RootPAOemIfc.aidl | 68 +- .../pa/ifc/RootPAProvisioningIntents.java | 58 +- .../gd/mobicore/pa/ifc/RootPAServiceIfc.aidl | 76 +- .../gd/mobicore/pa/ifc/SPContainerState.java | 58 +- .../pa/ifc/SPContainerStateParcel.aidl | 58 +- .../pa/ifc/SPContainerStateParcel.java | 58 +- .../mobicore/pa/ifc/SPContainerStructure.aidl | 58 +- .../mobicore/pa/ifc/SPContainerStructure.java | 58 +- .../lib/src/com/gd/mobicore/pa/ifc/SPID.aidl | 58 +- .../lib/src/com/gd/mobicore/pa/ifc/SPID.java | 58 +- .../lib/src/com/gd/mobicore/pa/ifc/SUID.aidl | 58 +- .../lib/src/com/gd/mobicore/pa/ifc/SUID.java | 58 +- .../gd/mobicore/pa/ifc/TrustletContainer.aidl | 58 +- .../gd/mobicore/pa/ifc/TrustletContainer.java | 58 +- .../pa/ifc/TrustletContainerState.java | 58 +- .../pa/ifc/TrustletContainerStateParcel.aidl | 58 +- .../pa/ifc/TrustletContainerStateParcel.java | 58 +- .../src/com/gd/mobicore/pa/ifc/Version.aidl | 58 +- .../src/com/gd/mobicore/pa/ifc/Version.java | 60 +- mobicore/rootpa/Code/CMakeLists.txt | 43 - mobicore/rootpa/Code/Common/NOTICE | 30 - mobicore/rootpa/Code/Common/base64.c | 141 +- mobicore/rootpa/Code/Common/base64.h | 58 +- mobicore/rootpa/Code/Common/cacerts.h | 115 +- mobicore/rootpa/Code/Common/commandhandler.c | 210 +- mobicore/rootpa/Code/Common/contentmanager.c | 113 +- mobicore/rootpa/Code/Common/contentmanager.h | 58 +- .../Code/Common/enrollmentservicexmlschema.h | 60 +- mobicore/rootpa/Code/Common/include/logging.h | 114 +- .../Code/Common/include/provisioningagent.h | 73 +- mobicore/rootpa/Code/Common/include/rootpa.h | 62 +- .../rootpa/Code/Common/include/rootpaErrors.h | 58 +- mobicore/rootpa/Code/Common/include/version.h | 62 +- mobicore/rootpa/Code/Common/pacmp3.c | 80 +- mobicore/rootpa/Code/Common/pacmp3.h | 58 +- mobicore/rootpa/Code/Common/pacmtl.c | 70 +- mobicore/rootpa/Code/Common/pacmtl.h | 58 +- .../rootpa/Code/Common/provisioningengine.c | 153 +- .../rootpa/Code/Common/provisioningengine.h | 58 +- mobicore/rootpa/Code/Common/registry.c | 93 +- mobicore/rootpa/Code/Common/registry.h | 61 +- mobicore/rootpa/Code/Common/seclient.c | 259 +- mobicore/rootpa/Code/Common/seclient.h | 62 +- mobicore/rootpa/Code/Common/tools.h | 67 +- mobicore/rootpa/Code/Common/trustletchannel.c | 176 +- mobicore/rootpa/Code/Common/trustletchannel.h | 66 +- .../rootpa/Code/Common/xmlmessagehandler.c | 275 +- .../rootpa/Code/Common/xmlmessagehandler.h | 84 +- mobicore/tlcm/Android.mk | 11 - mobicore/tlcm/NOTICE | 30 - mobicore/tlcm/version.md5 | 1 - 329 files changed, 24466 insertions(+), 26831 deletions(-) create mode 100644 mobicore/CleanSpec.mk delete mode 100644 mobicore/ClientLib/Android.mk delete mode 100644 mobicore/ClientLib/NOTICE delete mode 100644 mobicore/ClientLib/include/GP/tee_client_error.h delete mode 100644 mobicore/ClientLib/include/GP/tee_client_types.h delete mode 100644 mobicore/ClientLib/include/log.h delete mode 100644 mobicore/ClientLib/include/mcDriverId.h delete mode 100644 mobicore/ClientLib/include/mcRootid.h delete mode 100644 mobicore/ClientLib/include/mcSpid.h delete mode 100644 mobicore/ClientLib/include/mcSuid.h delete mode 100644 mobicore/ClientLib/include/mcUuid.h delete mode 100644 mobicore/ClientLib/include/mcVersionInfo.h delete mode 100644 mobicore/ClientLib/include/proxy_server.h delete mode 100644 mobicore/ClientLib/src/buildTag.h delete mode 100644 mobicore/ClientLib/src/common_client.cpp delete mode 100644 mobicore/ClientLib/src/common_client.h delete mode 100644 mobicore/ClientLib/src/driver_client.cpp delete mode 100644 mobicore/ClientLib/src/driver_client.h delete mode 100644 mobicore/ClientLib/src/iclient.h delete mode 100644 mobicore/ClientLib/src/mc.pb.cpp delete mode 100644 mobicore/ClientLib/src/mc.pb.h delete mode 100644 mobicore/ClientLib/src/mc_client_api.cpp delete mode 100644 mobicore/ClientLib/src/mc_user.h delete mode 100644 mobicore/ClientLib/src/proxy_client.cpp delete mode 100644 mobicore/ClientLib/src/proxy_client.h delete mode 100644 mobicore/ClientLib/src/proxy_common.h delete mode 100644 mobicore/ClientLib/src/proxy_server.cpp delete mode 100644 mobicore/ClientLib/src/tee_client_api.cpp delete mode 100644 mobicore/Daemon/Android.mk delete mode 100644 mobicore/Daemon/NOTICE delete mode 100644 mobicore/Daemon/src/FSD2.cpp delete mode 100644 mobicore/Daemon/src/FSD2.h delete mode 100644 mobicore/Daemon/src/MobiCoreDriverCmd.h delete mode 100644 mobicore/Daemon/src/MobiCoreDriverDaemon.cpp delete mode 100644 mobicore/Daemon/src/MobiCoreDriverDaemon.h delete mode 100644 mobicore/Daemon/src/Registry.cpp delete mode 100644 mobicore/Daemon/src/SecureWorld.cpp delete mode 100644 mobicore/Daemon/src/SecureWorld.h delete mode 100644 mobicore/Daemon/src/Server.cpp delete mode 100644 mobicore/Daemon/src/buildTag.h delete mode 100644 mobicore/Daemon/src/drSecureFS_Api.h delete mode 100644 mobicore/Daemon/src/mc_admin.h delete mode 100644 mobicore/Daemon/src/mc_user.h delete mode 100644 mobicore/Daemon/src/service_delegation_protocol.h delete mode 100644 mobicore/Daemon/src/sfs_error.h delete mode 100644 mobicore/Daemon/src/sfs_type.h delete mode 100644 mobicore/Daemon/src/sth2ProxyApi.h rename mobicore/{ClientLib => }/MODULE_LICENSE_BSD (100%) create mode 100644 mobicore/NOTICE create mode 100644 mobicore/README.android delete mode 100644 mobicore/TuiService/Android.mk delete mode 100644 mobicore/TuiService/AndroidManifest.xml delete mode 100644 mobicore/TuiService/NOTICE delete mode 100644 mobicore/TuiService/ant.properties delete mode 100644 mobicore/TuiService/build.xml delete mode 100644 mobicore/TuiService/google_certificate.keystore delete mode 100644 mobicore/TuiService/jni/tlcTui.cpp delete mode 100644 mobicore/TuiService/jni/tlcTui.h delete mode 100644 mobicore/TuiService/jni/tlcTuiJni.cpp delete mode 100644 mobicore/TuiService/jni/tlcTuiJni.h delete mode 100644 mobicore/TuiService/jni/tui_ioctl.h delete mode 100644 mobicore/TuiService/proguard-project.txt delete mode 100644 mobicore/TuiService/project.properties delete mode 100644 mobicore/TuiService/res/drawable-hdpi/sym_def_app_icon.png delete mode 100644 mobicore/TuiService/res/drawable-ldpi/sym_def_app_icon.png delete mode 100644 mobicore/TuiService/res/drawable-mdpi/sym_def_app_icon.png delete mode 100644 mobicore/TuiService/res/drawable-xhdpi/sym_def_app_icon.png delete mode 100644 mobicore/TuiService/res/drawable-xxhdpi/sym_def_app_icon.png delete mode 100644 mobicore/TuiService/res/layout/activity_tui.xml delete mode 100644 mobicore/TuiService/res/menu/tui_manager.xml delete mode 100644 mobicore/TuiService/res/values-v11/styles.xml delete mode 100644 mobicore/TuiService/res/values-v14/styles.xml delete mode 100644 mobicore/TuiService/res/values/attrs.xml delete mode 100644 mobicore/TuiService/res/values/colors.xml delete mode 100644 mobicore/TuiService/res/values/dimens.xml delete mode 100644 mobicore/TuiService/res/values/strings.xml delete mode 100644 mobicore/TuiService/res/values/styles.xml delete mode 100644 mobicore/TuiService/src/com/trustonic/tuiservice/BuildTag.java delete mode 100644 mobicore/TuiService/src/com/trustonic/tuiservice/TuiActivity.java delete mode 100644 mobicore/TuiService/src/com/trustonic/tuiservice/TuiService.java delete mode 100644 mobicore/TuiService/src/com/trustonic/tuiservice/TuiServiceAutoStart.java delete mode 100644 mobicore/TuiService/src/com/trustonic/tuiservice/TuiTlcWrapper.java create mode 100644 mobicore/common/DrSecureStorage/dci.h create mode 100644 mobicore/common/DrSecureStorage/drError.h create mode 100644 mobicore/common/DrSecureStorage/drSecureStorage_Api.h create mode 100644 mobicore/common/DrSecureStorage/tee_internal_api.h create mode 100644 mobicore/common/DrSecureStorage/tlDriverApi.h create mode 100644 mobicore/common/LogWrapper/log.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApi.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiCommon.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiError.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiFastCall.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiHeap.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiIpcMsg.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiLogging.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiMcSystem.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiMm.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/DrApiThread.h create mode 100644 mobicore/common/MobiCore/inc/DrApi/version.h create mode 100644 mobicore/common/MobiCore/inc/FwDrv/DrApiFastCall.h create mode 100644 mobicore/common/MobiCore/inc/GP/tee_type.h create mode 100644 mobicore/common/MobiCore/inc/GP/uuid_attestation.h rename mobicore/{ClientLib/include => common/MobiCore/inc/McLib}/GpTci.h (86%) create mode 100644 mobicore/common/MobiCore/inc/McLib/TlApiCryptoMarshal.h create mode 100644 mobicore/common/MobiCore/inc/McLib/TlApiStorageMarshal.h create mode 100644 mobicore/common/MobiCore/inc/McLib/TlApiTuiMarshal.h create mode 100644 mobicore/common/MobiCore/inc/McLib/mcLibWB.h create mode 100644 mobicore/common/MobiCore/inc/McLib/mclib_size.h create mode 100644 mobicore/common/MobiCore/inc/McLib/tplay_marshal.h create mode 100644 mobicore/common/MobiCore/inc/Mci/mci.h create mode 100644 mobicore/common/MobiCore/inc/Mci/mcifc.h create mode 100644 mobicore/common/MobiCore/inc/Mci/mcifcfunc.h rename mobicore/{ClientLib/include => common/MobiCore/inc}/Mci/mcimcp.h (72%) rename mobicore/{ClientLib/include => common/MobiCore/inc}/Mci/mcinq.h (54%) create mode 100644 mobicore/common/MobiCore/inc/Mci/version.h rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/2.0/cmp.h (97%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/2.0/tlCmApi.h (87%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/3.0/cmp.h (92%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/3.0/cmpMap.h (97%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/3.0/tlCmApi.h (85%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/cmpCommon.h (65%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/tlCmApiCommon.h (67%) rename mobicore/{tlcm => common/MobiCore/inc}/TlCm/tlCmError.h (71%) create mode 100644 mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h create mode 100644 mobicore/common/MobiCore/inc/TlCm/version.h rename mobicore/{ClientLib/include => common/MobiCore/inc}/mcContainer.h (80%) create mode 100644 mobicore/common/MobiCore/inc/mcDriverId.h rename mobicore/{ClientLib/include => common/MobiCore/inc}/mcLoadFormat.h (64%) create mode 100644 mobicore/common/MobiCore/inc/mcRootid.h rename mobicore/{ClientLib/include => common/MobiCore/inc}/mcSo.h (80%) create mode 100644 mobicore/common/MobiCore/inc/mcSpid.h create mode 100644 mobicore/common/MobiCore/inc/mcSuid.h create mode 100644 mobicore/common/MobiCore/inc/mcUuid.h rename mobicore/{ClientLib/include => common/MobiCore/inc}/mcVersionHelper.h (79%) create mode 100644 mobicore/common/MobiCore/inc/mcVersionInfo.h create mode 100644 mobicore/daemon/Android.mk create mode 100644 mobicore/daemon/Application.mk create mode 100644 mobicore/daemon/CleanSpec.mk create mode 100644 mobicore/daemon/ClientLib/Android.mk create mode 100644 mobicore/daemon/ClientLib/ClientLib.cpp create mode 100644 mobicore/daemon/ClientLib/Device.cpp create mode 100644 mobicore/daemon/ClientLib/Device.h create mode 100644 mobicore/daemon/ClientLib/GP/tee_client_api.cpp create mode 100644 mobicore/daemon/ClientLib/Session.cpp create mode 100644 mobicore/daemon/ClientLib/Session.h rename mobicore/{ClientLib/include => daemon/ClientLib/public}/GP/tee_client_api.h (75%) rename mobicore/{ClientLib/include => daemon/ClientLib/public}/GP/tee_client_api_imp.h (79%) create mode 100644 mobicore/daemon/ClientLib/public/GP/tee_error.h create mode 100644 mobicore/daemon/ClientLib/public/GP/tee_internal_api_impl.h create mode 100644 mobicore/daemon/ClientLib/public/GP/tee_type.h rename mobicore/{ClientLib/include => daemon/ClientLib/public/GP}/uuid_attestation.h (50%) rename mobicore/{ClientLib/include => daemon/ClientLib/public}/MobiCoreDriverApi.h (89%) create mode 100644 mobicore/daemon/ClientLib/public/Windows/t-base_client_api.def create mode 100644 mobicore/daemon/ClientLib/public/Windows/t-base_client_api.sln create mode 100644 mobicore/daemon/ClientLib/public/Windows/t-base_client_api.vcxproj create mode 100644 mobicore/daemon/Common/Android.mk rename mobicore/{Daemon/src/CThread.cpp => daemon/Common/CMutex.cpp} (65%) create mode 100644 mobicore/daemon/Common/CMutex.h create mode 100644 mobicore/daemon/Common/CSemaphore.cpp create mode 100644 mobicore/daemon/Common/CSemaphore.h create mode 100644 mobicore/daemon/Common/CThread.cpp rename mobicore/{Daemon/src => daemon/Common}/CThread.h (71%) create mode 100644 mobicore/daemon/Common/CWsm.h rename mobicore/{Daemon/src => daemon/Common}/Connection.cpp (52%) rename mobicore/{Daemon/src => daemon/Common}/Connection.h (65%) rename mobicore/{TuiService/src/com/trustonic/tuiapi/TUI_EventData.java => daemon/Common/McTypes.h} (89%) create mode 100644 mobicore/daemon/Common/NetlinkConnection.cpp create mode 100644 mobicore/daemon/Common/NetlinkConnection.h create mode 100644 mobicore/daemon/Daemon/Android.mk create mode 100644 mobicore/daemon/Daemon/Device/Android.mk rename mobicore/{TuiService/src/com/trustonic/tuiapi/TUI_EventType.java => daemon/Daemon/Device/DeviceIrqHandler.cpp} (84%) rename mobicore/{tlcm/TlCm/version.h => daemon/Daemon/Device/DeviceIrqHandler.h} (83%) rename mobicore/{tlcm/TlCm/tlCmUuid.h => daemon/Daemon/Device/DeviceScheduler.cpp} (86%) create mode 100644 mobicore/daemon/Daemon/Device/DeviceScheduler.h create mode 100644 mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp rename mobicore/{TuiService/src/com/trustonic/util/tLog.java => daemon/Daemon/Device/NotificationQueue.cpp} (57%) create mode 100644 mobicore/daemon/Daemon/Device/NotificationQueue.h create mode 100644 mobicore/daemon/Daemon/Device/Platforms/Android.mk create mode 100644 mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk create mode 100644 mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.cpp create mode 100644 mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.h create mode 100644 mobicore/daemon/Daemon/Device/TAExitHandler.cpp rename mobicore/{TuiService/src/com/trustonic/tuiapi/TUI_Event.java => daemon/Daemon/Device/TAExitHandler.h} (79%) create mode 100644 mobicore/daemon/Daemon/Device/TrustletSession.cpp create mode 100644 mobicore/daemon/Daemon/Device/TrustletSession.h create mode 100644 mobicore/daemon/Daemon/Device/public/ExcDevice.h create mode 100644 mobicore/daemon/Daemon/Device/public/MobiCoreDevice.h create mode 100644 mobicore/daemon/Daemon/FSD/Android.mk create mode 100644 mobicore/daemon/Daemon/FSD/FSD.cpp create mode 100644 mobicore/daemon/Daemon/FSD/public/FSD.h create mode 100644 mobicore/daemon/Daemon/FSD/public/dci.h create mode 100644 mobicore/daemon/Daemon/FSD/public/drSecureStorage_Api.h create mode 100644 mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp create mode 100644 mobicore/daemon/Daemon/MobiCoreDriverDaemon.h create mode 100644 mobicore/daemon/Daemon/Server/Android.mk create mode 100644 mobicore/daemon/Daemon/Server/NetlinkServer.cpp create mode 100644 mobicore/daemon/Daemon/Server/Server.cpp rename mobicore/{Daemon/src => daemon/Daemon/Server/public}/ConnectionHandler.h (80%) create mode 100644 mobicore/daemon/Daemon/Server/public/NetlinkServer.h rename mobicore/{Daemon/src => daemon/Daemon/Server/public}/Server.h (62%) create mode 100644 mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h rename mobicore/{Daemon/src => daemon/Daemon/public}/mcVersion.h (95%) create mode 100644 mobicore/daemon/Kernel/Android.mk create mode 100644 mobicore/daemon/Kernel/CKMod.cpp rename mobicore/{rootpa/Code/Common/include/wrapper.h => daemon/Kernel/CKMod.h} (72%) create mode 100644 mobicore/daemon/Kernel/Platforms/Generic/Android.mk create mode 100644 mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.cpp create mode 100644 mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.h rename mobicore/{Daemon => daemon}/MODULE_LICENSE_BSD (100%) create mode 100644 mobicore/daemon/NOTICE create mode 100644 mobicore/daemon/README.android create mode 100644 mobicore/daemon/Registry/Android.mk rename mobicore/{Daemon/src => daemon/Registry}/PrivateRegistry.cpp (53%) rename mobicore/{Daemon/src => daemon/Registry}/PrivateRegistry.h (74%) rename mobicore/{Daemon/include => daemon/Registry/Public}/MobiCoreRegistry.h (94%) create mode 100644 mobicore/daemon/Registry/Registry.cpp create mode 100644 mobicore/daemon/build.sh create mode 100644 mobicore/daemon/buildTag.h create mode 100644 mobicore/include/Public/mc_linux.h create mode 100644 mobicore/include/Public/version.h create mode 100644 mobicore/provlib/Android.mk create mode 100644 mobicore/provlib/Application.mk create mode 100644 mobicore/provlib/buildTag.h create mode 100644 mobicore/provlib/inc_private/gdmcdevicebinding.h create mode 100644 mobicore/provlib/inc_private/gdmcinstance.h create mode 100644 mobicore/provlib/inc_private/gdmcprovprotocol.h create mode 100644 mobicore/provlib/inc_private/mobicore.h create mode 100644 mobicore/provlib/inc_public/gdmcprovlib.h create mode 100644 mobicore/provlib/jni/Android.mk create mode 100644 mobicore/provlib/src/crc32.c create mode 100644 mobicore/provlib/src/gdmcdevicebinding.cpp create mode 100644 mobicore/provlib/src/gdmcprovlib.cpp create mode 100644 mobicore/provlib/src/mobicore.c delete mode 100644 mobicore/rootpa/Android.mk delete mode 100644 mobicore/rootpa/Code/Android/app/NOTICE rename mobicore/rootpa/Code/{ => Android/app/jni}/Common/Android.mk (59%) delete mode 100644 mobicore/rootpa/Code/Android/app/jni/CommonPAWrapper/NOTICE delete mode 100644 mobicore/rootpa/Code/Android/app/jni/McStub/NOTICE delete mode 100644 mobicore/rootpa/Code/Android/lib/NOTICE create mode 100644 mobicore/rootpa/Code/Android/lib/src/com/gd/mobicore/pa/ifc/README.txt delete mode 100644 mobicore/rootpa/Code/CMakeLists.txt delete mode 100644 mobicore/rootpa/Code/Common/NOTICE delete mode 100644 mobicore/tlcm/Android.mk delete mode 100644 mobicore/tlcm/NOTICE delete mode 100644 mobicore/tlcm/version.md5 diff --git a/mobicore/Android.mk b/mobicore/Android.mk index bd576fc..a77daac 100644 --- a/mobicore/Android.mk +++ b/mobicore/Android.mk @@ -1,10 +1,46 @@ -# Some things are specific to Android 6.0 and later (use stlport absence as indicator) -ifneq ($(wildcard external/stlport/libstlport.mk),) -# Up to Lollipop -TRUSTONIC_ANDROID_LEGACY_SUPPORT = yes -else -# Since Marshmallow -TRUSTONIC_ANDROID_LEGACY_SUPPORT = -endif - -include $(call all-subdir-makefiles) +# ============================================================================= +# +# Makefile pointing to all makefiles within the project. +# +# ============================================================================= +MOBICORE_PROJECT_PATH := $(call my-dir) +# Setup common variables +COMP_PATH_MobiCore := $(MOBICORE_PROJECT_PATH)/common/MobiCore +COMP_PATH_MobiCoreDriverMod := $(MOBICORE_PROJECT_PATH)/include + + +# Application wide Cflags +GLOBAL_INCLUDES := bionic \ + $(COMP_PATH_MobiCore)/inc \ + $(COMP_PATH_MobiCoreDriverMod)/Public \ + $(COMP_PATH_MobiCore)/inc/TlCm \ + $(COMP_PATH_MobiCore)/inc/GP \ + $(MOBICORE_PROJECT_PATH)/common/DrSecureStorage + +LOCAL_CXX_STL := libstlport + +# Include the Daemon +include $(MOBICORE_PROJECT_PATH)/daemon/Android.mk + +MC_INCLUDE_DIR := \ + $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr/include \ + $(COMP_PATH_MobiCore)/inc \ + $(COMP_PATH_MobiCore)/inc/GP \ + $(COMP_PATH_MobiCore)/inc/TlCm \ + $(COMP_PATH_MobiCore)/inc/TlCm/2.0 \ + $(MOBICORE_PROJECT_PATH)/daemon/ClientLib/public \ + $(MOBICORE_PROJECT_PATH)/daemon/Registry/Public + +MC_DEBUG := _DEBUG +SYSTEM_LIB_DIR=/system/lib +GDM_PROVLIB_SHARED_LIBS=libMcClient +# Include the provisioning lib +include $(MOBICORE_PROJECT_PATH)/provlib/Android.mk + +LOCAL_ADDITIONAL_DEPENDENCIES += \ + $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr + +MOBICORE_DIR_INC := $(MC_INCLUDE_DIR) $(MOBICORE_PROJECT_PATH)/common/curl/include +include $(MOBICORE_PROJECT_PATH)/rootpa/Code/Android/app/jni/Android.mk +include $(MOBICORE_PROJECT_PATH)/rootpa/Code/Android/lib/Android.mk +include $(MOBICORE_PROJECT_PATH)/rootpa/Code/Android/app/Android.mk diff --git a/mobicore/CleanSpec.mk b/mobicore/CleanSpec.mk new file mode 100644 index 0000000..7dd6f6c --- /dev/null +++ b/mobicore/CleanSpec.mk @@ -0,0 +1,61 @@ +# Copyright (C) 2007 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# If you don't need to do a full clean build but would like to touch +# a file or delete some intermediate files, add a clean step to the end +# of the list. These steps will only be run once, if they haven't been +# run before. +# +# E.g.: +# $(call add-clean-step, touch -c external/sqlite/sqlite3.h) +# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates) +# +# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with +# files that are missing or have been moved. +# +# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory. +# Use $(OUT_DIR) to refer to the "out" directory. +# +# If you need to re-do something that's already mentioned, just copy +# the command and add it to the bottom of the list. E.g., if a change +# that you made last week required touching a file and a change you +# made today requires touching the same file, just copy the old +# touch step and add it to the end of the list. +# +# ************************************************ +# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST +# ************************************************ + +# For example: +#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates) +#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates) +#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libssl_static_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libcrypto_static_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/*ssl*_intermediates $(PRODUCT_OUT)/obj/*/libssl_*intermediates $(PRODUCT_OUT)/obj/*/libcrypto_*intermediates) + +# ************************************************ +# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST +# ************************************************ diff --git a/mobicore/ClientLib/Android.mk b/mobicore/ClientLib/Android.mk deleted file mode 100644 index f98e5b8..0000000 --- a/mobicore/ClientLib/Android.mk +++ /dev/null @@ -1,163 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -ifndef TRUSTONIC_ANDROID_LEGACY_SUPPORT - -# Proxy server lib - -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcProxy -LOCAL_MODULE_TAGS := eng - -LOCAL_CFLAGS := -fvisibility=hidden -LOCAL_CFLAGS += -DTBASE_API_LEVEL=5 -LOCAL_CFLAGS += -Wall -Wextra -LOCAL_CFLAGS += -std=c++11 -LOCAL_CFLAGS += -DLOG_ANDROID -LOCAL_CFLAGS += -DGOOGLE_PROTOBUF_NO_RTTI - -LOCAL_C_INCLUDES := \ - $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/include/GP \ - external/protobuf/src - -ifeq ($(APP_PROJECT_PATH),) -LOCAL_SHARED_LIBRARIES := \ - liblog \ - libprotobuf-cpp-lite -else -LOCAL_C_INCLUDES += \ - ${COMP_PATH_AndroidProtoBuf}/Bin/host/include - -LOCAL_STATIC_LIBRARIES := \ - libprotobuf-cpp-lite -endif - -LOCAL_SRC_FILES := \ - src/driver_client.cpp \ - src/proxy_server.cpp \ - src/mc.pb.cpp - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES) -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_EXPORT_C_INCLUDES) - -include $(BUILD_STATIC_LIBRARY) - -endif # !TRUSTONIC_ANDROID_LEGACY_SUPPORT - -# Client lib - -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcClient -LOCAL_MODULE_TAGS := eng - -LOCAL_CFLAGS := -fvisibility=hidden -LOCAL_CFLAGS += -DTBASE_API_LEVEL=5 -LOCAL_CFLAGS += -Wall -Wextra -LOCAL_CFLAGS += -std=c++11 -LOCAL_CFLAGS += -DLOG_ANDROID -ifndef TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_CFLAGS += -DGOOGLE_PROTOBUF_NO_RTTI -else # !TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_CFLAGS += -DWITHOUT_PROXY -endif # TRUSTONIC_ANDROID_LEGACY_SUPPORT - -LOCAL_C_INCLUDES := \ - $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/include/GP - -ifeq ($(APP_PROJECT_PATH),) -LOCAL_SHARED_LIBRARIES := \ - liblog - -ifdef TRUSTONIC_ANDROID_LEGACY_SUPPORT -include external/stlport/libstlport.mk - -LOCAL_C_INCLUDES += \ - external/stlport/stlport - -LOCAL_SHARED_LIBRARIES += \ - libstlport -else # TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_C_INCLUDES += \ - external/protobuf/src - -LOCAL_SHARED_LIBRARIES += \ - libprotobuf-cpp-lite -endif # !TRUSTONIC_ANDROID_LEGACY_SUPPORT -else # !NDK -LOCAL_LDLIBS := -llog - -LOCAL_CFLAGS += -static-libstdc++ - -LOCAL_C_INCLUDES += \ - ${COMP_PATH_AndroidProtoBuf}/Bin/host/include - -LOCAL_STATIC_LIBRARIES := \ - libprotobuf-cpp-lite -endif # NDK - -LOCAL_SRC_FILES := \ - src/common_client.cpp \ - src/driver_client.cpp \ - src/mc_client_api.cpp \ - src/tee_client_api.cpp - -ifndef TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_SRC_FILES += \ - src/proxy_client.cpp \ - src/mc.pb.cpp -endif # !TRUSTONIC_ANDROID_LEGACY_SUPPORT - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES) -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_EXPORT_C_INCLUDES) - -include $(BUILD_SHARED_LIBRARY) - -# Static version of the client lib for recovery - -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcClient_static -LOCAL_MODULE_TAGS := eng - -LOCAL_CFLAGS := -fvisibility=hidden -LOCAL_CFLAGS += -DTBASE_API_LEVEL=5 -LOCAL_CFLAGS += -Wall -Wextra -LOCAL_CFLAGS += -std=c++11 -LOCAL_CFLAGS += -DLOG_ANDROID -LOCAL_CFLAGS += -DWITHOUT_PROXY - -LOCAL_C_INCLUDES := \ - $(LOCAL_PATH)/include \ - $(LOCAL_PATH)/include/GP - -ifdef TRUSTONIC_ANDROID_LEGACY_SUPPORT -include external/stlport/libstlport.mk - -LOCAL_C_INCLUDES += \ - external/stlport/stlport - -LOCAL_SHARED_LIBRARIES += \ - libstlport -endif # TRUSTONIC_ANDROID_LEGACY_SUPPORT - -LOCAL_SRC_FILES := \ - src/common_client.cpp \ - src/driver_client.cpp \ - src/mc_client_api.cpp \ - src/tee_client_api.cpp - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/include/GP -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_EXPORT_C_INCLUDES) - -include $(BUILD_STATIC_LIBRARY) - -# ============================================================================= - -# adding the root folder to the search path appears to make absolute paths -# work for import-module - lets see how long this works and what surprises -# future developers get from this. -$(call import-add-path,/) -$(call import-module,$(COMP_PATH_AndroidProtoBuf)) diff --git a/mobicore/ClientLib/NOTICE b/mobicore/ClientLib/NOTICE deleted file mode 100644 index 627167a..0000000 --- a/mobicore/ClientLib/NOTICE +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ diff --git a/mobicore/ClientLib/include/GP/tee_client_error.h b/mobicore/ClientLib/include/GP/tee_client_error.h deleted file mode 100644 index 8aa4fbf..0000000 --- a/mobicore/ClientLib/include/GP/tee_client_error.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __TEE_CLIENT_ERROR_H__ -#define __TEE_CLIENT_ERROR_H__ - -#define TEEC_SUCCESS ((TEEC_Result)0x00000000) - -/** - * Generic error code : Generic error - **/ -#define TEEC_ERROR_GENERIC ((TEEC_Result)0xFFFF0000) - -/** - * Generic error code : The underlying security system denies the access to the - * object - **/ -#define TEEC_ERROR_ACCESS_DENIED ((TEEC_Result)0xFFFF0001) - -/** - * Generic error code : The pending operation is cancelled. - **/ -#define TEEC_ERROR_CANCEL ((TEEC_Result)0xFFFF0002) - -/** - * Generic error code : The underlying system detects a conflict - **/ -#define TEEC_ERROR_ACCESS_CONFLICT ((TEEC_Result)0xFFFF0003) - -/** - * Generic error code : Too much data for the operation or some data remain - * unprocessed by the operation. - **/ -#define TEEC_ERROR_EXCESS_DATA ((TEEC_Result)0xFFFF0004) - -/** - * Generic error code : Error of data format - **/ -#define TEEC_ERROR_BAD_FORMAT ((TEEC_Result)0xFFFF0005) - -/** - * Generic error code : The specified parameters are invalid - **/ -#define TEEC_ERROR_BAD_PARAMETERS ((TEEC_Result)0xFFFF0006) - -/** - * Generic error code : Illegal state for the operation. - **/ -#define TEEC_ERROR_BAD_STATE ((TEEC_Result)0xFFFF0007) - -/** - * Generic error code : The item is not found - **/ -#define TEEC_ERROR_ITEM_NOT_FOUND ((TEEC_Result)0xFFFF0008) - -/** - * Generic error code : The specified operation is not implemented - **/ -#define TEEC_ERROR_NOT_IMPLEMENTED ((TEEC_Result)0xFFFF0009) - -/** - * Generic error code : The specified operation is not supported - **/ -#define TEEC_ERROR_NOT_SUPPORTED ((TEEC_Result)0xFFFF000A) - -/** - * Generic error code : Insufficient data is available for the operation. - **/ -#define TEEC_ERROR_NO_DATA ((TEEC_Result)0xFFFF000B) - -/** - * Generic error code : Not enough memory to perform the operation - **/ -#define TEEC_ERROR_OUT_OF_MEMORY ((TEEC_Result)0xFFFF000C) - -/** - * Generic error code : The service is currently unable to handle the request; - * try later - **/ -#define TEEC_ERROR_BUSY ((TEEC_Result)0xFFFF000D) - -/** - * Generic communication error - **/ -#define TEEC_ERROR_COMMUNICATION ((TEEC_Result)0xFFFF000E) - -/** - * Generic error code : security violation - **/ -#define TEEC_ERROR_SECURITY ((TEEC_Result)0xFFFF000F) - -/** - * Generic error code : the buffer is too short - **/ -#define TEEC_ERROR_SHORT_BUFFER ((TEEC_Result)0xFFFF0010) - -/** - * Error of communication: The target of the connection is dead - **/ -#define TEEC_ERROR_TARGET_DEAD ((TEEC_Result)0xFFFF3024) - -/** - * File system error code: not enough space to complete the operation. - **/ -#define TEEC_ERROR_STORAGE_NO_SPACE ((TEEC_Result)0xFFFF3041) - -/*------------------------------------------------------------------------------ - Implementation-specific errors -------------------------------------------------------------------------------*/ -#define TEEC_TBASE_ERROR_STORAGE_ITEM_EXISTS ((TEEC_Result)0x80000000) -#define TEEC_TBASE_ERROR_STORAGE_CORRUPTED ((TEEC_Result)0x80000001) -#define TEEC_TBASE_ERROR_STORAGE_UNREACHABLE ((TEEC_Result)0x80000002) -#define TEEC_TBASE_ERROR_NO_MORE_HANDLES ((TEEC_Result)0x80000003) -#define TEEC_TBASE_ERROR_ITEM_EXISTS ((TEEC_Result)0x80000004) - -#endif /* __TEE_CLIENT_ERROR_H__ */ - diff --git a/mobicore/ClientLib/include/GP/tee_client_types.h b/mobicore/ClientLib/include/GP/tee_client_types.h deleted file mode 100644 index 6642592..0000000 --- a/mobicore/ClientLib/include/GP/tee_client_types.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __TEE_CLIENT_TYPES_H__ -#define __TEE_CLIENT_TYPES_H__ - -#include - -#include -#include -#include - -#ifndef NULL -# ifdef __cplusplus -# define NULL 0 -# else -# define NULL ((void *)0) -# endif -#endif - -#define IN -#define OUT - -typedef uint32_t TEEC_Result; - -/** Definition of an UUID (from RFC 4122 http://www.ietf.org/rfc/rfc4122.txt) */ -typedef struct TEE_UUID { - uint32_t timeLow; - uint16_t timeMid; - uint16_t timeHiAndVersion; - uint8_t clockSeqAndNode[8]; -} TEE_UUID; -typedef TEE_UUID TEEC_UUID; - -/** Type definition for a TEE Identity */ -typedef struct TEE_Identity { - uint32_t login; - TEE_UUID uuid; -} TEE_Identity; - -#endif /* __TEE_CLIENT_TYPES_H__ */ diff --git a/mobicore/ClientLib/include/log.h b/mobicore/ClientLib/include/log.h deleted file mode 100644 index 34f3e40..0000000 --- a/mobicore/ClientLib/include/log.h +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -/** Log wrapper for Android. - * Maps LOG_*() macros to __android_log_print() if LOG_ANDROID is defined. - * Adds some extra info to log output like LOG_TAG, file name and line number. - */ -#ifndef TLCWRAPPERANDROIDLOG_H_ -#define TLCWRAPPERANDROIDLOG_H_ - -#include -#include -#include -#ifndef __cplusplus -#include -#endif - -#ifndef WIN32 -#include -#include -#define GETPID getpid -#else -#include -#define GETPID _getpid -#endif - -/** LOG_D(fmt, ...) - * Debug information logging, only shown in debug version - */ - -/** LOG_I(fmt, ...) - * Important information logging - */ - -/** LOG_W(fmt, ...) - * Warnings logging - */ - -/** LOG_E(fmt, ...) - * Error logging - */ - -/** LOG_D_BUF(szDescriptor, blob, sizeOfBlob) - * Binary logging, line-wise output to LOG_D - */ - -#define DUMMY_FUNCTION() do {} while(0) - -#ifdef LOG_ANDROID -#include -// log to adb logcat -#ifdef NDEBUG // no logging in debug version - #define LOG_D(fmt, ...) DUMMY_FUNCTION() -#else - // add LINE - #define LOG_D(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt " [%s:%d]", ##__VA_ARGS__, __FILE__, __LINE__) -#endif - #define LOG_I(fmt, ...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt " [%s:%d]", ##__VA_ARGS__, __FILE__, __LINE__) - #define LOG_W(fmt, ...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, fmt " [%s:%d]", ##__VA_ARGS__, __FILE__, __LINE__) - #define _LOG_E(fmt, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##__VA_ARGS__) -#endif // defined(LOG_ANDROID) - - -#ifdef LOG_TIZEN -#include -#ifdef NDEBUG - #define LOG_D(...) DUMMY_FUNCTION() -#else - #define LOG_D(...) SLOGD(__VA_ARGS__) -#endif - #define LOG_I(...) SLOGI(__VA_ARGS__) - #define LOG_W(...) SLOGW(__VA_ARGS__) - #define _LOG_E(...) SLOGE(__VA_ARGS__) -#endif // defined(LOG_TIZEN) - - -#if !defined(_LOG_E) - // log using fprintf, by default to stdout -#ifdef LOG_FPRINTF - extern FILE* mc_log_file_; - #define _LOG_x(_x_,...) \ - do { \ - fprintf(mc_log_file_, "%s/%s(%d): ",_x_,LOG_TAG,GETPID()); \ - fprintf(mc_log_file_, __VA_ARGS__); \ - fprintf(mc_log_file_, "\n"); \ - } while(0) -#else // LOG_FPRINTF - #define _LOG_x(_x_,...) \ - do { \ - printf("%s/%s(%d): ",_x_,LOG_TAG,GETPID()); \ - printf(__VA_ARGS__); \ - printf("\n"); \ - } while(0) -#endif // !LOG_FPRINTF - -#ifdef NDEBUG // no logging in debug version - #define LOG_D(fmt, ...) DUMMY_FUNCTION() -#else - #define LOG_D(...) _LOG_x("D",__VA_ARGS__) -#endif - #define LOG_I(...) _LOG_x("I",__VA_ARGS__) - #define LOG_W(...) _LOG_x("W",__VA_ARGS__) - #define _LOG_E(...) _LOG_x("E",__VA_ARGS__) -#endif // !defined(_LOG_E): neither Android nor Tizen - - -/** LOG_E() needs to be more prominent: - * Display "*********** ERROR ***********" before actual error message. - */ -#define LOG_E(...) \ - do { \ - _LOG_E(" *****************************"); \ - _LOG_E(" *** ERROR: " __VA_ARGS__); \ - _LOG_E(" *** Detected in %s:%u()", __FILE__, __LINE__); \ - _LOG_E(" *****************************"); \ - } while(0) - -#define LOG_ERRNO(MESSAGE) \ - LOG_E("%s failed with \"%s\"(errno %i)", MESSAGE, strerror(errno), errno); - -#ifdef NDEBUG - #define LOG_D_BUF(...) DUMMY_FUNCTION() -#else - #define LOG_D_BUF(f, b, s) LOG_x_BUF(f, b, s, true) -#endif -#define LOG_I_BUF(f, b, s) LOG_x_BUF(f, b, s, false) - -#ifndef WIN32 -__attribute__ ((unused)) -#endif -static void LOG_x_BUF( - const char* szDescriptor, - const void* blob, - size_t sizeOfBlob, - bool debug -) { - -#define CPL 0x10 // chars per line -#define OVERHEAD 20 - - char buffer[CPL * 4 + OVERHEAD]; - - int index = 0; - - uint32_t moreThanOneLine = (sizeOfBlob > CPL); - size_t blockLen = CPL; - uint32_t addr = 0; - uint32_t i = 0; - - if (NULL != szDescriptor) - { - index += sprintf(&buffer[index], "%s", szDescriptor); - } - - if (moreThanOneLine) - { - if (NULL == szDescriptor) - { - index += sprintf(&buffer[index], "memory dump"); - } - index += sprintf(&buffer[index], " (%p, %zu bytes)", blob,sizeOfBlob); - LOG_D("%s", buffer); - index = 0; - } - else if (NULL == szDescriptor) - { - index += sprintf(&buffer[index], "Data at %p: ", blob); - } - - if(sizeOfBlob == 0) { - LOG_D("%s", buffer); - } - else - { - while (sizeOfBlob > 0) - { - if (sizeOfBlob < blockLen) - { - blockLen = sizeOfBlob; - } - - // address - if (moreThanOneLine) - { - index += sprintf(&buffer[index], "0x%08X | ",addr); - addr += CPL; - } - // bytes as hex - for (i=0; i32)?c:'.'); - } - - blob = &(((const char *)blob)[blockLen]); - sizeOfBlob -= blockLen; - - // print line to logcat / stdout - if (debug) { - LOG_D("%s", buffer); - } else { - LOG_I("%s", buffer); - } - index = 0; - } - } -} - -#endif /** TLCWRAPPERANDROIDLOG_H_ */ diff --git a/mobicore/ClientLib/include/mcDriverId.h b/mobicore/ClientLib/include/mcDriverId.h deleted file mode 100644 index 65550d9..0000000 --- a/mobicore/ClientLib/include/mcDriverId.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 RTMDRVID_H_ -#define RTMDRVID_H_ - -#define MC_DRV_VENDOR_ID_SHIFT (16) -#define MC_DRV_VENDOR_ID_MASK (0xFFFF << MC_DRV_VENDOR_ID_SHIFT) -#define MC_DRV_NUMBER_MASK (0x0000FFFF) - -/** MobiCore vendor IDs. */ -typedef enum { - MC_DRV_VENDOR_ID_GD = 0 << MC_DRV_VENDOR_ID_SHIFT, -} mcDrvVendorId_t; - -/** MobiCore GD driver numbers. */ -typedef enum { - MC_DRV_NUMBER_INVALID = 0, - MC_DRV_NUMBER_CRYPTO = 1, - /** Last GD driver number reserved for pre-installed drivers. - * GD driver numbers up to this constant may not be used for loadable drivers. */ - MC_DRV_NUMBER_LAST_PRE_INSTALLED = 100, - TB_DRV_NUMBER_TUI = 0x101, - TB_DRV_NUMBER_SFS = 0x104, - TB_DRV_NUMBER_TPLAY = 0x600, -} mcDrvNumber_t; - -/** MobiCore driver IDs for Trustlets. */ -typedef enum { - MC_DRV_ID_INVALID = MC_DRV_VENDOR_ID_GD | MC_DRV_NUMBER_INVALID, - MC_DRV_ID_CRYPTO = MC_DRV_VENDOR_ID_GD | MC_DRV_NUMBER_CRYPTO, - MC_DRV_ID_SFS = MC_DRV_VENDOR_ID_GD | TB_DRV_NUMBER_SFS, - /** Last GD driver ID reserved for pre-installed drivers. - * GD driver IDs up to this constant may not be used for loadable drivers. */ - MC_DRV_ID_LAST_PRE_INSTALLED = MC_DRV_VENDOR_ID_GD | MC_DRV_NUMBER_LAST_PRE_INSTALLED, - TB_DRV_ID_TUI = MC_DRV_VENDOR_ID_GD | TB_DRV_NUMBER_TUI, - TB_DRV_ID_TPLAY = MC_DRV_VENDOR_ID_GD | TB_DRV_NUMBER_TPLAY, -} mcDriverId_t; - -#endif /* RTMDRVID_H_ */ diff --git a/mobicore/ClientLib/include/mcRootid.h b/mobicore/ClientLib/include/mcRootid.h deleted file mode 100644 index d1a17b1..0000000 --- a/mobicore/ClientLib/include/mcRootid.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_ROOTID_H_ -#define MC_ROOTID_H_ - -#ifdef WIN32 -#define _UNUSED -#else -#define _UNUSED __attribute__((unused)) -#endif - -/** Root Identifier type. */ -typedef uint32_t mcRootid_t; - -/** Reserved root id value 1. */ -static _UNUSED const mcRootid_t MC_ROOTID_RESERVED1 = 0; - -/** Reserved root id value 2. */ -static _UNUSED const mcRootid_t MC_ROOTID_RESERVED2 = 0xFFFFFFFF; - -/** Root id for system applications. */ -static _UNUSED const mcRootid_t MC_ROOTID_SYSTEM = 0xFFFFFFFE; - -/** Yet another test ROOT ID */ -static _UNUSED const mcRootid_t MC_ROOTID_RESERVED3 = 0xFFFFFFFD; - -/** GP TAs - used in the Trusted storage */ -static _UNUSED const mcRootid_t MC_ROOTID_GP = 0xFFFFFFFC; - -/** RTM's Root ID */ -static _UNUSED const mcRootid_t MC_ROOTID_RTM = 0xFFFFFFFB; - -#endif // MC_ROOTID_H_ - diff --git a/mobicore/ClientLib/include/mcSpid.h b/mobicore/ClientLib/include/mcSpid.h deleted file mode 100644 index 643e720..0000000 --- a/mobicore/ClientLib/include/mcSpid.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_SPID_H_ -#define MC_SPID_H_ - -#ifdef WIN32 -#define _UNUSED -#else -#define _UNUSED __attribute__((unused)) -#endif - -/** Service provider Identifier type. */ -typedef uint32_t mcSpid_t; - -/** SPID value used as free marker in root containers. */ -static _UNUSED const mcSpid_t MC_SPID_FREE = 0xFFFFFFFF; - -/** Reserved SPID value. */ -static _UNUSED const mcSpid_t MC_SPID_RESERVED = 0; - -/** SPID for system applications. */ -static _UNUSED const mcSpid_t MC_SPID_SYSTEM = 0xFFFFFFFE; - -/** SPID reserved for tests only */ -static _UNUSED const mcSpid_t MC_SPID_RESERVED_TEST = 0xFFFFFFFD; -static _UNUSED const mcSpid_t MC_SPID_TRUSTONIC_TEST = 0x4; - -/** SPID reserved for OTA development */ -static _UNUSED const mcSpid_t MC_SPID_TRUSTONIC_OTA = 0x2A; - -/** GP TAs - stored in the trusted storage. They all share the same */ -static _UNUSED const mcSpid_t MC_SPID_GP = 0xFFFFFFFC; - -/** RTM's SPID */ -static _UNUSED const mcSpid_t MC_SPID_RTM = 0xFFFFFFFB; - -#endif // MC_SPID_H_ - diff --git a/mobicore/ClientLib/include/mcSuid.h b/mobicore/ClientLib/include/mcSuid.h deleted file mode 100644 index b5bb983..0000000 --- a/mobicore/ClientLib/include/mcSuid.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_SUID_H_ -#define MC_SUID_H_ - -/** Length of SUID. */ -#define MC_SUID_LEN 16 - -/** Platform specific device identifier (serial number of the chip). */ -typedef struct { - uint8_t data[MC_SUID_LEN - sizeof(uint32_t)]; -} suidData_t; - -/** Soc unique identifier type. */ -typedef struct { - uint32_t sipId; /**< Silicon Provider ID to be set during build. */ - suidData_t suidData; -} mcSuid_t; - -#endif // MC_SUID_H_ - diff --git a/mobicore/ClientLib/include/mcUuid.h b/mobicore/ClientLib/include/mcUuid.h deleted file mode 100644 index 61ee94b..0000000 --- a/mobicore/ClientLib/include/mcUuid.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_UUID_H_ -#define MC_UUID_H_ - -#ifdef WIN32 -#define _UNUSED -#else -#define _UNUSED __attribute__((unused)) -#endif - -#define UUID_TYPE - -#define UUID_LENGTH 16 -/** Universally Unique Identifier (UUID) according to ISO/IEC 11578. */ -typedef struct { - uint8_t value[UUID_LENGTH]; /**< Value of the UUID. */ -} mcUuid_t, *mcUuid_ptr; - -/** UUID value used as free marker in service provider containers. */ -#define MC_UUID_FREE_DEFINE \ - { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } - -static _UNUSED const mcUuid_t MC_UUID_FREE = { - MC_UUID_FREE_DEFINE -}; - -/** Reserved UUID. */ -#define MC_UUID_RESERVED_DEFINE \ - { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } - -static _UNUSED const mcUuid_t MC_UUID_RESERVED = { - MC_UUID_RESERVED_DEFINE -}; - -/** UUID for system applications. */ -#define MC_UUID_SYSTEM_DEFINE \ - { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE } - -static _UNUSED const mcUuid_t MC_UUID_SYSTEM = { - MC_UUID_SYSTEM_DEFINE -}; - -#define MC_UUID_RTM_DEFINE \ - { 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, \ - 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, 0x12, 0x34 } - -static _UNUSED const mcUuid_t MC_UUID_RTM = { - MC_UUID_RTM_DEFINE -}; - -/** - * TODO: Replace with v5 UUID (milestone #3) - */ -#define LTA_UUID_DEFINE \ - { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ - 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11} - -#endif // MC_UUID_H_ - diff --git a/mobicore/ClientLib/include/mcVersionInfo.h b/mobicore/ClientLib/include/mcVersionInfo.h deleted file mode 100644 index 5e2ae86..0000000 --- a/mobicore/ClientLib/include/mcVersionInfo.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 MCVERSIONINFO_H_ -#define MCVERSIONINFO_H_ - -/** Length of MobiCore product ID string. */ -#define MC_PRODUCT_ID_LEN 64 - -/** Global MobiCore Version Information. - */ -typedef struct { - char productId[MC_PRODUCT_ID_LEN]; /** < Product ID of Mobicore; zero-terminated */ - uint32_t versionMci; /** < Version of Mobicore Control Interface */ - uint32_t versionSo; /** < Version of Secure Objects */ - uint32_t versionMclf; /** < Version of MobiCore Load Format */ - uint32_t versionContainer; /** < Version of MobiCore Container Format */ - uint32_t versionMcConfig; /** < Version of MobiCore Configuration Block Format */ - uint32_t versionTlApi; /** < Version of MobiCore Trustlet API Implementation */ - uint32_t versionDrApi; /** < Version of MobiCore Driver API Implementation */ - uint32_t versionCmp; /** < Version of Content Management Protocol */ -} mcVersionInfo_t; - -#endif /** MCVERSIONINFO_H_ */ diff --git a/mobicore/ClientLib/include/proxy_server.h b/mobicore/ClientLib/include/proxy_server.h deleted file mode 100644 index 0c5cae1..0000000 --- a/mobicore/ClientLib/include/proxy_server.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __PROXY_SERVER_H__ -#define __PROXY_SERVER_H__ - -class ProxyServer { - struct Impl; - Impl* const pimpl_; - void run(); -public: - ProxyServer(); - ~ProxyServer(); - int open(); - int close(); -}; - -#endif // __PROXY_SERVER_H__ diff --git a/mobicore/ClientLib/src/buildTag.h b/mobicore/ClientLib/src/buildTag.h deleted file mode 100644 index d8a4859..0000000 --- a/mobicore/ClientLib/src/buildTag.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 MOBICORE_COMPONENT_BUILD_TAG -#define MOBICORE_COMPONENT_BUILD_TAG \ - "t-base-EXYNOS64-Android-310B-V006-20160331_140301_7136" -#endif diff --git a/mobicore/ClientLib/src/common_client.cpp b/mobicore/ClientLib/src/common_client.cpp deleted file mode 100644 index 90e5fd7..0000000 --- a/mobicore/ClientLib/src/common_client.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#undef LOG_TAG -#define LOG_TAG "TeeCommonClient" -#include "log.h" -#include "mcVersionHelper.h" -#include "driver_client.h" -#ifndef WITHOUT_PROXY -#include "proxy_client.h" -#endif -#include "common_client.h" - -#ifdef LOG_FPRINTF -// Set default log destination (needs to be somewhere) -FILE* mc_log_file_ = stdout; -#endif - -struct CommonClient::Impl { - pthread_mutex_t mutex; - int open_count; - DriverClient driver; -#ifndef WITHOUT_PROXY - ProxyClient proxy; -#endif - IClient* client; - OpenMode open_mode; - Impl(): open_count(0), client(NULL), open_mode(AUTO) { - pthread_mutex_init(&mutex, NULL); - } -}; - -CommonClient::CommonClient(): pimpl_(new Impl) { -} - -CommonClient::~CommonClient() { - delete pimpl_; -} - -int CommonClient::open() { - int ret = 0; - pthread_mutex_lock(&pimpl_->mutex); - if (pimpl_->client && !pimpl_->client->isOpen()) { - pimpl_->open_count = 0; - } - if (pimpl_->open_count == 0) { - if ((pimpl_->open_mode != PROXY) && (pimpl_->driver.open() >= 0)) { - pimpl_->client = &pimpl_->driver; -#ifndef WITHOUT_PROXY - } else if ((pimpl_->open_mode != DRIVER) && - (pimpl_->proxy.open() >= 0)) { - pimpl_->client = &pimpl_->proxy; -#endif - } else { - LOG_E("Failed to open lower layers: %s", strerror(errno)); - ret = -1; - } - } - if (pimpl_->client) { - pimpl_->open_count++; - } - pthread_mutex_unlock(&pimpl_->mutex); - LOG_D("%s ret=%d open_count=%d", __FUNCTION__, ret, pimpl_->open_count); - return ret; -} - -int CommonClient::closeCheck() { - int ret; - pthread_mutex_lock(&pimpl_->mutex); - if (pimpl_->open_count > 1) { - pimpl_->open_count--; - ret = 0; - } else { - errno = EPERM; - ret = -1; - } - pthread_mutex_unlock(&pimpl_->mutex); - LOG_D("%s ret=%d open_count=%d", __FUNCTION__, ret, pimpl_->open_count); - return ret; -} - -int CommonClient::close() { - int ret = -1; - pthread_mutex_lock(&pimpl_->mutex); - /* Not open */ - if (!pimpl_->client) { - errno = EBADF; - } else { - /* Last token */ - if (pimpl_->open_count == 1) { - ret = pimpl_->client->close(); - pimpl_->client = NULL; - } else { - ret = 0; - } - pimpl_->open_count--; - } - pthread_mutex_unlock(&pimpl_->mutex); - LOG_D("%s ret=%d open_count=%d", __FUNCTION__, ret, pimpl_->open_count); - return ret; -} - -bool CommonClient::isOpen() const { - return pimpl_->open_count > 0; -} - -int CommonClient::hasOpenSessions() const { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->hasOpenSessions(); -} - -int CommonClient::openSession(struct mc_ioctl_open_session& session) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->openSession(session); -} - -int CommonClient::openTrustlet(struct mc_ioctl_open_trustlet& trustlet) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->openTrustlet(trustlet); -} - -int CommonClient::closeSession(uint32_t session_id) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->closeSession(session_id); -} - -int CommonClient::notify(uint32_t session_id) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->notify(session_id); -} - -int CommonClient::waitNotification(const struct mc_ioctl_wait& wait) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->waitNotification(wait); -} - -int CommonClient::malloc(uint8_t** buffer, uint32_t length) { - // Check length here to make sure we are consistent, with or without proxy - if ((length == 0) || (length > BUFFER_LENGTH_MAX)) { - errno = EINVAL; - return -1; - } - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->malloc(buffer, length); -} - -int CommonClient::free(uint8_t* buffer, uint32_t length) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->free(buffer, length); -} - -int CommonClient::map(struct mc_ioctl_map& map) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->map(map); -} - -int CommonClient::unmap(const struct mc_ioctl_map& map) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->unmap(map); -} - -int CommonClient::getError(struct mc_ioctl_geterr& err) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->getError(err); -} - -int CommonClient::getVersion(struct mc_version_info& version_info) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->getVersion(version_info); -} - -int CommonClient::gpRequestCancellation(uint32_t session_id) { - if (!pimpl_->client) { - errno = EBADF; - return -1; - } - return pimpl_->client->gpRequestCancellation(session_id); -} - -void CommonClient::setOpenMode(OpenMode open_mode) { -#ifdef WITHOUT_PROXY - (void) open_mode; -#else - pimpl_->open_mode = open_mode; -#endif -} diff --git a/mobicore/ClientLib/src/common_client.h b/mobicore/ClientLib/src/common_client.h deleted file mode 100644 index 0458999..0000000 --- a/mobicore/ClientLib/src/common_client.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -/* Common open/file device functions for Mobicore and GP */ - -#ifndef __CLIENT_COMMON_H__ -#define __CLIENT_COMMON_H__ - -#include "iclient.h" - -class CommonClient: public IClient { - struct Impl; - Impl* const pimpl_; - CommonClient(); -public: - ~CommonClient(); - virtual int open(); - int closeCheck(); - virtual int close(); - virtual bool isOpen() const; - virtual int hasOpenSessions() const; - virtual int openSession(struct mc_ioctl_open_session& session); - virtual int openTrustlet(struct mc_ioctl_open_trustlet& trustlet); - virtual int closeSession(uint32_t session_id); - virtual int notify(uint32_t session_id); - virtual int waitNotification(const struct mc_ioctl_wait& wait); - virtual int malloc(uint8_t** buffer, uint32_t length); - virtual int free(uint8_t* buffer, uint32_t length); - virtual int map(struct mc_ioctl_map& map); - virtual int unmap(const struct mc_ioctl_map& map); - virtual int getError(struct mc_ioctl_geterr& err); - virtual int getVersion(struct mc_version_info& version_info); - virtual int gpRequestCancellation(uint32_t session_id); - // Singleton - static CommonClient& getInstance() { - static CommonClient client; - return client; - } - // For test purpose - enum OpenMode { - AUTO, - DRIVER = 0x44525652, - PROXY = 0x50525859, - }; - void setOpenMode(OpenMode open_mode); -}; - -#endif // __CLIENT_COMMON_H__ diff --git a/mobicore/ClientLib/src/driver_client.cpp b/mobicore/ClientLib/src/driver_client.cpp deleted file mode 100644 index e93a7a5..0000000 --- a/mobicore/ClientLib/src/driver_client.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include - -#include -#include -#include -#include -#include -#include - -#include // TEEC_UUID -#include // _TEEC_TCI - -#undef LOG_TAG -#define LOG_TAG "TeeDriverClient" -#include "log.h" -#include "mcVersionHelper.h" -#include "driver_client.h" - -MC_CHECK_VERSION(MCDRVMODULEAPI, 2, 1); - -struct DriverClient::Impl { - struct GpSession { - uint32_t id; - _TEEC_TCI* tci; - GpSession(uint32_t i, uint64_t t): id(i) { - tci = reinterpret_cast<_TEEC_TCI*>(static_cast(t)); - } - }; - pthread_mutex_t gp_sessions_mutex; - std::vector gp_sessions; - int fd; - Impl(): fd(-1) { - ::pthread_mutex_init(&gp_sessions_mutex, NULL); - } - ~Impl() { - ::pthread_mutex_destroy(&gp_sessions_mutex); - } -}; - -DriverClient::DriverClient(): pimpl_(new Impl) { -} - -DriverClient::~DriverClient() { - delete pimpl_; -} - -int DriverClient::open() { - int fd = ::open("/dev/" MC_USER_DEVNODE, O_RDWR | O_CLOEXEC); - if (fd < 0) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return -1; - } - - struct mc_version_info version_info; - if (::ioctl(fd, MC_IO_VERSION, &version_info) < 0) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - (void)::close(fd); - return -1; - } - - // Run-time check. - uint32_t version = version_info.version_nwd; - char* errmsg; - if (!checkVersionOkMCDRVMODULEAPI(version, &errmsg)) { - (void)::close(fd); - errno = EHOSTDOWN; - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return -1; - } - - pimpl_->fd = fd; - LOG_I("driver client open"); - return 0; -} - -int DriverClient::close() { - int ret = ::close(pimpl_->fd); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - } - pimpl_->fd = -1; - LOG_I("driver client closed"); - return ret; -} - -bool DriverClient::isOpen() const { - return pimpl_->fd != -1; -} - -int DriverClient::hasOpenSessions() const { - int ret = ::ioctl(pimpl_->fd, MC_IO_HAS_SESSIONS); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - } - return ret; -} - -int DriverClient::openSession(struct mc_ioctl_open_session& session) { - int ret = ::ioctl(pimpl_->fd, MC_IO_OPEN_SESSION, &session); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - if (session.is_gp_uuid) { - pthread_mutex_lock(&pimpl_->gp_sessions_mutex); - pimpl_->gp_sessions.push_back( - new Impl::GpSession(session.sid, session.tci)); - pthread_mutex_unlock(&pimpl_->gp_sessions_mutex); - } - LOG_D("session %x open", session.sid); - return ret; -} - -int DriverClient::openTrustlet(struct mc_ioctl_open_trustlet& trustlet) { - int ret = ::ioctl(pimpl_->fd, MC_IO_OPEN_TRUSTLET, &trustlet); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - LOG_D("session %x open", trustlet.sid); - return ret; -} - -int DriverClient::closeSession(uint32_t session_id) { - LOG_D("session %x close", session_id); - int ret = ::ioctl(pimpl_->fd, MC_IO_CLOSE_SESSION, session_id); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - pthread_mutex_lock(&pimpl_->gp_sessions_mutex); - for (auto it = pimpl_->gp_sessions.begin(); - it != pimpl_->gp_sessions.end(); it++) { - auto gp_session = *it; - if (gp_session->id == session_id) { - pimpl_->gp_sessions.erase(it); - delete gp_session; - break; - } - } - pthread_mutex_unlock(&pimpl_->gp_sessions_mutex); - LOG_D("session %x closed", session_id); - return ret; -} - -int DriverClient::notify(uint32_t session_id) { - int ret = ::ioctl(pimpl_->fd, MC_IO_NOTIFY, session_id); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - LOG_D("session %x notification sent", session_id); - return ret; -} - -int DriverClient::waitNotification(const struct mc_ioctl_wait& wait) { - LOG_D("session %x wait for notification", wait.sid); - int ret = ::ioctl(pimpl_->fd, MC_IO_WAIT, &wait); - if (ret && ((errno != ETIME) || !wait.partial)) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - LOG_D("session %x notification received", wait.sid); - return ret; -} - -int DriverClient::malloc(uint8_t** buffer, uint32_t length) { - *buffer = static_cast(mmap(0, length, PROT_READ | PROT_WRITE, - MAP_SHARED, pimpl_->fd, 0)); - if (*buffer == MAP_FAILED) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return -1; - } - return 0; -} - -int DriverClient::free(uint8_t* buffer, uint32_t length) { - int ret = munmap(buffer, length); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - } - return ret; -} - -int DriverClient::map(struct mc_ioctl_map& map) { - int ret = ::ioctl(pimpl_->fd, MC_IO_MAP, &map); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - LOG_D("session %x buffer(s) mapped", map.sid); - return ret; -} - -int DriverClient::unmap(const struct mc_ioctl_map& map) { - int ret = ::ioctl(pimpl_->fd, MC_IO_UNMAP, &map); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - LOG_D("session %x buffer(s) unmapped", map.sid); - return ret; -} - -int DriverClient::getError(struct mc_ioctl_geterr& err) { - int ret = ::ioctl(pimpl_->fd, MC_IO_ERR, &err); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - return ret; - } - LOG_D("session %x exit code %d", err.sid, err.value); - return ret; -} - -int DriverClient::getVersion(struct mc_version_info& version_info) { - int ret = ::ioctl(pimpl_->fd, MC_IO_VERSION, &version_info); - if (ret) { - _LOG_E("%s in %s", strerror(errno), __FUNCTION__); - } - return ret; -} - -// This class will need to handle the GP protocol at some point, but for now it -// only deals with cancellation -int DriverClient::gpRequestCancellation(uint32_t session_id) { - bool found = false; - pthread_mutex_lock(&pimpl_->gp_sessions_mutex); - for (auto it = pimpl_->gp_sessions.begin(); it != pimpl_->gp_sessions.end(); - it++) { - auto gp_session = *it; - if (gp_session->id == session_id) { - // Will be reset by caller at next InvokeCommand - gp_session->tci->operation.isCancelled = true; - found = true; - } - } - pthread_mutex_unlock(&pimpl_->gp_sessions_mutex); - if (!found) { - errno = ENOENT; - return -1; - } - return notify(session_id); -} diff --git a/mobicore/ClientLib/src/driver_client.h b/mobicore/ClientLib/src/driver_client.h deleted file mode 100644 index 6902714..0000000 --- a/mobicore/ClientLib/src/driver_client.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __CLIENT_DRIVER_H__ -#define __CLIENT_DRIVER_H__ - -#include "iclient.h" - -class DriverClient: public IClient { - struct Impl; - Impl* const pimpl_; -public: - DriverClient(); - ~DriverClient(); - virtual int open(); - virtual int close(); - virtual bool isOpen() const; - virtual int hasOpenSessions() const; - virtual int openSession(struct mc_ioctl_open_session& session); - virtual int openTrustlet(struct mc_ioctl_open_trustlet& trustlet); - virtual int closeSession(uint32_t session_id); - virtual int notify(uint32_t session_id); - virtual int waitNotification(const struct mc_ioctl_wait& wait); - virtual int malloc(uint8_t** buffer, uint32_t length); - virtual int free(uint8_t* buffer, uint32_t length); - virtual int map(struct mc_ioctl_map& map); - virtual int unmap(const struct mc_ioctl_map& map); - virtual int getError(struct mc_ioctl_geterr& err); - virtual int getVersion(struct mc_version_info& version_info); - virtual int gpRequestCancellation(uint32_t session_id); -}; - -#endif // __CLIENT_DRIVER_H__ diff --git a/mobicore/ClientLib/src/iclient.h b/mobicore/ClientLib/src/iclient.h deleted file mode 100644 index f95186c..0000000 --- a/mobicore/ClientLib/src/iclient.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __CLIENT_INTERFACE_H__ -#define __CLIENT_INTERFACE_H__ - -#include // *int*_t -#include // uid_t git_t -#include "mc_user.h" // ioctl structures - -class IClient { -public: - virtual ~IClient() {} - virtual int open() = 0; - virtual int close() = 0; - virtual bool isOpen() const = 0; - // MC protocol, also used by GP for now - virtual int hasOpenSessions() const = 0; - virtual int openSession(struct mc_ioctl_open_session& session) = 0; - virtual int openTrustlet(struct mc_ioctl_open_trustlet& trustlet) = 0; - virtual int closeSession(uint32_t session_id) = 0; - virtual int notify(uint32_t session_id) = 0; - virtual int waitNotification(const struct mc_ioctl_wait& wait) = 0; - virtual int malloc(uint8_t** buffer, uint32_t length) = 0; - virtual int free(uint8_t* buffer, uint32_t length) = 0; - virtual int map(struct mc_ioctl_map& map) = 0; - virtual int unmap(const struct mc_ioctl_map& map) = 0; - virtual int getError(struct mc_ioctl_geterr& err) = 0; - virtual int getVersion(struct mc_version_info& version_info) = 0; - // GP protocol only - virtual int gpRequestCancellation(uint32_t session_id) = 0; -}; - -#endif // __CLIENT_INTERFACE_H__ diff --git a/mobicore/ClientLib/src/mc.pb.cpp b/mobicore/ClientLib/src/mc.pb.cpp deleted file mode 100644 index a36a527..0000000 --- a/mobicore/ClientLib/src/mc.pb.cpp +++ /dev/null @@ -1,5695 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: mc.proto - -#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION -#include "mc.pb.h" - -#include - -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace com { -namespace trustonic { -namespace tee_proxy { - -void protobuf_ShutdownFile_mc_2eproto() { - delete OpenSessionRequest::default_instance_; - delete OpenSessionResponse::default_instance_; - delete OpenTrustletRequest::default_instance_; - delete OpenTrustletResponse::default_instance_; - delete CloseSessionRequest::default_instance_; - delete CloseSessionResponse::default_instance_; - delete NotifyRequest::default_instance_; - delete NotifyRequest_Buffers::default_instance_; - delete NotifyResponse::default_instance_; - delete WaitNotificationRequest::default_instance_; - delete WaitNotificationResponse::default_instance_; - delete WaitNotificationResponse_Buffers::default_instance_; - delete MapRequest::default_instance_; - delete MapRequest_Buffers::default_instance_; - delete MapResponse::default_instance_; - delete MapResponse_Buffers::default_instance_; - delete UnmapRequest::default_instance_; - delete UnmapRequest_Buffers::default_instance_; - delete UnmapResponse::default_instance_; - delete GetErrorRequest::default_instance_; - delete GetErrorResponse::default_instance_; - delete GetVersionRequest::default_instance_; - delete GetVersionResponse::default_instance_; - delete GpRequestCancellationRequest::default_instance_; - delete GpRequestCancellationResponse::default_instance_; -} - -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER -void protobuf_AddDesc_mc_2eproto_impl() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - -#else -void protobuf_AddDesc_mc_2eproto() { - static bool already_here = false; - if (already_here) return; - already_here = true; - GOOGLE_PROTOBUF_VERIFY_VERSION; - -#endif - OpenSessionRequest::default_instance_ = new OpenSessionRequest(); - OpenSessionResponse::default_instance_ = new OpenSessionResponse(); - OpenTrustletRequest::default_instance_ = new OpenTrustletRequest(); - OpenTrustletResponse::default_instance_ = new OpenTrustletResponse(); - CloseSessionRequest::default_instance_ = new CloseSessionRequest(); - CloseSessionResponse::default_instance_ = new CloseSessionResponse(); - NotifyRequest::default_instance_ = new NotifyRequest(); - NotifyRequest_Buffers::default_instance_ = new NotifyRequest_Buffers(); - NotifyResponse::default_instance_ = new NotifyResponse(); - WaitNotificationRequest::default_instance_ = new WaitNotificationRequest(); - WaitNotificationResponse::default_instance_ = new WaitNotificationResponse(); - WaitNotificationResponse_Buffers::default_instance_ = new WaitNotificationResponse_Buffers(); - MapRequest::default_instance_ = new MapRequest(); - MapRequest_Buffers::default_instance_ = new MapRequest_Buffers(); - MapResponse::default_instance_ = new MapResponse(); - MapResponse_Buffers::default_instance_ = new MapResponse_Buffers(); - UnmapRequest::default_instance_ = new UnmapRequest(); - UnmapRequest_Buffers::default_instance_ = new UnmapRequest_Buffers(); - UnmapResponse::default_instance_ = new UnmapResponse(); - GetErrorRequest::default_instance_ = new GetErrorRequest(); - GetErrorResponse::default_instance_ = new GetErrorResponse(); - GetVersionRequest::default_instance_ = new GetVersionRequest(); - GetVersionResponse::default_instance_ = new GetVersionResponse(); - GpRequestCancellationRequest::default_instance_ = new GpRequestCancellationRequest(); - GpRequestCancellationResponse::default_instance_ = new GpRequestCancellationResponse(); - OpenSessionRequest::default_instance_->InitAsDefaultInstance(); - OpenSessionResponse::default_instance_->InitAsDefaultInstance(); - OpenTrustletRequest::default_instance_->InitAsDefaultInstance(); - OpenTrustletResponse::default_instance_->InitAsDefaultInstance(); - CloseSessionRequest::default_instance_->InitAsDefaultInstance(); - CloseSessionResponse::default_instance_->InitAsDefaultInstance(); - NotifyRequest::default_instance_->InitAsDefaultInstance(); - NotifyRequest_Buffers::default_instance_->InitAsDefaultInstance(); - NotifyResponse::default_instance_->InitAsDefaultInstance(); - WaitNotificationRequest::default_instance_->InitAsDefaultInstance(); - WaitNotificationResponse::default_instance_->InitAsDefaultInstance(); - WaitNotificationResponse_Buffers::default_instance_->InitAsDefaultInstance(); - MapRequest::default_instance_->InitAsDefaultInstance(); - MapRequest_Buffers::default_instance_->InitAsDefaultInstance(); - MapResponse::default_instance_->InitAsDefaultInstance(); - MapResponse_Buffers::default_instance_->InitAsDefaultInstance(); - UnmapRequest::default_instance_->InitAsDefaultInstance(); - UnmapRequest_Buffers::default_instance_->InitAsDefaultInstance(); - UnmapResponse::default_instance_->InitAsDefaultInstance(); - GetErrorRequest::default_instance_->InitAsDefaultInstance(); - GetErrorResponse::default_instance_->InitAsDefaultInstance(); - GetVersionRequest::default_instance_->InitAsDefaultInstance(); - GetVersionResponse::default_instance_->InitAsDefaultInstance(); - GpRequestCancellationRequest::default_instance_->InitAsDefaultInstance(); - GpRequestCancellationResponse::default_instance_->InitAsDefaultInstance(); - ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_mc_2eproto); -} - -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_mc_2eproto_once_); -void protobuf_AddDesc_mc_2eproto() { - ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_mc_2eproto_once_, - &protobuf_AddDesc_mc_2eproto_impl); -} -#else -// Force AddDescriptors() to be called at static initialization time. -struct StaticDescriptorInitializer_mc_2eproto { - StaticDescriptorInitializer_mc_2eproto() { - protobuf_AddDesc_mc_2eproto(); - } -} static_descriptor_initializer_mc_2eproto_; -#endif -bool LoginType_IsValid(int value) { - switch(value) { - case 0: - case 1: - case 2: - case 4: - case 5: - case 6: - return true; - default: - return false; - } -} - - -// =================================================================== - -#ifndef _MSC_VER -const int OpenSessionRequest::kUuidFieldNumber; -const int OpenSessionRequest::kIsGpUuidFieldNumber; -const int OpenSessionRequest::kTciFieldNumber; -const int OpenSessionRequest::kLoginTypeFieldNumber; -const int OpenSessionRequest::kLoginDataFieldNumber; -#endif // !_MSC_VER - -OpenSessionRequest::OpenSessionRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.OpenSessionRequest) -} - -void OpenSessionRequest::InitAsDefaultInstance() { -} - -OpenSessionRequest::OpenSessionRequest(const OpenSessionRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.OpenSessionRequest) -} - -void OpenSessionRequest::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - uuid_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - is_gp_uuid_ = false; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - login_type_ = 0; - login_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -OpenSessionRequest::~OpenSessionRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.OpenSessionRequest) - SharedDtor(); -} - -void OpenSessionRequest::SharedDtor() { - if (uuid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete uuid_; - } - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - if (login_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete login_data_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void OpenSessionRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const OpenSessionRequest& OpenSessionRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -OpenSessionRequest* OpenSessionRequest::default_instance_ = NULL; - -OpenSessionRequest* OpenSessionRequest::New() const { - return new OpenSessionRequest; -} - -void OpenSessionRequest::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - if (_has_bits_[0 / 32] & 31) { - ZR_(is_gp_uuid_, login_type_); - if (has_uuid()) { - if (uuid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - uuid_->clear(); - } - } - if (has_tci()) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - } - if (has_login_data()) { - if (login_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - login_data_->clear(); - } - } - } - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool OpenSessionRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.OpenSessionRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required bytes uuid = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_uuid())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_is_gp_uuid; - break; - } - - // required bool is_gp_uuid = 2; - case 2: { - if (tag == 16) { - parse_is_gp_uuid: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &is_gp_uuid_))); - set_has_is_gp_uuid(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_tci; - break; - } - - // optional bytes tci = 3; - case 3: { - if (tag == 26) { - parse_tci: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_tci())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(32)) goto parse_login_type; - break; - } - - // required .com.trustonic.tee_proxy.LoginType login_type = 4; - case 4: { - if (tag == 32) { - parse_login_type: - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - if (::com::trustonic::tee_proxy::LoginType_IsValid(value)) { - set_login_type(static_cast< ::com::trustonic::tee_proxy::LoginType >(value)); - } else { - unknown_fields_stream.WriteVarint32(tag); - unknown_fields_stream.WriteVarint32(value); - } - } else { - goto handle_unusual; - } - if (input->ExpectTag(42)) goto parse_login_data; - break; - } - - // required bytes login_data = 5; - case 5: { - if (tag == 42) { - parse_login_data: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_login_data())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.OpenSessionRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.OpenSessionRequest) - return false; -#undef DO_ -} - -void OpenSessionRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.OpenSessionRequest) - // required bytes uuid = 1; - if (has_uuid()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 1, this->uuid(), output); - } - - // required bool is_gp_uuid = 2; - if (has_is_gp_uuid()) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_gp_uuid(), output); - } - - // optional bytes tci = 3; - if (has_tci()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 3, this->tci(), output); - } - - // required .com.trustonic.tee_proxy.LoginType login_type = 4; - if (has_login_type()) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 4, this->login_type(), output); - } - - // required bytes login_data = 5; - if (has_login_data()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 5, this->login_data(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.OpenSessionRequest) -} - -int OpenSessionRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required bytes uuid = 1; - if (has_uuid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->uuid()); - } - - // required bool is_gp_uuid = 2; - if (has_is_gp_uuid()) { - total_size += 1 + 1; - } - - // optional bytes tci = 3; - if (has_tci()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->tci()); - } - - // required .com.trustonic.tee_proxy.LoginType login_type = 4; - if (has_login_type()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->login_type()); - } - - // required bytes login_data = 5; - if (has_login_data()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->login_data()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void OpenSessionRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void OpenSessionRequest::MergeFrom(const OpenSessionRequest& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_uuid()) { - set_uuid(from.uuid()); - } - if (from.has_is_gp_uuid()) { - set_is_gp_uuid(from.is_gp_uuid()); - } - if (from.has_tci()) { - set_tci(from.tci()); - } - if (from.has_login_type()) { - set_login_type(from.login_type()); - } - if (from.has_login_data()) { - set_login_data(from.login_data()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void OpenSessionRequest::CopyFrom(const OpenSessionRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool OpenSessionRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x0000001b) != 0x0000001b) return false; - - return true; -} - -void OpenSessionRequest::Swap(OpenSessionRequest* other) { - if (other != this) { - std::swap(uuid_, other->uuid_); - std::swap(is_gp_uuid_, other->is_gp_uuid_); - std::swap(tci_, other->tci_); - std::swap(login_type_, other->login_type_); - std::swap(login_data_, other->login_data_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string OpenSessionRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.OpenSessionRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int OpenSessionResponse::kIdFieldNumber; -#endif // !_MSC_VER - -OpenSessionResponse::OpenSessionResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.OpenSessionResponse) -} - -void OpenSessionResponse::InitAsDefaultInstance() { -} - -OpenSessionResponse::OpenSessionResponse(const OpenSessionResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.OpenSessionResponse) -} - -void OpenSessionResponse::SharedCtor() { - _cached_size_ = 0; - id_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -OpenSessionResponse::~OpenSessionResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.OpenSessionResponse) - SharedDtor(); -} - -void OpenSessionResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void OpenSessionResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const OpenSessionResponse& OpenSessionResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -OpenSessionResponse* OpenSessionResponse::default_instance_ = NULL; - -OpenSessionResponse* OpenSessionResponse::New() const { - return new OpenSessionResponse; -} - -void OpenSessionResponse::Clear() { - id_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool OpenSessionResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.OpenSessionResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 id = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &id_))); - set_has_id(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.OpenSessionResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.OpenSessionResponse) - return false; -#undef DO_ -} - -void OpenSessionResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.OpenSessionResponse) - // required uint32 id = 1; - if (has_id()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->id(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.OpenSessionResponse) -} - -int OpenSessionResponse::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 id = 1; - if (has_id()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->id()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void OpenSessionResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void OpenSessionResponse::MergeFrom(const OpenSessionResponse& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_id()) { - set_id(from.id()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void OpenSessionResponse::CopyFrom(const OpenSessionResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool OpenSessionResponse::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void OpenSessionResponse::Swap(OpenSessionResponse* other) { - if (other != this) { - std::swap(id_, other->id_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string OpenSessionResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.OpenSessionResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int OpenTrustletRequest::kSpidFieldNumber; -const int OpenTrustletRequest::kTrustappFieldNumber; -const int OpenTrustletRequest::kTciFieldNumber; -#endif // !_MSC_VER - -OpenTrustletRequest::OpenTrustletRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.OpenTrustletRequest) -} - -void OpenTrustletRequest::InitAsDefaultInstance() { -} - -OpenTrustletRequest::OpenTrustletRequest(const OpenTrustletRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.OpenTrustletRequest) -} - -void OpenTrustletRequest::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - spid_ = 0u; - trustapp_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -OpenTrustletRequest::~OpenTrustletRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.OpenTrustletRequest) - SharedDtor(); -} - -void OpenTrustletRequest::SharedDtor() { - if (trustapp_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete trustapp_; - } - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void OpenTrustletRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const OpenTrustletRequest& OpenTrustletRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -OpenTrustletRequest* OpenTrustletRequest::default_instance_ = NULL; - -OpenTrustletRequest* OpenTrustletRequest::New() const { - return new OpenTrustletRequest; -} - -void OpenTrustletRequest::Clear() { - if (_has_bits_[0 / 32] & 7) { - spid_ = 0u; - if (has_trustapp()) { - if (trustapp_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - trustapp_->clear(); - } - } - if (has_tci()) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool OpenTrustletRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.OpenTrustletRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 spid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &spid_))); - set_has_spid(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_trustapp; - break; - } - - // required bytes trustapp = 2; - case 2: { - if (tag == 18) { - parse_trustapp: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_trustapp())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_tci; - break; - } - - // optional bytes tci = 3; - case 3: { - if (tag == 26) { - parse_tci: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_tci())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.OpenTrustletRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.OpenTrustletRequest) - return false; -#undef DO_ -} - -void OpenTrustletRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.OpenTrustletRequest) - // required uint32 spid = 1; - if (has_spid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->spid(), output); - } - - // required bytes trustapp = 2; - if (has_trustapp()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 2, this->trustapp(), output); - } - - // optional bytes tci = 3; - if (has_tci()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 3, this->tci(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.OpenTrustletRequest) -} - -int OpenTrustletRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 spid = 1; - if (has_spid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->spid()); - } - - // required bytes trustapp = 2; - if (has_trustapp()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->trustapp()); - } - - // optional bytes tci = 3; - if (has_tci()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->tci()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void OpenTrustletRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void OpenTrustletRequest::MergeFrom(const OpenTrustletRequest& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_spid()) { - set_spid(from.spid()); - } - if (from.has_trustapp()) { - set_trustapp(from.trustapp()); - } - if (from.has_tci()) { - set_tci(from.tci()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void OpenTrustletRequest::CopyFrom(const OpenTrustletRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool OpenTrustletRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; - - return true; -} - -void OpenTrustletRequest::Swap(OpenTrustletRequest* other) { - if (other != this) { - std::swap(spid_, other->spid_); - std::swap(trustapp_, other->trustapp_); - std::swap(tci_, other->tci_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string OpenTrustletRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.OpenTrustletRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int OpenTrustletResponse::kIdFieldNumber; -#endif // !_MSC_VER - -OpenTrustletResponse::OpenTrustletResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.OpenTrustletResponse) -} - -void OpenTrustletResponse::InitAsDefaultInstance() { -} - -OpenTrustletResponse::OpenTrustletResponse(const OpenTrustletResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.OpenTrustletResponse) -} - -void OpenTrustletResponse::SharedCtor() { - _cached_size_ = 0; - id_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -OpenTrustletResponse::~OpenTrustletResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.OpenTrustletResponse) - SharedDtor(); -} - -void OpenTrustletResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void OpenTrustletResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const OpenTrustletResponse& OpenTrustletResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -OpenTrustletResponse* OpenTrustletResponse::default_instance_ = NULL; - -OpenTrustletResponse* OpenTrustletResponse::New() const { - return new OpenTrustletResponse; -} - -void OpenTrustletResponse::Clear() { - id_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool OpenTrustletResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.OpenTrustletResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 id = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &id_))); - set_has_id(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.OpenTrustletResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.OpenTrustletResponse) - return false; -#undef DO_ -} - -void OpenTrustletResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.OpenTrustletResponse) - // required uint32 id = 1; - if (has_id()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->id(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.OpenTrustletResponse) -} - -int OpenTrustletResponse::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 id = 1; - if (has_id()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->id()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void OpenTrustletResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void OpenTrustletResponse::MergeFrom(const OpenTrustletResponse& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_id()) { - set_id(from.id()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void OpenTrustletResponse::CopyFrom(const OpenTrustletResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool OpenTrustletResponse::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void OpenTrustletResponse::Swap(OpenTrustletResponse* other) { - if (other != this) { - std::swap(id_, other->id_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string OpenTrustletResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.OpenTrustletResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int CloseSessionRequest::kIdFieldNumber; -#endif // !_MSC_VER - -CloseSessionRequest::CloseSessionRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.CloseSessionRequest) -} - -void CloseSessionRequest::InitAsDefaultInstance() { -} - -CloseSessionRequest::CloseSessionRequest(const CloseSessionRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.CloseSessionRequest) -} - -void CloseSessionRequest::SharedCtor() { - _cached_size_ = 0; - id_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -CloseSessionRequest::~CloseSessionRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.CloseSessionRequest) - SharedDtor(); -} - -void CloseSessionRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void CloseSessionRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const CloseSessionRequest& CloseSessionRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -CloseSessionRequest* CloseSessionRequest::default_instance_ = NULL; - -CloseSessionRequest* CloseSessionRequest::New() const { - return new CloseSessionRequest; -} - -void CloseSessionRequest::Clear() { - id_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool CloseSessionRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.CloseSessionRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 id = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &id_))); - set_has_id(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.CloseSessionRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.CloseSessionRequest) - return false; -#undef DO_ -} - -void CloseSessionRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.CloseSessionRequest) - // required uint32 id = 1; - if (has_id()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->id(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.CloseSessionRequest) -} - -int CloseSessionRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 id = 1; - if (has_id()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->id()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void CloseSessionRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void CloseSessionRequest::MergeFrom(const CloseSessionRequest& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_id()) { - set_id(from.id()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void CloseSessionRequest::CopyFrom(const CloseSessionRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CloseSessionRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void CloseSessionRequest::Swap(CloseSessionRequest* other) { - if (other != this) { - std::swap(id_, other->id_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string CloseSessionRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.CloseSessionRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -#endif // !_MSC_VER - -CloseSessionResponse::CloseSessionResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.CloseSessionResponse) -} - -void CloseSessionResponse::InitAsDefaultInstance() { -} - -CloseSessionResponse::CloseSessionResponse(const CloseSessionResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.CloseSessionResponse) -} - -void CloseSessionResponse::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -CloseSessionResponse::~CloseSessionResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.CloseSessionResponse) - SharedDtor(); -} - -void CloseSessionResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void CloseSessionResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const CloseSessionResponse& CloseSessionResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -CloseSessionResponse* CloseSessionResponse::default_instance_ = NULL; - -CloseSessionResponse* CloseSessionResponse::New() const { - return new CloseSessionResponse; -} - -void CloseSessionResponse::Clear() { - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool CloseSessionResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.CloseSessionResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.CloseSessionResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.CloseSessionResponse) - return false; -#undef DO_ -} - -void CloseSessionResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.CloseSessionResponse) - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.CloseSessionResponse) -} - -int CloseSessionResponse::ByteSize() const { - int total_size = 0; - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void CloseSessionResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void CloseSessionResponse::MergeFrom(const CloseSessionResponse& from) { - GOOGLE_CHECK_NE(&from, this); - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void CloseSessionResponse::CopyFrom(const CloseSessionResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CloseSessionResponse::IsInitialized() const { - - return true; -} - -void CloseSessionResponse::Swap(CloseSessionResponse* other) { - if (other != this) { - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string CloseSessionResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.CloseSessionResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int NotifyRequest_Buffers::kSvaFieldNumber; -const int NotifyRequest_Buffers::kDataFieldNumber; -#endif // !_MSC_VER - -NotifyRequest_Buffers::NotifyRequest_Buffers() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.NotifyRequest.Buffers) -} - -void NotifyRequest_Buffers::InitAsDefaultInstance() { -} - -NotifyRequest_Buffers::NotifyRequest_Buffers(const NotifyRequest_Buffers& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.NotifyRequest.Buffers) -} - -void NotifyRequest_Buffers::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - sva_ = GOOGLE_ULONGLONG(0); - data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -NotifyRequest_Buffers::~NotifyRequest_Buffers() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.NotifyRequest.Buffers) - SharedDtor(); -} - -void NotifyRequest_Buffers::SharedDtor() { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete data_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void NotifyRequest_Buffers::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const NotifyRequest_Buffers& NotifyRequest_Buffers::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -NotifyRequest_Buffers* NotifyRequest_Buffers::default_instance_ = NULL; - -NotifyRequest_Buffers* NotifyRequest_Buffers::New() const { - return new NotifyRequest_Buffers; -} - -void NotifyRequest_Buffers::Clear() { - if (_has_bits_[0 / 32] & 3) { - sva_ = GOOGLE_ULONGLONG(0); - if (has_data()) { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool NotifyRequest_Buffers::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.NotifyRequest.Buffers) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint64 sva = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &sva_))); - set_has_sva(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_data; - break; - } - - // required bytes data = 2; - case 2: { - if (tag == 18) { - parse_data: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_data())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.NotifyRequest.Buffers) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.NotifyRequest.Buffers) - return false; -#undef DO_ -} - -void NotifyRequest_Buffers::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.NotifyRequest.Buffers) - // required uint64 sva = 1; - if (has_sva()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sva(), output); - } - - // required bytes data = 2; - if (has_data()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 2, this->data(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.NotifyRequest.Buffers) -} - -int NotifyRequest_Buffers::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint64 sva = 1; - if (has_sva()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->sva()); - } - - // required bytes data = 2; - if (has_data()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->data()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void NotifyRequest_Buffers::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void NotifyRequest_Buffers::MergeFrom(const NotifyRequest_Buffers& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sva()) { - set_sva(from.sva()); - } - if (from.has_data()) { - set_data(from.data()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void NotifyRequest_Buffers::CopyFrom(const NotifyRequest_Buffers& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool NotifyRequest_Buffers::IsInitialized() const { - if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; - - return true; -} - -void NotifyRequest_Buffers::Swap(NotifyRequest_Buffers* other) { - if (other != this) { - std::swap(sva_, other->sva_); - std::swap(data_, other->data_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string NotifyRequest_Buffers::GetTypeName() const { - return "com.trustonic.tee_proxy.NotifyRequest.Buffers"; -} - - -// ------------------------------------------------------------------- - -#ifndef _MSC_VER -const int NotifyRequest::kSidFieldNumber; -const int NotifyRequest::kTciFieldNumber; -const int NotifyRequest::kBuffersFieldNumber; -#endif // !_MSC_VER - -NotifyRequest::NotifyRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.NotifyRequest) -} - -void NotifyRequest::InitAsDefaultInstance() { -} - -NotifyRequest::NotifyRequest(const NotifyRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.NotifyRequest) -} - -void NotifyRequest::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - sid_ = 0u; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -NotifyRequest::~NotifyRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.NotifyRequest) - SharedDtor(); -} - -void NotifyRequest::SharedDtor() { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void NotifyRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const NotifyRequest& NotifyRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -NotifyRequest* NotifyRequest::default_instance_ = NULL; - -NotifyRequest* NotifyRequest::New() const { - return new NotifyRequest; -} - -void NotifyRequest::Clear() { - if (_has_bits_[0 / 32] & 3) { - sid_ = 0u; - if (has_tci()) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - } - } - buffers_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool NotifyRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.NotifyRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 sid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &sid_))); - set_has_sid(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_tci; - break; - } - - // optional bytes tci = 2; - case 2: { - if (tag == 18) { - parse_tci: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_tci())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_buffers; - break; - } - - // repeated .com.trustonic.tee_proxy.NotifyRequest.Buffers buffers = 3; - case 3: { - if (tag == 26) { - parse_buffers: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_buffers())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_buffers; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.NotifyRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.NotifyRequest) - return false; -#undef DO_ -} - -void NotifyRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.NotifyRequest) - // required uint32 sid = 1; - if (has_sid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->sid(), output); - } - - // optional bytes tci = 2; - if (has_tci()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 2, this->tci(), output); - } - - // repeated .com.trustonic.tee_proxy.NotifyRequest.Buffers buffers = 3; - for (int i = 0; i < this->buffers_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessage( - 3, this->buffers(i), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.NotifyRequest) -} - -int NotifyRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 sid = 1; - if (has_sid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->sid()); - } - - // optional bytes tci = 2; - if (has_tci()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->tci()); - } - - } - // repeated .com.trustonic.tee_proxy.NotifyRequest.Buffers buffers = 3; - total_size += 1 * this->buffers_size(); - for (int i = 0; i < this->buffers_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->buffers(i)); - } - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void NotifyRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void NotifyRequest::MergeFrom(const NotifyRequest& from) { - GOOGLE_CHECK_NE(&from, this); - buffers_.MergeFrom(from.buffers_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sid()) { - set_sid(from.sid()); - } - if (from.has_tci()) { - set_tci(from.tci()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void NotifyRequest::CopyFrom(const NotifyRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool NotifyRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - if (!::google::protobuf::internal::AllAreInitialized(this->buffers())) return false; - return true; -} - -void NotifyRequest::Swap(NotifyRequest* other) { - if (other != this) { - std::swap(sid_, other->sid_); - std::swap(tci_, other->tci_); - buffers_.Swap(&other->buffers_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string NotifyRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.NotifyRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -#endif // !_MSC_VER - -NotifyResponse::NotifyResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.NotifyResponse) -} - -void NotifyResponse::InitAsDefaultInstance() { -} - -NotifyResponse::NotifyResponse(const NotifyResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.NotifyResponse) -} - -void NotifyResponse::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -NotifyResponse::~NotifyResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.NotifyResponse) - SharedDtor(); -} - -void NotifyResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void NotifyResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const NotifyResponse& NotifyResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -NotifyResponse* NotifyResponse::default_instance_ = NULL; - -NotifyResponse* NotifyResponse::New() const { - return new NotifyResponse; -} - -void NotifyResponse::Clear() { - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool NotifyResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.NotifyResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.NotifyResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.NotifyResponse) - return false; -#undef DO_ -} - -void NotifyResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.NotifyResponse) - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.NotifyResponse) -} - -int NotifyResponse::ByteSize() const { - int total_size = 0; - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void NotifyResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void NotifyResponse::MergeFrom(const NotifyResponse& from) { - GOOGLE_CHECK_NE(&from, this); - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void NotifyResponse::CopyFrom(const NotifyResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool NotifyResponse::IsInitialized() const { - - return true; -} - -void NotifyResponse::Swap(NotifyResponse* other) { - if (other != this) { - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string NotifyResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.NotifyResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int WaitNotificationRequest::kSidFieldNumber; -const int WaitNotificationRequest::kTimeoutFieldNumber; -const int WaitNotificationRequest::kPartialFieldNumber; -#endif // !_MSC_VER - -WaitNotificationRequest::WaitNotificationRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.WaitNotificationRequest) -} - -void WaitNotificationRequest::InitAsDefaultInstance() { -} - -WaitNotificationRequest::WaitNotificationRequest(const WaitNotificationRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.WaitNotificationRequest) -} - -void WaitNotificationRequest::SharedCtor() { - _cached_size_ = 0; - sid_ = 0u; - timeout_ = 0; - partial_ = false; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -WaitNotificationRequest::~WaitNotificationRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.WaitNotificationRequest) - SharedDtor(); -} - -void WaitNotificationRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void WaitNotificationRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const WaitNotificationRequest& WaitNotificationRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -WaitNotificationRequest* WaitNotificationRequest::default_instance_ = NULL; - -WaitNotificationRequest* WaitNotificationRequest::New() const { - return new WaitNotificationRequest; -} - -void WaitNotificationRequest::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(sid_, partial_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool WaitNotificationRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.WaitNotificationRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 sid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &sid_))); - set_has_sid(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_timeout; - break; - } - - // required sint32 timeout = 2; - case 2: { - if (tag == 16) { - parse_timeout: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_SINT32>( - input, &timeout_))); - set_has_timeout(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(24)) goto parse_partial; - break; - } - - // required bool partial = 3; - case 3: { - if (tag == 24) { - parse_partial: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &partial_))); - set_has_partial(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.WaitNotificationRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.WaitNotificationRequest) - return false; -#undef DO_ -} - -void WaitNotificationRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.WaitNotificationRequest) - // required uint32 sid = 1; - if (has_sid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->sid(), output); - } - - // required sint32 timeout = 2; - if (has_timeout()) { - ::google::protobuf::internal::WireFormatLite::WriteSInt32(2, this->timeout(), output); - } - - // required bool partial = 3; - if (has_partial()) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->partial(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.WaitNotificationRequest) -} - -int WaitNotificationRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 sid = 1; - if (has_sid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->sid()); - } - - // required sint32 timeout = 2; - if (has_timeout()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::SInt32Size( - this->timeout()); - } - - // required bool partial = 3; - if (has_partial()) { - total_size += 1 + 1; - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void WaitNotificationRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void WaitNotificationRequest::MergeFrom(const WaitNotificationRequest& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sid()) { - set_sid(from.sid()); - } - if (from.has_timeout()) { - set_timeout(from.timeout()); - } - if (from.has_partial()) { - set_partial(from.partial()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void WaitNotificationRequest::CopyFrom(const WaitNotificationRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool WaitNotificationRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; - - return true; -} - -void WaitNotificationRequest::Swap(WaitNotificationRequest* other) { - if (other != this) { - std::swap(sid_, other->sid_); - std::swap(timeout_, other->timeout_); - std::swap(partial_, other->partial_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string WaitNotificationRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.WaitNotificationRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int WaitNotificationResponse_Buffers::kSvaFieldNumber; -const int WaitNotificationResponse_Buffers::kDataFieldNumber; -#endif // !_MSC_VER - -WaitNotificationResponse_Buffers::WaitNotificationResponse_Buffers() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) -} - -void WaitNotificationResponse_Buffers::InitAsDefaultInstance() { -} - -WaitNotificationResponse_Buffers::WaitNotificationResponse_Buffers(const WaitNotificationResponse_Buffers& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) -} - -void WaitNotificationResponse_Buffers::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - sva_ = GOOGLE_ULONGLONG(0); - data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -WaitNotificationResponse_Buffers::~WaitNotificationResponse_Buffers() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) - SharedDtor(); -} - -void WaitNotificationResponse_Buffers::SharedDtor() { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete data_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void WaitNotificationResponse_Buffers::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const WaitNotificationResponse_Buffers& WaitNotificationResponse_Buffers::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -WaitNotificationResponse_Buffers* WaitNotificationResponse_Buffers::default_instance_ = NULL; - -WaitNotificationResponse_Buffers* WaitNotificationResponse_Buffers::New() const { - return new WaitNotificationResponse_Buffers; -} - -void WaitNotificationResponse_Buffers::Clear() { - if (_has_bits_[0 / 32] & 3) { - sva_ = GOOGLE_ULONGLONG(0); - if (has_data()) { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool WaitNotificationResponse_Buffers::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint64 sva = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &sva_))); - set_has_sva(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_data; - break; - } - - // required bytes data = 2; - case 2: { - if (tag == 18) { - parse_data: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_data())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) - return false; -#undef DO_ -} - -void WaitNotificationResponse_Buffers::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) - // required uint64 sva = 1; - if (has_sva()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sva(), output); - } - - // required bytes data = 2; - if (has_data()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 2, this->data(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) -} - -int WaitNotificationResponse_Buffers::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint64 sva = 1; - if (has_sva()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->sva()); - } - - // required bytes data = 2; - if (has_data()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->data()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void WaitNotificationResponse_Buffers::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void WaitNotificationResponse_Buffers::MergeFrom(const WaitNotificationResponse_Buffers& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sva()) { - set_sva(from.sva()); - } - if (from.has_data()) { - set_data(from.data()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void WaitNotificationResponse_Buffers::CopyFrom(const WaitNotificationResponse_Buffers& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool WaitNotificationResponse_Buffers::IsInitialized() const { - if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; - - return true; -} - -void WaitNotificationResponse_Buffers::Swap(WaitNotificationResponse_Buffers* other) { - if (other != this) { - std::swap(sva_, other->sva_); - std::swap(data_, other->data_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string WaitNotificationResponse_Buffers::GetTypeName() const { - return "com.trustonic.tee_proxy.WaitNotificationResponse.Buffers"; -} - - -// ------------------------------------------------------------------- - -#ifndef _MSC_VER -const int WaitNotificationResponse::kTciFieldNumber; -const int WaitNotificationResponse::kBuffersFieldNumber; -#endif // !_MSC_VER - -WaitNotificationResponse::WaitNotificationResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.WaitNotificationResponse) -} - -void WaitNotificationResponse::InitAsDefaultInstance() { -} - -WaitNotificationResponse::WaitNotificationResponse(const WaitNotificationResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.WaitNotificationResponse) -} - -void WaitNotificationResponse::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -WaitNotificationResponse::~WaitNotificationResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.WaitNotificationResponse) - SharedDtor(); -} - -void WaitNotificationResponse::SharedDtor() { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void WaitNotificationResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const WaitNotificationResponse& WaitNotificationResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -WaitNotificationResponse* WaitNotificationResponse::default_instance_ = NULL; - -WaitNotificationResponse* WaitNotificationResponse::New() const { - return new WaitNotificationResponse; -} - -void WaitNotificationResponse::Clear() { - if (has_tci()) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - } - buffers_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool WaitNotificationResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.WaitNotificationResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional bytes tci = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_tci())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_buffers; - break; - } - - // repeated .com.trustonic.tee_proxy.WaitNotificationResponse.Buffers buffers = 2; - case 2: { - if (tag == 18) { - parse_buffers: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_buffers())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_buffers; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.WaitNotificationResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.WaitNotificationResponse) - return false; -#undef DO_ -} - -void WaitNotificationResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.WaitNotificationResponse) - // optional bytes tci = 1; - if (has_tci()) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 1, this->tci(), output); - } - - // repeated .com.trustonic.tee_proxy.WaitNotificationResponse.Buffers buffers = 2; - for (int i = 0; i < this->buffers_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessage( - 2, this->buffers(i), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.WaitNotificationResponse) -} - -int WaitNotificationResponse::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional bytes tci = 1; - if (has_tci()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->tci()); - } - - } - // repeated .com.trustonic.tee_proxy.WaitNotificationResponse.Buffers buffers = 2; - total_size += 1 * this->buffers_size(); - for (int i = 0; i < this->buffers_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->buffers(i)); - } - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void WaitNotificationResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void WaitNotificationResponse::MergeFrom(const WaitNotificationResponse& from) { - GOOGLE_CHECK_NE(&from, this); - buffers_.MergeFrom(from.buffers_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_tci()) { - set_tci(from.tci()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void WaitNotificationResponse::CopyFrom(const WaitNotificationResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool WaitNotificationResponse::IsInitialized() const { - - if (!::google::protobuf::internal::AllAreInitialized(this->buffers())) return false; - return true; -} - -void WaitNotificationResponse::Swap(WaitNotificationResponse* other) { - if (other != this) { - std::swap(tci_, other->tci_); - buffers_.Swap(&other->buffers_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string WaitNotificationResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.WaitNotificationResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int MapRequest_Buffers::kLenFieldNumber; -const int MapRequest_Buffers::kFlagsFieldNumber; -#endif // !_MSC_VER - -MapRequest_Buffers::MapRequest_Buffers() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.MapRequest.Buffers) -} - -void MapRequest_Buffers::InitAsDefaultInstance() { -} - -MapRequest_Buffers::MapRequest_Buffers(const MapRequest_Buffers& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.MapRequest.Buffers) -} - -void MapRequest_Buffers::SharedCtor() { - _cached_size_ = 0; - len_ = 0u; - flags_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MapRequest_Buffers::~MapRequest_Buffers() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.MapRequest.Buffers) - SharedDtor(); -} - -void MapRequest_Buffers::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void MapRequest_Buffers::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const MapRequest_Buffers& MapRequest_Buffers::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -MapRequest_Buffers* MapRequest_Buffers::default_instance_ = NULL; - -MapRequest_Buffers* MapRequest_Buffers::New() const { - return new MapRequest_Buffers; -} - -void MapRequest_Buffers::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(len_, flags_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool MapRequest_Buffers::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.MapRequest.Buffers) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 len = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &len_))); - set_has_len(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_flags; - break; - } - - // required uint32 flags = 2; - case 2: { - if (tag == 16) { - parse_flags: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &flags_))); - set_has_flags(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.MapRequest.Buffers) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.MapRequest.Buffers) - return false; -#undef DO_ -} - -void MapRequest_Buffers::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.MapRequest.Buffers) - // required uint32 len = 1; - if (has_len()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->len(), output); - } - - // required uint32 flags = 2; - if (has_flags()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->flags(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.MapRequest.Buffers) -} - -int MapRequest_Buffers::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 len = 1; - if (has_len()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->len()); - } - - // required uint32 flags = 2; - if (has_flags()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->flags()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MapRequest_Buffers::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void MapRequest_Buffers::MergeFrom(const MapRequest_Buffers& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_len()) { - set_len(from.len()); - } - if (from.has_flags()) { - set_flags(from.flags()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void MapRequest_Buffers::CopyFrom(const MapRequest_Buffers& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MapRequest_Buffers::IsInitialized() const { - if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; - - return true; -} - -void MapRequest_Buffers::Swap(MapRequest_Buffers* other) { - if (other != this) { - std::swap(len_, other->len_); - std::swap(flags_, other->flags_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string MapRequest_Buffers::GetTypeName() const { - return "com.trustonic.tee_proxy.MapRequest.Buffers"; -} - - -// ------------------------------------------------------------------- - -#ifndef _MSC_VER -const int MapRequest::kSidFieldNumber; -const int MapRequest::kBuffersFieldNumber; -#endif // !_MSC_VER - -MapRequest::MapRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.MapRequest) -} - -void MapRequest::InitAsDefaultInstance() { -} - -MapRequest::MapRequest(const MapRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.MapRequest) -} - -void MapRequest::SharedCtor() { - _cached_size_ = 0; - sid_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MapRequest::~MapRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.MapRequest) - SharedDtor(); -} - -void MapRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void MapRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const MapRequest& MapRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -MapRequest* MapRequest::default_instance_ = NULL; - -MapRequest* MapRequest::New() const { - return new MapRequest; -} - -void MapRequest::Clear() { - sid_ = 0u; - buffers_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool MapRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.MapRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 sid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &sid_))); - set_has_sid(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_buffers; - break; - } - - // repeated .com.trustonic.tee_proxy.MapRequest.Buffers buffers = 2; - case 2: { - if (tag == 18) { - parse_buffers: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_buffers())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_buffers; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.MapRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.MapRequest) - return false; -#undef DO_ -} - -void MapRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.MapRequest) - // required uint32 sid = 1; - if (has_sid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->sid(), output); - } - - // repeated .com.trustonic.tee_proxy.MapRequest.Buffers buffers = 2; - for (int i = 0; i < this->buffers_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessage( - 2, this->buffers(i), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.MapRequest) -} - -int MapRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 sid = 1; - if (has_sid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->sid()); - } - - } - // repeated .com.trustonic.tee_proxy.MapRequest.Buffers buffers = 2; - total_size += 1 * this->buffers_size(); - for (int i = 0; i < this->buffers_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->buffers(i)); - } - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MapRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void MapRequest::MergeFrom(const MapRequest& from) { - GOOGLE_CHECK_NE(&from, this); - buffers_.MergeFrom(from.buffers_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sid()) { - set_sid(from.sid()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void MapRequest::CopyFrom(const MapRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MapRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - if (!::google::protobuf::internal::AllAreInitialized(this->buffers())) return false; - return true; -} - -void MapRequest::Swap(MapRequest* other) { - if (other != this) { - std::swap(sid_, other->sid_); - buffers_.Swap(&other->buffers_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string MapRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.MapRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int MapResponse_Buffers::kSvaFieldNumber; -#endif // !_MSC_VER - -MapResponse_Buffers::MapResponse_Buffers() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.MapResponse.Buffers) -} - -void MapResponse_Buffers::InitAsDefaultInstance() { -} - -MapResponse_Buffers::MapResponse_Buffers(const MapResponse_Buffers& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.MapResponse.Buffers) -} - -void MapResponse_Buffers::SharedCtor() { - _cached_size_ = 0; - sva_ = GOOGLE_ULONGLONG(0); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MapResponse_Buffers::~MapResponse_Buffers() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.MapResponse.Buffers) - SharedDtor(); -} - -void MapResponse_Buffers::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void MapResponse_Buffers::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const MapResponse_Buffers& MapResponse_Buffers::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -MapResponse_Buffers* MapResponse_Buffers::default_instance_ = NULL; - -MapResponse_Buffers* MapResponse_Buffers::New() const { - return new MapResponse_Buffers; -} - -void MapResponse_Buffers::Clear() { - sva_ = GOOGLE_ULONGLONG(0); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool MapResponse_Buffers::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.MapResponse.Buffers) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint64 sva = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &sva_))); - set_has_sva(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.MapResponse.Buffers) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.MapResponse.Buffers) - return false; -#undef DO_ -} - -void MapResponse_Buffers::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.MapResponse.Buffers) - // required uint64 sva = 1; - if (has_sva()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sva(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.MapResponse.Buffers) -} - -int MapResponse_Buffers::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint64 sva = 1; - if (has_sva()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->sva()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MapResponse_Buffers::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void MapResponse_Buffers::MergeFrom(const MapResponse_Buffers& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sva()) { - set_sva(from.sva()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void MapResponse_Buffers::CopyFrom(const MapResponse_Buffers& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MapResponse_Buffers::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void MapResponse_Buffers::Swap(MapResponse_Buffers* other) { - if (other != this) { - std::swap(sva_, other->sva_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string MapResponse_Buffers::GetTypeName() const { - return "com.trustonic.tee_proxy.MapResponse.Buffers"; -} - - -// ------------------------------------------------------------------- - -#ifndef _MSC_VER -const int MapResponse::kBuffersFieldNumber; -#endif // !_MSC_VER - -MapResponse::MapResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.MapResponse) -} - -void MapResponse::InitAsDefaultInstance() { -} - -MapResponse::MapResponse(const MapResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.MapResponse) -} - -void MapResponse::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MapResponse::~MapResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.MapResponse) - SharedDtor(); -} - -void MapResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void MapResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const MapResponse& MapResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -MapResponse* MapResponse::default_instance_ = NULL; - -MapResponse* MapResponse::New() const { - return new MapResponse; -} - -void MapResponse::Clear() { - buffers_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool MapResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.MapResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .com.trustonic.tee_proxy.MapResponse.Buffers buffers = 1; - case 1: { - if (tag == 10) { - parse_buffers: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_buffers())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(10)) goto parse_buffers; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.MapResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.MapResponse) - return false; -#undef DO_ -} - -void MapResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.MapResponse) - // repeated .com.trustonic.tee_proxy.MapResponse.Buffers buffers = 1; - for (int i = 0; i < this->buffers_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessage( - 1, this->buffers(i), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.MapResponse) -} - -int MapResponse::ByteSize() const { - int total_size = 0; - - // repeated .com.trustonic.tee_proxy.MapResponse.Buffers buffers = 1; - total_size += 1 * this->buffers_size(); - for (int i = 0; i < this->buffers_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->buffers(i)); - } - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MapResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void MapResponse::MergeFrom(const MapResponse& from) { - GOOGLE_CHECK_NE(&from, this); - buffers_.MergeFrom(from.buffers_); - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void MapResponse::CopyFrom(const MapResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MapResponse::IsInitialized() const { - - if (!::google::protobuf::internal::AllAreInitialized(this->buffers())) return false; - return true; -} - -void MapResponse::Swap(MapResponse* other) { - if (other != this) { - buffers_.Swap(&other->buffers_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string MapResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.MapResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int UnmapRequest_Buffers::kSvaFieldNumber; -#endif // !_MSC_VER - -UnmapRequest_Buffers::UnmapRequest_Buffers() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.UnmapRequest.Buffers) -} - -void UnmapRequest_Buffers::InitAsDefaultInstance() { -} - -UnmapRequest_Buffers::UnmapRequest_Buffers(const UnmapRequest_Buffers& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.UnmapRequest.Buffers) -} - -void UnmapRequest_Buffers::SharedCtor() { - _cached_size_ = 0; - sva_ = GOOGLE_ULONGLONG(0); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -UnmapRequest_Buffers::~UnmapRequest_Buffers() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.UnmapRequest.Buffers) - SharedDtor(); -} - -void UnmapRequest_Buffers::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void UnmapRequest_Buffers::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const UnmapRequest_Buffers& UnmapRequest_Buffers::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -UnmapRequest_Buffers* UnmapRequest_Buffers::default_instance_ = NULL; - -UnmapRequest_Buffers* UnmapRequest_Buffers::New() const { - return new UnmapRequest_Buffers; -} - -void UnmapRequest_Buffers::Clear() { - sva_ = GOOGLE_ULONGLONG(0); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool UnmapRequest_Buffers::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.UnmapRequest.Buffers) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint64 sva = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &sva_))); - set_has_sva(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.UnmapRequest.Buffers) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.UnmapRequest.Buffers) - return false; -#undef DO_ -} - -void UnmapRequest_Buffers::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.UnmapRequest.Buffers) - // required uint64 sva = 1; - if (has_sva()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sva(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.UnmapRequest.Buffers) -} - -int UnmapRequest_Buffers::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint64 sva = 1; - if (has_sva()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->sva()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void UnmapRequest_Buffers::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void UnmapRequest_Buffers::MergeFrom(const UnmapRequest_Buffers& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sva()) { - set_sva(from.sva()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void UnmapRequest_Buffers::CopyFrom(const UnmapRequest_Buffers& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool UnmapRequest_Buffers::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void UnmapRequest_Buffers::Swap(UnmapRequest_Buffers* other) { - if (other != this) { - std::swap(sva_, other->sva_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string UnmapRequest_Buffers::GetTypeName() const { - return "com.trustonic.tee_proxy.UnmapRequest.Buffers"; -} - - -// ------------------------------------------------------------------- - -#ifndef _MSC_VER -const int UnmapRequest::kSidFieldNumber; -const int UnmapRequest::kBuffersFieldNumber; -#endif // !_MSC_VER - -UnmapRequest::UnmapRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.UnmapRequest) -} - -void UnmapRequest::InitAsDefaultInstance() { -} - -UnmapRequest::UnmapRequest(const UnmapRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.UnmapRequest) -} - -void UnmapRequest::SharedCtor() { - _cached_size_ = 0; - sid_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -UnmapRequest::~UnmapRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.UnmapRequest) - SharedDtor(); -} - -void UnmapRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void UnmapRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const UnmapRequest& UnmapRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -UnmapRequest* UnmapRequest::default_instance_ = NULL; - -UnmapRequest* UnmapRequest::New() const { - return new UnmapRequest; -} - -void UnmapRequest::Clear() { - sid_ = 0u; - buffers_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool UnmapRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.UnmapRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 sid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &sid_))); - set_has_sid(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_buffers; - break; - } - - // repeated .com.trustonic.tee_proxy.UnmapRequest.Buffers buffers = 2; - case 2: { - if (tag == 18) { - parse_buffers: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_buffers())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_buffers; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.UnmapRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.UnmapRequest) - return false; -#undef DO_ -} - -void UnmapRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.UnmapRequest) - // required uint32 sid = 1; - if (has_sid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->sid(), output); - } - - // repeated .com.trustonic.tee_proxy.UnmapRequest.Buffers buffers = 2; - for (int i = 0; i < this->buffers_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessage( - 2, this->buffers(i), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.UnmapRequest) -} - -int UnmapRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 sid = 1; - if (has_sid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->sid()); - } - - } - // repeated .com.trustonic.tee_proxy.UnmapRequest.Buffers buffers = 2; - total_size += 1 * this->buffers_size(); - for (int i = 0; i < this->buffers_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->buffers(i)); - } - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void UnmapRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void UnmapRequest::MergeFrom(const UnmapRequest& from) { - GOOGLE_CHECK_NE(&from, this); - buffers_.MergeFrom(from.buffers_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sid()) { - set_sid(from.sid()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void UnmapRequest::CopyFrom(const UnmapRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool UnmapRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - if (!::google::protobuf::internal::AllAreInitialized(this->buffers())) return false; - return true; -} - -void UnmapRequest::Swap(UnmapRequest* other) { - if (other != this) { - std::swap(sid_, other->sid_); - buffers_.Swap(&other->buffers_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string UnmapRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.UnmapRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -#endif // !_MSC_VER - -UnmapResponse::UnmapResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.UnmapResponse) -} - -void UnmapResponse::InitAsDefaultInstance() { -} - -UnmapResponse::UnmapResponse(const UnmapResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.UnmapResponse) -} - -void UnmapResponse::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -UnmapResponse::~UnmapResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.UnmapResponse) - SharedDtor(); -} - -void UnmapResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void UnmapResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const UnmapResponse& UnmapResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -UnmapResponse* UnmapResponse::default_instance_ = NULL; - -UnmapResponse* UnmapResponse::New() const { - return new UnmapResponse; -} - -void UnmapResponse::Clear() { - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool UnmapResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.UnmapResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.UnmapResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.UnmapResponse) - return false; -#undef DO_ -} - -void UnmapResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.UnmapResponse) - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.UnmapResponse) -} - -int UnmapResponse::ByteSize() const { - int total_size = 0; - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void UnmapResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void UnmapResponse::MergeFrom(const UnmapResponse& from) { - GOOGLE_CHECK_NE(&from, this); - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void UnmapResponse::CopyFrom(const UnmapResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool UnmapResponse::IsInitialized() const { - - return true; -} - -void UnmapResponse::Swap(UnmapResponse* other) { - if (other != this) { - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string UnmapResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.UnmapResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int GetErrorRequest::kSidFieldNumber; -#endif // !_MSC_VER - -GetErrorRequest::GetErrorRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.GetErrorRequest) -} - -void GetErrorRequest::InitAsDefaultInstance() { -} - -GetErrorRequest::GetErrorRequest(const GetErrorRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.GetErrorRequest) -} - -void GetErrorRequest::SharedCtor() { - _cached_size_ = 0; - sid_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -GetErrorRequest::~GetErrorRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.GetErrorRequest) - SharedDtor(); -} - -void GetErrorRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void GetErrorRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const GetErrorRequest& GetErrorRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -GetErrorRequest* GetErrorRequest::default_instance_ = NULL; - -GetErrorRequest* GetErrorRequest::New() const { - return new GetErrorRequest; -} - -void GetErrorRequest::Clear() { - sid_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool GetErrorRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.GetErrorRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 sid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &sid_))); - set_has_sid(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.GetErrorRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.GetErrorRequest) - return false; -#undef DO_ -} - -void GetErrorRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.GetErrorRequest) - // required uint32 sid = 1; - if (has_sid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->sid(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.GetErrorRequest) -} - -int GetErrorRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 sid = 1; - if (has_sid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->sid()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void GetErrorRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void GetErrorRequest::MergeFrom(const GetErrorRequest& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sid()) { - set_sid(from.sid()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void GetErrorRequest::CopyFrom(const GetErrorRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool GetErrorRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void GetErrorRequest::Swap(GetErrorRequest* other) { - if (other != this) { - std::swap(sid_, other->sid_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string GetErrorRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.GetErrorRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int GetErrorResponse::kExitCodeFieldNumber; -#endif // !_MSC_VER - -GetErrorResponse::GetErrorResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.GetErrorResponse) -} - -void GetErrorResponse::InitAsDefaultInstance() { -} - -GetErrorResponse::GetErrorResponse(const GetErrorResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.GetErrorResponse) -} - -void GetErrorResponse::SharedCtor() { - _cached_size_ = 0; - exit_code_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -GetErrorResponse::~GetErrorResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.GetErrorResponse) - SharedDtor(); -} - -void GetErrorResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void GetErrorResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const GetErrorResponse& GetErrorResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -GetErrorResponse* GetErrorResponse::default_instance_ = NULL; - -GetErrorResponse* GetErrorResponse::New() const { - return new GetErrorResponse; -} - -void GetErrorResponse::Clear() { - exit_code_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool GetErrorResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.GetErrorResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required sint32 exit_code = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_SINT32>( - input, &exit_code_))); - set_has_exit_code(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.GetErrorResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.GetErrorResponse) - return false; -#undef DO_ -} - -void GetErrorResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.GetErrorResponse) - // required sint32 exit_code = 1; - if (has_exit_code()) { - ::google::protobuf::internal::WireFormatLite::WriteSInt32(1, this->exit_code(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.GetErrorResponse) -} - -int GetErrorResponse::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required sint32 exit_code = 1; - if (has_exit_code()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::SInt32Size( - this->exit_code()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void GetErrorResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void GetErrorResponse::MergeFrom(const GetErrorResponse& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_exit_code()) { - set_exit_code(from.exit_code()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void GetErrorResponse::CopyFrom(const GetErrorResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool GetErrorResponse::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void GetErrorResponse::Swap(GetErrorResponse* other) { - if (other != this) { - std::swap(exit_code_, other->exit_code_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string GetErrorResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.GetErrorResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -#endif // !_MSC_VER - -GetVersionRequest::GetVersionRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.GetVersionRequest) -} - -void GetVersionRequest::InitAsDefaultInstance() { -} - -GetVersionRequest::GetVersionRequest(const GetVersionRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.GetVersionRequest) -} - -void GetVersionRequest::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -GetVersionRequest::~GetVersionRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.GetVersionRequest) - SharedDtor(); -} - -void GetVersionRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void GetVersionRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const GetVersionRequest& GetVersionRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -GetVersionRequest* GetVersionRequest::default_instance_ = NULL; - -GetVersionRequest* GetVersionRequest::New() const { - return new GetVersionRequest; -} - -void GetVersionRequest::Clear() { - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool GetVersionRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.GetVersionRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.GetVersionRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.GetVersionRequest) - return false; -#undef DO_ -} - -void GetVersionRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.GetVersionRequest) - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.GetVersionRequest) -} - -int GetVersionRequest::ByteSize() const { - int total_size = 0; - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void GetVersionRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void GetVersionRequest::MergeFrom(const GetVersionRequest& from) { - GOOGLE_CHECK_NE(&from, this); - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void GetVersionRequest::CopyFrom(const GetVersionRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool GetVersionRequest::IsInitialized() const { - - return true; -} - -void GetVersionRequest::Swap(GetVersionRequest* other) { - if (other != this) { - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string GetVersionRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.GetVersionRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int GetVersionResponse::kProductIdFieldNumber; -const int GetVersionResponse::kMciFieldNumber; -const int GetVersionResponse::kSoFieldNumber; -const int GetVersionResponse::kMclfFieldNumber; -const int GetVersionResponse::kContainerFieldNumber; -const int GetVersionResponse::kMcConfigFieldNumber; -const int GetVersionResponse::kTlApiFieldNumber; -const int GetVersionResponse::kDrApiFieldNumber; -const int GetVersionResponse::kNwdFieldNumber; -#endif // !_MSC_VER - -GetVersionResponse::GetVersionResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.GetVersionResponse) -} - -void GetVersionResponse::InitAsDefaultInstance() { -} - -GetVersionResponse::GetVersionResponse(const GetVersionResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.GetVersionResponse) -} - -void GetVersionResponse::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - product_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - mci_ = 0u; - so_ = 0u; - mclf_ = 0u; - container_ = 0u; - mc_config_ = 0u; - tl_api_ = 0u; - dr_api_ = 0u; - nwd_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -GetVersionResponse::~GetVersionResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.GetVersionResponse) - SharedDtor(); -} - -void GetVersionResponse::SharedDtor() { - if (product_id_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete product_id_; - } - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void GetVersionResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const GetVersionResponse& GetVersionResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -GetVersionResponse* GetVersionResponse::default_instance_ = NULL; - -GetVersionResponse* GetVersionResponse::New() const { - return new GetVersionResponse; -} - -void GetVersionResponse::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - if (_has_bits_[0 / 32] & 255) { - ZR_(mci_, dr_api_); - if (has_product_id()) { - if (product_id_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - product_id_->clear(); - } - } - } - nwd_ = 0u; - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool GetVersionResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.GetVersionResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required string product_id = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_product_id())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_mci; - break; - } - - // required uint32 mci = 2; - case 2: { - if (tag == 16) { - parse_mci: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &mci_))); - set_has_mci(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(24)) goto parse_so; - break; - } - - // required uint32 so = 3; - case 3: { - if (tag == 24) { - parse_so: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &so_))); - set_has_so(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(32)) goto parse_mclf; - break; - } - - // required uint32 mclf = 4; - case 4: { - if (tag == 32) { - parse_mclf: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &mclf_))); - set_has_mclf(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(40)) goto parse_container; - break; - } - - // required uint32 container = 5; - case 5: { - if (tag == 40) { - parse_container: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &container_))); - set_has_container(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(48)) goto parse_mc_config; - break; - } - - // required uint32 mc_config = 6; - case 6: { - if (tag == 48) { - parse_mc_config: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &mc_config_))); - set_has_mc_config(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(56)) goto parse_tl_api; - break; - } - - // required uint32 tl_api = 7; - case 7: { - if (tag == 56) { - parse_tl_api: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &tl_api_))); - set_has_tl_api(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(64)) goto parse_dr_api; - break; - } - - // required uint32 dr_api = 8; - case 8: { - if (tag == 64) { - parse_dr_api: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &dr_api_))); - set_has_dr_api(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(72)) goto parse_nwd; - break; - } - - // required uint32 nwd = 9; - case 9: { - if (tag == 72) { - parse_nwd: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &nwd_))); - set_has_nwd(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.GetVersionResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.GetVersionResponse) - return false; -#undef DO_ -} - -void GetVersionResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.GetVersionResponse) - // required string product_id = 1; - if (has_product_id()) { - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->product_id(), output); - } - - // required uint32 mci = 2; - if (has_mci()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->mci(), output); - } - - // required uint32 so = 3; - if (has_so()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->so(), output); - } - - // required uint32 mclf = 4; - if (has_mclf()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->mclf(), output); - } - - // required uint32 container = 5; - if (has_container()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->container(), output); - } - - // required uint32 mc_config = 6; - if (has_mc_config()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->mc_config(), output); - } - - // required uint32 tl_api = 7; - if (has_tl_api()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(7, this->tl_api(), output); - } - - // required uint32 dr_api = 8; - if (has_dr_api()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(8, this->dr_api(), output); - } - - // required uint32 nwd = 9; - if (has_nwd()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(9, this->nwd(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.GetVersionResponse) -} - -int GetVersionResponse::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required string product_id = 1; - if (has_product_id()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->product_id()); - } - - // required uint32 mci = 2; - if (has_mci()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->mci()); - } - - // required uint32 so = 3; - if (has_so()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->so()); - } - - // required uint32 mclf = 4; - if (has_mclf()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->mclf()); - } - - // required uint32 container = 5; - if (has_container()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->container()); - } - - // required uint32 mc_config = 6; - if (has_mc_config()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->mc_config()); - } - - // required uint32 tl_api = 7; - if (has_tl_api()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->tl_api()); - } - - // required uint32 dr_api = 8; - if (has_dr_api()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->dr_api()); - } - - } - if (_has_bits_[8 / 32] & (0xffu << (8 % 32))) { - // required uint32 nwd = 9; - if (has_nwd()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->nwd()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void GetVersionResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void GetVersionResponse::MergeFrom(const GetVersionResponse& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_product_id()) { - set_product_id(from.product_id()); - } - if (from.has_mci()) { - set_mci(from.mci()); - } - if (from.has_so()) { - set_so(from.so()); - } - if (from.has_mclf()) { - set_mclf(from.mclf()); - } - if (from.has_container()) { - set_container(from.container()); - } - if (from.has_mc_config()) { - set_mc_config(from.mc_config()); - } - if (from.has_tl_api()) { - set_tl_api(from.tl_api()); - } - if (from.has_dr_api()) { - set_dr_api(from.dr_api()); - } - } - if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) { - if (from.has_nwd()) { - set_nwd(from.nwd()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void GetVersionResponse::CopyFrom(const GetVersionResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool GetVersionResponse::IsInitialized() const { - if ((_has_bits_[0] & 0x000001ff) != 0x000001ff) return false; - - return true; -} - -void GetVersionResponse::Swap(GetVersionResponse* other) { - if (other != this) { - std::swap(product_id_, other->product_id_); - std::swap(mci_, other->mci_); - std::swap(so_, other->so_); - std::swap(mclf_, other->mclf_); - std::swap(container_, other->container_); - std::swap(mc_config_, other->mc_config_); - std::swap(tl_api_, other->tl_api_); - std::swap(dr_api_, other->dr_api_); - std::swap(nwd_, other->nwd_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string GetVersionResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.GetVersionResponse"; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int GpRequestCancellationRequest::kSidFieldNumber; -#endif // !_MSC_VER - -GpRequestCancellationRequest::GpRequestCancellationRequest() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.GpRequestCancellationRequest) -} - -void GpRequestCancellationRequest::InitAsDefaultInstance() { -} - -GpRequestCancellationRequest::GpRequestCancellationRequest(const GpRequestCancellationRequest& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.GpRequestCancellationRequest) -} - -void GpRequestCancellationRequest::SharedCtor() { - _cached_size_ = 0; - sid_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -GpRequestCancellationRequest::~GpRequestCancellationRequest() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.GpRequestCancellationRequest) - SharedDtor(); -} - -void GpRequestCancellationRequest::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void GpRequestCancellationRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const GpRequestCancellationRequest& GpRequestCancellationRequest::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -GpRequestCancellationRequest* GpRequestCancellationRequest::default_instance_ = NULL; - -GpRequestCancellationRequest* GpRequestCancellationRequest::New() const { - return new GpRequestCancellationRequest; -} - -void GpRequestCancellationRequest::Clear() { - sid_ = 0u; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool GpRequestCancellationRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.GpRequestCancellationRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required uint32 sid = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &sid_))); - set_has_sid(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.GpRequestCancellationRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.GpRequestCancellationRequest) - return false; -#undef DO_ -} - -void GpRequestCancellationRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.GpRequestCancellationRequest) - // required uint32 sid = 1; - if (has_sid()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->sid(), output); - } - - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.GpRequestCancellationRequest) -} - -int GpRequestCancellationRequest::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required uint32 sid = 1; - if (has_sid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->sid()); - } - - } - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void GpRequestCancellationRequest::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void GpRequestCancellationRequest::MergeFrom(const GpRequestCancellationRequest& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sid()) { - set_sid(from.sid()); - } - } - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void GpRequestCancellationRequest::CopyFrom(const GpRequestCancellationRequest& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool GpRequestCancellationRequest::IsInitialized() const { - if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; - - return true; -} - -void GpRequestCancellationRequest::Swap(GpRequestCancellationRequest* other) { - if (other != this) { - std::swap(sid_, other->sid_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string GpRequestCancellationRequest::GetTypeName() const { - return "com.trustonic.tee_proxy.GpRequestCancellationRequest"; -} - - -// =================================================================== - -#ifndef _MSC_VER -#endif // !_MSC_VER - -GpRequestCancellationResponse::GpRequestCancellationResponse() - : ::google::protobuf::MessageLite() { - SharedCtor(); - // @@protoc_insertion_point(constructor:com.trustonic.tee_proxy.GpRequestCancellationResponse) -} - -void GpRequestCancellationResponse::InitAsDefaultInstance() { -} - -GpRequestCancellationResponse::GpRequestCancellationResponse(const GpRequestCancellationResponse& from) - : ::google::protobuf::MessageLite() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:com.trustonic.tee_proxy.GpRequestCancellationResponse) -} - -void GpRequestCancellationResponse::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -GpRequestCancellationResponse::~GpRequestCancellationResponse() { - // @@protoc_insertion_point(destructor:com.trustonic.tee_proxy.GpRequestCancellationResponse) - SharedDtor(); -} - -void GpRequestCancellationResponse::SharedDtor() { - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - if (this != &default_instance()) { - #else - if (this != default_instance_) { - #endif - } -} - -void GpRequestCancellationResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const GpRequestCancellationResponse& GpRequestCancellationResponse::default_instance() { -#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - protobuf_AddDesc_mc_2eproto(); -#else - if (default_instance_ == NULL) protobuf_AddDesc_mc_2eproto(); -#endif - return *default_instance_; -} - -GpRequestCancellationResponse* GpRequestCancellationResponse::default_instance_ = NULL; - -GpRequestCancellationResponse* GpRequestCancellationResponse::New() const { - return new GpRequestCancellationResponse; -} - -void GpRequestCancellationResponse::Clear() { - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->clear(); -} - -bool GpRequestCancellationResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - ::google::protobuf::io::StringOutputStream unknown_fields_string( - mutable_unknown_fields()); - ::google::protobuf::io::CodedOutputStream unknown_fields_stream( - &unknown_fields_string); - // @@protoc_insertion_point(parse_start:com.trustonic.tee_proxy.GpRequestCancellationResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField( - input, tag, &unknown_fields_stream)); - } -success: - // @@protoc_insertion_point(parse_success:com.trustonic.tee_proxy.GpRequestCancellationResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:com.trustonic.tee_proxy.GpRequestCancellationResponse) - return false; -#undef DO_ -} - -void GpRequestCancellationResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:com.trustonic.tee_proxy.GpRequestCancellationResponse) - output->WriteRaw(unknown_fields().data(), - unknown_fields().size()); - // @@protoc_insertion_point(serialize_end:com.trustonic.tee_proxy.GpRequestCancellationResponse) -} - -int GpRequestCancellationResponse::ByteSize() const { - int total_size = 0; - - total_size += unknown_fields().size(); - - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void GpRequestCancellationResponse::CheckTypeAndMergeFrom( - const ::google::protobuf::MessageLite& from) { - MergeFrom(*::google::protobuf::down_cast(&from)); -} - -void GpRequestCancellationResponse::MergeFrom(const GpRequestCancellationResponse& from) { - GOOGLE_CHECK_NE(&from, this); - mutable_unknown_fields()->append(from.unknown_fields()); -} - -void GpRequestCancellationResponse::CopyFrom(const GpRequestCancellationResponse& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool GpRequestCancellationResponse::IsInitialized() const { - - return true; -} - -void GpRequestCancellationResponse::Swap(GpRequestCancellationResponse* other) { - if (other != this) { - _unknown_fields_.swap(other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::std::string GpRequestCancellationResponse::GetTypeName() const { - return "com.trustonic.tee_proxy.GpRequestCancellationResponse"; -} - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace tee_proxy -} // namespace trustonic -} // namespace com - -// @@protoc_insertion_point(global_scope) diff --git a/mobicore/ClientLib/src/mc.pb.h b/mobicore/ClientLib/src/mc.pb.h deleted file mode 100644 index dabb10b..0000000 --- a/mobicore/ClientLib/src/mc.pb.h +++ /dev/null @@ -1,4365 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: mc.proto - -#ifndef PROTOBUF_mc_2eproto__INCLUDED -#define PROTOBUF_mc_2eproto__INCLUDED - -#include - -#include - -#if GOOGLE_PROTOBUF_VERSION < 2006000 -#warning This file was generated by a newer version of protoc which is -#warning incompatible with your Protocol Buffer headers. Please update -#warning your headers. -#endif -#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION -#warning This file was generated by an older version of protoc which is -#warning incompatible with your Protocol Buffer headers. Please -#warning regenerate this file with a newer version of protoc. -#endif - -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace com { -namespace trustonic { -namespace tee_proxy { - -// Internal implementation detail -- do not call these. -void protobuf_AddDesc_mc_2eproto(); -void protobuf_AssignDesc_mc_2eproto(); -void protobuf_ShutdownFile_mc_2eproto(); - -class OpenSessionRequest; -class OpenSessionResponse; -class OpenTrustletRequest; -class OpenTrustletResponse; -class CloseSessionRequest; -class CloseSessionResponse; -class NotifyRequest; -class NotifyRequest_Buffers; -class NotifyResponse; -class WaitNotificationRequest; -class WaitNotificationResponse; -class WaitNotificationResponse_Buffers; -class MapRequest; -class MapRequest_Buffers; -class MapResponse; -class MapResponse_Buffers; -class UnmapRequest; -class UnmapRequest_Buffers; -class UnmapResponse; -class GetErrorRequest; -class GetErrorResponse; -class GetVersionRequest; -class GetVersionResponse; -class GpRequestCancellationRequest; -class GpRequestCancellationResponse; - -enum LoginType { - TEEC_LOGIN_PUBLIC = 0, - TEEC_LOGIN_USER = 1, - TEEC_LOGIN_GROUP = 2, - TEEC_LOGIN_APPLICATION = 4, - TEEC_LOGIN_USER_APPLICATION = 5, - TEEC_LOGIN_GROUP_APPLICATION = 6 -}; -bool LoginType_IsValid(int value); -const LoginType LoginType_MIN = TEEC_LOGIN_PUBLIC; -const LoginType LoginType_MAX = TEEC_LOGIN_GROUP_APPLICATION; -const int LoginType_ARRAYSIZE = LoginType_MAX + 1; - -// =================================================================== - -class OpenSessionRequest : public ::google::protobuf::MessageLite { - public: - OpenSessionRequest(); - virtual ~OpenSessionRequest(); - - OpenSessionRequest(const OpenSessionRequest& from); - - inline OpenSessionRequest& operator=(const OpenSessionRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const OpenSessionRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const OpenSessionRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(OpenSessionRequest* other); - - // implements Message ---------------------------------------------- - - OpenSessionRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const OpenSessionRequest& from); - void MergeFrom(const OpenSessionRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required bytes uuid = 1; - inline bool has_uuid() const; - inline void clear_uuid(); - static const int kUuidFieldNumber = 1; - inline const ::std::string& uuid() const; - inline void set_uuid(const ::std::string& value); - inline void set_uuid(const char* value); - inline void set_uuid(const void* value, size_t size); - inline ::std::string* mutable_uuid(); - inline ::std::string* release_uuid(); - inline void set_allocated_uuid(::std::string* uuid); - - // required bool is_gp_uuid = 2; - inline bool has_is_gp_uuid() const; - inline void clear_is_gp_uuid(); - static const int kIsGpUuidFieldNumber = 2; - inline bool is_gp_uuid() const; - inline void set_is_gp_uuid(bool value); - - // optional bytes tci = 3; - inline bool has_tci() const; - inline void clear_tci(); - static const int kTciFieldNumber = 3; - inline const ::std::string& tci() const; - inline void set_tci(const ::std::string& value); - inline void set_tci(const char* value); - inline void set_tci(const void* value, size_t size); - inline ::std::string* mutable_tci(); - inline ::std::string* release_tci(); - inline void set_allocated_tci(::std::string* tci); - - // required .com.trustonic.tee_proxy.LoginType login_type = 4; - inline bool has_login_type() const; - inline void clear_login_type(); - static const int kLoginTypeFieldNumber = 4; - inline ::com::trustonic::tee_proxy::LoginType login_type() const; - inline void set_login_type(::com::trustonic::tee_proxy::LoginType value); - - // required bytes login_data = 5; - inline bool has_login_data() const; - inline void clear_login_data(); - static const int kLoginDataFieldNumber = 5; - inline const ::std::string& login_data() const; - inline void set_login_data(const ::std::string& value); - inline void set_login_data(const char* value); - inline void set_login_data(const void* value, size_t size); - inline ::std::string* mutable_login_data(); - inline ::std::string* release_login_data(); - inline void set_allocated_login_data(::std::string* login_data); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.OpenSessionRequest) - private: - inline void set_has_uuid(); - inline void clear_has_uuid(); - inline void set_has_is_gp_uuid(); - inline void clear_has_is_gp_uuid(); - inline void set_has_tci(); - inline void clear_has_tci(); - inline void set_has_login_type(); - inline void clear_has_login_type(); - inline void set_has_login_data(); - inline void clear_has_login_data(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* uuid_; - ::std::string* tci_; - bool is_gp_uuid_; - int login_type_; - ::std::string* login_data_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static OpenSessionRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class OpenSessionResponse : public ::google::protobuf::MessageLite { - public: - OpenSessionResponse(); - virtual ~OpenSessionResponse(); - - OpenSessionResponse(const OpenSessionResponse& from); - - inline OpenSessionResponse& operator=(const OpenSessionResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const OpenSessionResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const OpenSessionResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(OpenSessionResponse* other); - - // implements Message ---------------------------------------------- - - OpenSessionResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const OpenSessionResponse& from); - void MergeFrom(const OpenSessionResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 id = 1; - inline bool has_id() const; - inline void clear_id(); - static const int kIdFieldNumber = 1; - inline ::google::protobuf::uint32 id() const; - inline void set_id(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.OpenSessionResponse) - private: - inline void set_has_id(); - inline void clear_has_id(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 id_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static OpenSessionResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class OpenTrustletRequest : public ::google::protobuf::MessageLite { - public: - OpenTrustletRequest(); - virtual ~OpenTrustletRequest(); - - OpenTrustletRequest(const OpenTrustletRequest& from); - - inline OpenTrustletRequest& operator=(const OpenTrustletRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const OpenTrustletRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const OpenTrustletRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(OpenTrustletRequest* other); - - // implements Message ---------------------------------------------- - - OpenTrustletRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const OpenTrustletRequest& from); - void MergeFrom(const OpenTrustletRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 spid = 1; - inline bool has_spid() const; - inline void clear_spid(); - static const int kSpidFieldNumber = 1; - inline ::google::protobuf::uint32 spid() const; - inline void set_spid(::google::protobuf::uint32 value); - - // required bytes trustapp = 2; - inline bool has_trustapp() const; - inline void clear_trustapp(); - static const int kTrustappFieldNumber = 2; - inline const ::std::string& trustapp() const; - inline void set_trustapp(const ::std::string& value); - inline void set_trustapp(const char* value); - inline void set_trustapp(const void* value, size_t size); - inline ::std::string* mutable_trustapp(); - inline ::std::string* release_trustapp(); - inline void set_allocated_trustapp(::std::string* trustapp); - - // optional bytes tci = 3; - inline bool has_tci() const; - inline void clear_tci(); - static const int kTciFieldNumber = 3; - inline const ::std::string& tci() const; - inline void set_tci(const ::std::string& value); - inline void set_tci(const char* value); - inline void set_tci(const void* value, size_t size); - inline ::std::string* mutable_tci(); - inline ::std::string* release_tci(); - inline void set_allocated_tci(::std::string* tci); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.OpenTrustletRequest) - private: - inline void set_has_spid(); - inline void clear_has_spid(); - inline void set_has_trustapp(); - inline void clear_has_trustapp(); - inline void set_has_tci(); - inline void clear_has_tci(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* trustapp_; - ::std::string* tci_; - ::google::protobuf::uint32 spid_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static OpenTrustletRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class OpenTrustletResponse : public ::google::protobuf::MessageLite { - public: - OpenTrustletResponse(); - virtual ~OpenTrustletResponse(); - - OpenTrustletResponse(const OpenTrustletResponse& from); - - inline OpenTrustletResponse& operator=(const OpenTrustletResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const OpenTrustletResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const OpenTrustletResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(OpenTrustletResponse* other); - - // implements Message ---------------------------------------------- - - OpenTrustletResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const OpenTrustletResponse& from); - void MergeFrom(const OpenTrustletResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 id = 1; - inline bool has_id() const; - inline void clear_id(); - static const int kIdFieldNumber = 1; - inline ::google::protobuf::uint32 id() const; - inline void set_id(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.OpenTrustletResponse) - private: - inline void set_has_id(); - inline void clear_has_id(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 id_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static OpenTrustletResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class CloseSessionRequest : public ::google::protobuf::MessageLite { - public: - CloseSessionRequest(); - virtual ~CloseSessionRequest(); - - CloseSessionRequest(const CloseSessionRequest& from); - - inline CloseSessionRequest& operator=(const CloseSessionRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const CloseSessionRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const CloseSessionRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(CloseSessionRequest* other); - - // implements Message ---------------------------------------------- - - CloseSessionRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const CloseSessionRequest& from); - void MergeFrom(const CloseSessionRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 id = 1; - inline bool has_id() const; - inline void clear_id(); - static const int kIdFieldNumber = 1; - inline ::google::protobuf::uint32 id() const; - inline void set_id(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.CloseSessionRequest) - private: - inline void set_has_id(); - inline void clear_has_id(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 id_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static CloseSessionRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class CloseSessionResponse : public ::google::protobuf::MessageLite { - public: - CloseSessionResponse(); - virtual ~CloseSessionResponse(); - - CloseSessionResponse(const CloseSessionResponse& from); - - inline CloseSessionResponse& operator=(const CloseSessionResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const CloseSessionResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const CloseSessionResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(CloseSessionResponse* other); - - // implements Message ---------------------------------------------- - - CloseSessionResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const CloseSessionResponse& from); - void MergeFrom(const CloseSessionResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.CloseSessionResponse) - private: - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static CloseSessionResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class NotifyRequest_Buffers : public ::google::protobuf::MessageLite { - public: - NotifyRequest_Buffers(); - virtual ~NotifyRequest_Buffers(); - - NotifyRequest_Buffers(const NotifyRequest_Buffers& from); - - inline NotifyRequest_Buffers& operator=(const NotifyRequest_Buffers& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const NotifyRequest_Buffers& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const NotifyRequest_Buffers* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(NotifyRequest_Buffers* other); - - // implements Message ---------------------------------------------- - - NotifyRequest_Buffers* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const NotifyRequest_Buffers& from); - void MergeFrom(const NotifyRequest_Buffers& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint64 sva = 1; - inline bool has_sva() const; - inline void clear_sva(); - static const int kSvaFieldNumber = 1; - inline ::google::protobuf::uint64 sva() const; - inline void set_sva(::google::protobuf::uint64 value); - - // required bytes data = 2; - inline bool has_data() const; - inline void clear_data(); - static const int kDataFieldNumber = 2; - inline const ::std::string& data() const; - inline void set_data(const ::std::string& value); - inline void set_data(const char* value); - inline void set_data(const void* value, size_t size); - inline ::std::string* mutable_data(); - inline ::std::string* release_data(); - inline void set_allocated_data(::std::string* data); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.NotifyRequest.Buffers) - private: - inline void set_has_sva(); - inline void clear_has_sva(); - inline void set_has_data(); - inline void clear_has_data(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 sva_; - ::std::string* data_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static NotifyRequest_Buffers* default_instance_; -}; -// ------------------------------------------------------------------- - -class NotifyRequest : public ::google::protobuf::MessageLite { - public: - NotifyRequest(); - virtual ~NotifyRequest(); - - NotifyRequest(const NotifyRequest& from); - - inline NotifyRequest& operator=(const NotifyRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const NotifyRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const NotifyRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(NotifyRequest* other); - - // implements Message ---------------------------------------------- - - NotifyRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const NotifyRequest& from); - void MergeFrom(const NotifyRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - typedef NotifyRequest_Buffers Buffers; - - // accessors ------------------------------------------------------- - - // required uint32 sid = 1; - inline bool has_sid() const; - inline void clear_sid(); - static const int kSidFieldNumber = 1; - inline ::google::protobuf::uint32 sid() const; - inline void set_sid(::google::protobuf::uint32 value); - - // optional bytes tci = 2; - inline bool has_tci() const; - inline void clear_tci(); - static const int kTciFieldNumber = 2; - inline const ::std::string& tci() const; - inline void set_tci(const ::std::string& value); - inline void set_tci(const char* value); - inline void set_tci(const void* value, size_t size); - inline ::std::string* mutable_tci(); - inline ::std::string* release_tci(); - inline void set_allocated_tci(::std::string* tci); - - // repeated .com.trustonic.tee_proxy.NotifyRequest.Buffers buffers = 3; - inline int buffers_size() const; - inline void clear_buffers(); - static const int kBuffersFieldNumber = 3; - inline const ::com::trustonic::tee_proxy::NotifyRequest_Buffers& buffers(int index) const; - inline ::com::trustonic::tee_proxy::NotifyRequest_Buffers* mutable_buffers(int index); - inline ::com::trustonic::tee_proxy::NotifyRequest_Buffers* add_buffers(); - inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::NotifyRequest_Buffers >& - buffers() const; - inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::NotifyRequest_Buffers >* - mutable_buffers(); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.NotifyRequest) - private: - inline void set_has_sid(); - inline void clear_has_sid(); - inline void set_has_tci(); - inline void clear_has_tci(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* tci_; - ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::NotifyRequest_Buffers > buffers_; - ::google::protobuf::uint32 sid_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static NotifyRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class NotifyResponse : public ::google::protobuf::MessageLite { - public: - NotifyResponse(); - virtual ~NotifyResponse(); - - NotifyResponse(const NotifyResponse& from); - - inline NotifyResponse& operator=(const NotifyResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const NotifyResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const NotifyResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(NotifyResponse* other); - - // implements Message ---------------------------------------------- - - NotifyResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const NotifyResponse& from); - void MergeFrom(const NotifyResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.NotifyResponse) - private: - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static NotifyResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class WaitNotificationRequest : public ::google::protobuf::MessageLite { - public: - WaitNotificationRequest(); - virtual ~WaitNotificationRequest(); - - WaitNotificationRequest(const WaitNotificationRequest& from); - - inline WaitNotificationRequest& operator=(const WaitNotificationRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const WaitNotificationRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const WaitNotificationRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(WaitNotificationRequest* other); - - // implements Message ---------------------------------------------- - - WaitNotificationRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const WaitNotificationRequest& from); - void MergeFrom(const WaitNotificationRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 sid = 1; - inline bool has_sid() const; - inline void clear_sid(); - static const int kSidFieldNumber = 1; - inline ::google::protobuf::uint32 sid() const; - inline void set_sid(::google::protobuf::uint32 value); - - // required sint32 timeout = 2; - inline bool has_timeout() const; - inline void clear_timeout(); - static const int kTimeoutFieldNumber = 2; - inline ::google::protobuf::int32 timeout() const; - inline void set_timeout(::google::protobuf::int32 value); - - // required bool partial = 3; - inline bool has_partial() const; - inline void clear_partial(); - static const int kPartialFieldNumber = 3; - inline bool partial() const; - inline void set_partial(bool value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.WaitNotificationRequest) - private: - inline void set_has_sid(); - inline void clear_has_sid(); - inline void set_has_timeout(); - inline void clear_has_timeout(); - inline void set_has_partial(); - inline void clear_has_partial(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 sid_; - ::google::protobuf::int32 timeout_; - bool partial_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static WaitNotificationRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class WaitNotificationResponse_Buffers : public ::google::protobuf::MessageLite { - public: - WaitNotificationResponse_Buffers(); - virtual ~WaitNotificationResponse_Buffers(); - - WaitNotificationResponse_Buffers(const WaitNotificationResponse_Buffers& from); - - inline WaitNotificationResponse_Buffers& operator=(const WaitNotificationResponse_Buffers& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const WaitNotificationResponse_Buffers& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const WaitNotificationResponse_Buffers* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(WaitNotificationResponse_Buffers* other); - - // implements Message ---------------------------------------------- - - WaitNotificationResponse_Buffers* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const WaitNotificationResponse_Buffers& from); - void MergeFrom(const WaitNotificationResponse_Buffers& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint64 sva = 1; - inline bool has_sva() const; - inline void clear_sva(); - static const int kSvaFieldNumber = 1; - inline ::google::protobuf::uint64 sva() const; - inline void set_sva(::google::protobuf::uint64 value); - - // required bytes data = 2; - inline bool has_data() const; - inline void clear_data(); - static const int kDataFieldNumber = 2; - inline const ::std::string& data() const; - inline void set_data(const ::std::string& value); - inline void set_data(const char* value); - inline void set_data(const void* value, size_t size); - inline ::std::string* mutable_data(); - inline ::std::string* release_data(); - inline void set_allocated_data(::std::string* data); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers) - private: - inline void set_has_sva(); - inline void clear_has_sva(); - inline void set_has_data(); - inline void clear_has_data(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 sva_; - ::std::string* data_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static WaitNotificationResponse_Buffers* default_instance_; -}; -// ------------------------------------------------------------------- - -class WaitNotificationResponse : public ::google::protobuf::MessageLite { - public: - WaitNotificationResponse(); - virtual ~WaitNotificationResponse(); - - WaitNotificationResponse(const WaitNotificationResponse& from); - - inline WaitNotificationResponse& operator=(const WaitNotificationResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const WaitNotificationResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const WaitNotificationResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(WaitNotificationResponse* other); - - // implements Message ---------------------------------------------- - - WaitNotificationResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const WaitNotificationResponse& from); - void MergeFrom(const WaitNotificationResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - typedef WaitNotificationResponse_Buffers Buffers; - - // accessors ------------------------------------------------------- - - // optional bytes tci = 1; - inline bool has_tci() const; - inline void clear_tci(); - static const int kTciFieldNumber = 1; - inline const ::std::string& tci() const; - inline void set_tci(const ::std::string& value); - inline void set_tci(const char* value); - inline void set_tci(const void* value, size_t size); - inline ::std::string* mutable_tci(); - inline ::std::string* release_tci(); - inline void set_allocated_tci(::std::string* tci); - - // repeated .com.trustonic.tee_proxy.WaitNotificationResponse.Buffers buffers = 2; - inline int buffers_size() const; - inline void clear_buffers(); - static const int kBuffersFieldNumber = 2; - inline const ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers& buffers(int index) const; - inline ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers* mutable_buffers(int index); - inline ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers* add_buffers(); - inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers >& - buffers() const; - inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers >* - mutable_buffers(); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.WaitNotificationResponse) - private: - inline void set_has_tci(); - inline void clear_has_tci(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* tci_; - ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers > buffers_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static WaitNotificationResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class MapRequest_Buffers : public ::google::protobuf::MessageLite { - public: - MapRequest_Buffers(); - virtual ~MapRequest_Buffers(); - - MapRequest_Buffers(const MapRequest_Buffers& from); - - inline MapRequest_Buffers& operator=(const MapRequest_Buffers& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const MapRequest_Buffers& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const MapRequest_Buffers* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(MapRequest_Buffers* other); - - // implements Message ---------------------------------------------- - - MapRequest_Buffers* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const MapRequest_Buffers& from); - void MergeFrom(const MapRequest_Buffers& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 len = 1; - inline bool has_len() const; - inline void clear_len(); - static const int kLenFieldNumber = 1; - inline ::google::protobuf::uint32 len() const; - inline void set_len(::google::protobuf::uint32 value); - - // required uint32 flags = 2; - inline bool has_flags() const; - inline void clear_flags(); - static const int kFlagsFieldNumber = 2; - inline ::google::protobuf::uint32 flags() const; - inline void set_flags(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.MapRequest.Buffers) - private: - inline void set_has_len(); - inline void clear_has_len(); - inline void set_has_flags(); - inline void clear_has_flags(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 len_; - ::google::protobuf::uint32 flags_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static MapRequest_Buffers* default_instance_; -}; -// ------------------------------------------------------------------- - -class MapRequest : public ::google::protobuf::MessageLite { - public: - MapRequest(); - virtual ~MapRequest(); - - MapRequest(const MapRequest& from); - - inline MapRequest& operator=(const MapRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const MapRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const MapRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(MapRequest* other); - - // implements Message ---------------------------------------------- - - MapRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const MapRequest& from); - void MergeFrom(const MapRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - typedef MapRequest_Buffers Buffers; - - // accessors ------------------------------------------------------- - - // required uint32 sid = 1; - inline bool has_sid() const; - inline void clear_sid(); - static const int kSidFieldNumber = 1; - inline ::google::protobuf::uint32 sid() const; - inline void set_sid(::google::protobuf::uint32 value); - - // repeated .com.trustonic.tee_proxy.MapRequest.Buffers buffers = 2; - inline int buffers_size() const; - inline void clear_buffers(); - static const int kBuffersFieldNumber = 2; - inline const ::com::trustonic::tee_proxy::MapRequest_Buffers& buffers(int index) const; - inline ::com::trustonic::tee_proxy::MapRequest_Buffers* mutable_buffers(int index); - inline ::com::trustonic::tee_proxy::MapRequest_Buffers* add_buffers(); - inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapRequest_Buffers >& - buffers() const; - inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapRequest_Buffers >* - mutable_buffers(); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.MapRequest) - private: - inline void set_has_sid(); - inline void clear_has_sid(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapRequest_Buffers > buffers_; - ::google::protobuf::uint32 sid_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static MapRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class MapResponse_Buffers : public ::google::protobuf::MessageLite { - public: - MapResponse_Buffers(); - virtual ~MapResponse_Buffers(); - - MapResponse_Buffers(const MapResponse_Buffers& from); - - inline MapResponse_Buffers& operator=(const MapResponse_Buffers& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const MapResponse_Buffers& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const MapResponse_Buffers* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(MapResponse_Buffers* other); - - // implements Message ---------------------------------------------- - - MapResponse_Buffers* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const MapResponse_Buffers& from); - void MergeFrom(const MapResponse_Buffers& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint64 sva = 1; - inline bool has_sva() const; - inline void clear_sva(); - static const int kSvaFieldNumber = 1; - inline ::google::protobuf::uint64 sva() const; - inline void set_sva(::google::protobuf::uint64 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.MapResponse.Buffers) - private: - inline void set_has_sva(); - inline void clear_has_sva(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 sva_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static MapResponse_Buffers* default_instance_; -}; -// ------------------------------------------------------------------- - -class MapResponse : public ::google::protobuf::MessageLite { - public: - MapResponse(); - virtual ~MapResponse(); - - MapResponse(const MapResponse& from); - - inline MapResponse& operator=(const MapResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const MapResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const MapResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(MapResponse* other); - - // implements Message ---------------------------------------------- - - MapResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const MapResponse& from); - void MergeFrom(const MapResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - typedef MapResponse_Buffers Buffers; - - // accessors ------------------------------------------------------- - - // repeated .com.trustonic.tee_proxy.MapResponse.Buffers buffers = 1; - inline int buffers_size() const; - inline void clear_buffers(); - static const int kBuffersFieldNumber = 1; - inline const ::com::trustonic::tee_proxy::MapResponse_Buffers& buffers(int index) const; - inline ::com::trustonic::tee_proxy::MapResponse_Buffers* mutable_buffers(int index); - inline ::com::trustonic::tee_proxy::MapResponse_Buffers* add_buffers(); - inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapResponse_Buffers >& - buffers() const; - inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapResponse_Buffers >* - mutable_buffers(); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.MapResponse) - private: - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapResponse_Buffers > buffers_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static MapResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class UnmapRequest_Buffers : public ::google::protobuf::MessageLite { - public: - UnmapRequest_Buffers(); - virtual ~UnmapRequest_Buffers(); - - UnmapRequest_Buffers(const UnmapRequest_Buffers& from); - - inline UnmapRequest_Buffers& operator=(const UnmapRequest_Buffers& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const UnmapRequest_Buffers& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const UnmapRequest_Buffers* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(UnmapRequest_Buffers* other); - - // implements Message ---------------------------------------------- - - UnmapRequest_Buffers* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const UnmapRequest_Buffers& from); - void MergeFrom(const UnmapRequest_Buffers& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint64 sva = 1; - inline bool has_sva() const; - inline void clear_sva(); - static const int kSvaFieldNumber = 1; - inline ::google::protobuf::uint64 sva() const; - inline void set_sva(::google::protobuf::uint64 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.UnmapRequest.Buffers) - private: - inline void set_has_sva(); - inline void clear_has_sva(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 sva_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static UnmapRequest_Buffers* default_instance_; -}; -// ------------------------------------------------------------------- - -class UnmapRequest : public ::google::protobuf::MessageLite { - public: - UnmapRequest(); - virtual ~UnmapRequest(); - - UnmapRequest(const UnmapRequest& from); - - inline UnmapRequest& operator=(const UnmapRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const UnmapRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const UnmapRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(UnmapRequest* other); - - // implements Message ---------------------------------------------- - - UnmapRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const UnmapRequest& from); - void MergeFrom(const UnmapRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - typedef UnmapRequest_Buffers Buffers; - - // accessors ------------------------------------------------------- - - // required uint32 sid = 1; - inline bool has_sid() const; - inline void clear_sid(); - static const int kSidFieldNumber = 1; - inline ::google::protobuf::uint32 sid() const; - inline void set_sid(::google::protobuf::uint32 value); - - // repeated .com.trustonic.tee_proxy.UnmapRequest.Buffers buffers = 2; - inline int buffers_size() const; - inline void clear_buffers(); - static const int kBuffersFieldNumber = 2; - inline const ::com::trustonic::tee_proxy::UnmapRequest_Buffers& buffers(int index) const; - inline ::com::trustonic::tee_proxy::UnmapRequest_Buffers* mutable_buffers(int index); - inline ::com::trustonic::tee_proxy::UnmapRequest_Buffers* add_buffers(); - inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::UnmapRequest_Buffers >& - buffers() const; - inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::UnmapRequest_Buffers >* - mutable_buffers(); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.UnmapRequest) - private: - inline void set_has_sid(); - inline void clear_has_sid(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::UnmapRequest_Buffers > buffers_; - ::google::protobuf::uint32 sid_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static UnmapRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class UnmapResponse : public ::google::protobuf::MessageLite { - public: - UnmapResponse(); - virtual ~UnmapResponse(); - - UnmapResponse(const UnmapResponse& from); - - inline UnmapResponse& operator=(const UnmapResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const UnmapResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const UnmapResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(UnmapResponse* other); - - // implements Message ---------------------------------------------- - - UnmapResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const UnmapResponse& from); - void MergeFrom(const UnmapResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.UnmapResponse) - private: - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static UnmapResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class GetErrorRequest : public ::google::protobuf::MessageLite { - public: - GetErrorRequest(); - virtual ~GetErrorRequest(); - - GetErrorRequest(const GetErrorRequest& from); - - inline GetErrorRequest& operator=(const GetErrorRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const GetErrorRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const GetErrorRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(GetErrorRequest* other); - - // implements Message ---------------------------------------------- - - GetErrorRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const GetErrorRequest& from); - void MergeFrom(const GetErrorRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 sid = 1; - inline bool has_sid() const; - inline void clear_sid(); - static const int kSidFieldNumber = 1; - inline ::google::protobuf::uint32 sid() const; - inline void set_sid(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.GetErrorRequest) - private: - inline void set_has_sid(); - inline void clear_has_sid(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 sid_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static GetErrorRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class GetErrorResponse : public ::google::protobuf::MessageLite { - public: - GetErrorResponse(); - virtual ~GetErrorResponse(); - - GetErrorResponse(const GetErrorResponse& from); - - inline GetErrorResponse& operator=(const GetErrorResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const GetErrorResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const GetErrorResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(GetErrorResponse* other); - - // implements Message ---------------------------------------------- - - GetErrorResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const GetErrorResponse& from); - void MergeFrom(const GetErrorResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required sint32 exit_code = 1; - inline bool has_exit_code() const; - inline void clear_exit_code(); - static const int kExitCodeFieldNumber = 1; - inline ::google::protobuf::int32 exit_code() const; - inline void set_exit_code(::google::protobuf::int32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.GetErrorResponse) - private: - inline void set_has_exit_code(); - inline void clear_has_exit_code(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::int32 exit_code_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static GetErrorResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class GetVersionRequest : public ::google::protobuf::MessageLite { - public: - GetVersionRequest(); - virtual ~GetVersionRequest(); - - GetVersionRequest(const GetVersionRequest& from); - - inline GetVersionRequest& operator=(const GetVersionRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const GetVersionRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const GetVersionRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(GetVersionRequest* other); - - // implements Message ---------------------------------------------- - - GetVersionRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const GetVersionRequest& from); - void MergeFrom(const GetVersionRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.GetVersionRequest) - private: - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static GetVersionRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class GetVersionResponse : public ::google::protobuf::MessageLite { - public: - GetVersionResponse(); - virtual ~GetVersionResponse(); - - GetVersionResponse(const GetVersionResponse& from); - - inline GetVersionResponse& operator=(const GetVersionResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const GetVersionResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const GetVersionResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(GetVersionResponse* other); - - // implements Message ---------------------------------------------- - - GetVersionResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const GetVersionResponse& from); - void MergeFrom(const GetVersionResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required string product_id = 1; - inline bool has_product_id() const; - inline void clear_product_id(); - static const int kProductIdFieldNumber = 1; - inline const ::std::string& product_id() const; - inline void set_product_id(const ::std::string& value); - inline void set_product_id(const char* value); - inline void set_product_id(const char* value, size_t size); - inline ::std::string* mutable_product_id(); - inline ::std::string* release_product_id(); - inline void set_allocated_product_id(::std::string* product_id); - - // required uint32 mci = 2; - inline bool has_mci() const; - inline void clear_mci(); - static const int kMciFieldNumber = 2; - inline ::google::protobuf::uint32 mci() const; - inline void set_mci(::google::protobuf::uint32 value); - - // required uint32 so = 3; - inline bool has_so() const; - inline void clear_so(); - static const int kSoFieldNumber = 3; - inline ::google::protobuf::uint32 so() const; - inline void set_so(::google::protobuf::uint32 value); - - // required uint32 mclf = 4; - inline bool has_mclf() const; - inline void clear_mclf(); - static const int kMclfFieldNumber = 4; - inline ::google::protobuf::uint32 mclf() const; - inline void set_mclf(::google::protobuf::uint32 value); - - // required uint32 container = 5; - inline bool has_container() const; - inline void clear_container(); - static const int kContainerFieldNumber = 5; - inline ::google::protobuf::uint32 container() const; - inline void set_container(::google::protobuf::uint32 value); - - // required uint32 mc_config = 6; - inline bool has_mc_config() const; - inline void clear_mc_config(); - static const int kMcConfigFieldNumber = 6; - inline ::google::protobuf::uint32 mc_config() const; - inline void set_mc_config(::google::protobuf::uint32 value); - - // required uint32 tl_api = 7; - inline bool has_tl_api() const; - inline void clear_tl_api(); - static const int kTlApiFieldNumber = 7; - inline ::google::protobuf::uint32 tl_api() const; - inline void set_tl_api(::google::protobuf::uint32 value); - - // required uint32 dr_api = 8; - inline bool has_dr_api() const; - inline void clear_dr_api(); - static const int kDrApiFieldNumber = 8; - inline ::google::protobuf::uint32 dr_api() const; - inline void set_dr_api(::google::protobuf::uint32 value); - - // required uint32 nwd = 9; - inline bool has_nwd() const; - inline void clear_nwd(); - static const int kNwdFieldNumber = 9; - inline ::google::protobuf::uint32 nwd() const; - inline void set_nwd(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.GetVersionResponse) - private: - inline void set_has_product_id(); - inline void clear_has_product_id(); - inline void set_has_mci(); - inline void clear_has_mci(); - inline void set_has_so(); - inline void clear_has_so(); - inline void set_has_mclf(); - inline void clear_has_mclf(); - inline void set_has_container(); - inline void clear_has_container(); - inline void set_has_mc_config(); - inline void clear_has_mc_config(); - inline void set_has_tl_api(); - inline void clear_has_tl_api(); - inline void set_has_dr_api(); - inline void clear_has_dr_api(); - inline void set_has_nwd(); - inline void clear_has_nwd(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* product_id_; - ::google::protobuf::uint32 mci_; - ::google::protobuf::uint32 so_; - ::google::protobuf::uint32 mclf_; - ::google::protobuf::uint32 container_; - ::google::protobuf::uint32 mc_config_; - ::google::protobuf::uint32 tl_api_; - ::google::protobuf::uint32 dr_api_; - ::google::protobuf::uint32 nwd_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static GetVersionResponse* default_instance_; -}; -// ------------------------------------------------------------------- - -class GpRequestCancellationRequest : public ::google::protobuf::MessageLite { - public: - GpRequestCancellationRequest(); - virtual ~GpRequestCancellationRequest(); - - GpRequestCancellationRequest(const GpRequestCancellationRequest& from); - - inline GpRequestCancellationRequest& operator=(const GpRequestCancellationRequest& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const GpRequestCancellationRequest& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const GpRequestCancellationRequest* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(GpRequestCancellationRequest* other); - - // implements Message ---------------------------------------------- - - GpRequestCancellationRequest* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const GpRequestCancellationRequest& from); - void MergeFrom(const GpRequestCancellationRequest& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required uint32 sid = 1; - inline bool has_sid() const; - inline void clear_sid(); - static const int kSidFieldNumber = 1; - inline ::google::protobuf::uint32 sid() const; - inline void set_sid(::google::protobuf::uint32 value); - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.GpRequestCancellationRequest) - private: - inline void set_has_sid(); - inline void clear_has_sid(); - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint32 sid_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static GpRequestCancellationRequest* default_instance_; -}; -// ------------------------------------------------------------------- - -class GpRequestCancellationResponse : public ::google::protobuf::MessageLite { - public: - GpRequestCancellationResponse(); - virtual ~GpRequestCancellationResponse(); - - GpRequestCancellationResponse(const GpRequestCancellationResponse& from); - - inline GpRequestCancellationResponse& operator=(const GpRequestCancellationResponse& from) { - CopyFrom(from); - return *this; - } - - inline const ::std::string& unknown_fields() const { - return _unknown_fields_; - } - - inline ::std::string* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const GpRequestCancellationResponse& default_instance(); - - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - // Returns the internal default instance pointer. This function can - // return NULL thus should not be used by the user. This is intended - // for Protobuf internal code. Please use default_instance() declared - // above instead. - static inline const GpRequestCancellationResponse* internal_default_instance() { - return default_instance_; - } - #endif - - void Swap(GpRequestCancellationResponse* other); - - // implements Message ---------------------------------------------- - - GpRequestCancellationResponse* New() const; - void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); - void CopyFrom(const GpRequestCancellationResponse& from); - void MergeFrom(const GpRequestCancellationResponse& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - void DiscardUnknownFields(); - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::std::string GetTypeName() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // @@protoc_insertion_point(class_scope:com.trustonic.tee_proxy.GpRequestCancellationResponse) - private: - - ::std::string _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER - friend void protobuf_AddDesc_mc_2eproto_impl(); - #else - friend void protobuf_AddDesc_mc_2eproto(); - #endif - friend void protobuf_AssignDesc_mc_2eproto(); - friend void protobuf_ShutdownFile_mc_2eproto(); - - void InitAsDefaultInstance(); - static GpRequestCancellationResponse* default_instance_; -}; -// =================================================================== - - -// =================================================================== - -// OpenSessionRequest - -// required bytes uuid = 1; -inline bool OpenSessionRequest::has_uuid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void OpenSessionRequest::set_has_uuid() { - _has_bits_[0] |= 0x00000001u; -} -inline void OpenSessionRequest::clear_has_uuid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void OpenSessionRequest::clear_uuid() { - if (uuid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - uuid_->clear(); - } - clear_has_uuid(); -} -inline const ::std::string& OpenSessionRequest::uuid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenSessionRequest.uuid) - return *uuid_; -} -inline void OpenSessionRequest::set_uuid(const ::std::string& value) { - set_has_uuid(); - if (uuid_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - uuid_ = new ::std::string; - } - uuid_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenSessionRequest.uuid) -} -inline void OpenSessionRequest::set_uuid(const char* value) { - set_has_uuid(); - if (uuid_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - uuid_ = new ::std::string; - } - uuid_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.OpenSessionRequest.uuid) -} -inline void OpenSessionRequest::set_uuid(const void* value, size_t size) { - set_has_uuid(); - if (uuid_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - uuid_ = new ::std::string; - } - uuid_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.OpenSessionRequest.uuid) -} -inline ::std::string* OpenSessionRequest::mutable_uuid() { - set_has_uuid(); - if (uuid_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - uuid_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.OpenSessionRequest.uuid) - return uuid_; -} -inline ::std::string* OpenSessionRequest::release_uuid() { - clear_has_uuid(); - if (uuid_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = uuid_; - uuid_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void OpenSessionRequest::set_allocated_uuid(::std::string* uuid) { - if (uuid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete uuid_; - } - if (uuid) { - set_has_uuid(); - uuid_ = uuid; - } else { - clear_has_uuid(); - uuid_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.OpenSessionRequest.uuid) -} - -// required bool is_gp_uuid = 2; -inline bool OpenSessionRequest::has_is_gp_uuid() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void OpenSessionRequest::set_has_is_gp_uuid() { - _has_bits_[0] |= 0x00000002u; -} -inline void OpenSessionRequest::clear_has_is_gp_uuid() { - _has_bits_[0] &= ~0x00000002u; -} -inline void OpenSessionRequest::clear_is_gp_uuid() { - is_gp_uuid_ = false; - clear_has_is_gp_uuid(); -} -inline bool OpenSessionRequest::is_gp_uuid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenSessionRequest.is_gp_uuid) - return is_gp_uuid_; -} -inline void OpenSessionRequest::set_is_gp_uuid(bool value) { - set_has_is_gp_uuid(); - is_gp_uuid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenSessionRequest.is_gp_uuid) -} - -// optional bytes tci = 3; -inline bool OpenSessionRequest::has_tci() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void OpenSessionRequest::set_has_tci() { - _has_bits_[0] |= 0x00000004u; -} -inline void OpenSessionRequest::clear_has_tci() { - _has_bits_[0] &= ~0x00000004u; -} -inline void OpenSessionRequest::clear_tci() { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - clear_has_tci(); -} -inline const ::std::string& OpenSessionRequest::tci() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenSessionRequest.tci) - return *tci_; -} -inline void OpenSessionRequest::set_tci(const ::std::string& value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenSessionRequest.tci) -} -inline void OpenSessionRequest::set_tci(const char* value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.OpenSessionRequest.tci) -} -inline void OpenSessionRequest::set_tci(const void* value, size_t size) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.OpenSessionRequest.tci) -} -inline ::std::string* OpenSessionRequest::mutable_tci() { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.OpenSessionRequest.tci) - return tci_; -} -inline ::std::string* OpenSessionRequest::release_tci() { - clear_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = tci_; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void OpenSessionRequest::set_allocated_tci(::std::string* tci) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - if (tci) { - set_has_tci(); - tci_ = tci; - } else { - clear_has_tci(); - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.OpenSessionRequest.tci) -} - -// required .com.trustonic.tee_proxy.LoginType login_type = 4; -inline bool OpenSessionRequest::has_login_type() const { - return (_has_bits_[0] & 0x00000008u) != 0; -} -inline void OpenSessionRequest::set_has_login_type() { - _has_bits_[0] |= 0x00000008u; -} -inline void OpenSessionRequest::clear_has_login_type() { - _has_bits_[0] &= ~0x00000008u; -} -inline void OpenSessionRequest::clear_login_type() { - login_type_ = 0; - clear_has_login_type(); -} -inline ::com::trustonic::tee_proxy::LoginType OpenSessionRequest::login_type() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenSessionRequest.login_type) - return static_cast< ::com::trustonic::tee_proxy::LoginType >(login_type_); -} -inline void OpenSessionRequest::set_login_type(::com::trustonic::tee_proxy::LoginType value) { - assert(::com::trustonic::tee_proxy::LoginType_IsValid(value)); - set_has_login_type(); - login_type_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenSessionRequest.login_type) -} - -// required bytes login_data = 5; -inline bool OpenSessionRequest::has_login_data() const { - return (_has_bits_[0] & 0x00000010u) != 0; -} -inline void OpenSessionRequest::set_has_login_data() { - _has_bits_[0] |= 0x00000010u; -} -inline void OpenSessionRequest::clear_has_login_data() { - _has_bits_[0] &= ~0x00000010u; -} -inline void OpenSessionRequest::clear_login_data() { - if (login_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - login_data_->clear(); - } - clear_has_login_data(); -} -inline const ::std::string& OpenSessionRequest::login_data() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenSessionRequest.login_data) - return *login_data_; -} -inline void OpenSessionRequest::set_login_data(const ::std::string& value) { - set_has_login_data(); - if (login_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - login_data_ = new ::std::string; - } - login_data_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenSessionRequest.login_data) -} -inline void OpenSessionRequest::set_login_data(const char* value) { - set_has_login_data(); - if (login_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - login_data_ = new ::std::string; - } - login_data_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.OpenSessionRequest.login_data) -} -inline void OpenSessionRequest::set_login_data(const void* value, size_t size) { - set_has_login_data(); - if (login_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - login_data_ = new ::std::string; - } - login_data_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.OpenSessionRequest.login_data) -} -inline ::std::string* OpenSessionRequest::mutable_login_data() { - set_has_login_data(); - if (login_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - login_data_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.OpenSessionRequest.login_data) - return login_data_; -} -inline ::std::string* OpenSessionRequest::release_login_data() { - clear_has_login_data(); - if (login_data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = login_data_; - login_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void OpenSessionRequest::set_allocated_login_data(::std::string* login_data) { - if (login_data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete login_data_; - } - if (login_data) { - set_has_login_data(); - login_data_ = login_data; - } else { - clear_has_login_data(); - login_data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.OpenSessionRequest.login_data) -} - -// ------------------------------------------------------------------- - -// OpenSessionResponse - -// required uint32 id = 1; -inline bool OpenSessionResponse::has_id() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void OpenSessionResponse::set_has_id() { - _has_bits_[0] |= 0x00000001u; -} -inline void OpenSessionResponse::clear_has_id() { - _has_bits_[0] &= ~0x00000001u; -} -inline void OpenSessionResponse::clear_id() { - id_ = 0u; - clear_has_id(); -} -inline ::google::protobuf::uint32 OpenSessionResponse::id() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenSessionResponse.id) - return id_; -} -inline void OpenSessionResponse::set_id(::google::protobuf::uint32 value) { - set_has_id(); - id_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenSessionResponse.id) -} - -// ------------------------------------------------------------------- - -// OpenTrustletRequest - -// required uint32 spid = 1; -inline bool OpenTrustletRequest::has_spid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void OpenTrustletRequest::set_has_spid() { - _has_bits_[0] |= 0x00000001u; -} -inline void OpenTrustletRequest::clear_has_spid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void OpenTrustletRequest::clear_spid() { - spid_ = 0u; - clear_has_spid(); -} -inline ::google::protobuf::uint32 OpenTrustletRequest::spid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenTrustletRequest.spid) - return spid_; -} -inline void OpenTrustletRequest::set_spid(::google::protobuf::uint32 value) { - set_has_spid(); - spid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenTrustletRequest.spid) -} - -// required bytes trustapp = 2; -inline bool OpenTrustletRequest::has_trustapp() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void OpenTrustletRequest::set_has_trustapp() { - _has_bits_[0] |= 0x00000002u; -} -inline void OpenTrustletRequest::clear_has_trustapp() { - _has_bits_[0] &= ~0x00000002u; -} -inline void OpenTrustletRequest::clear_trustapp() { - if (trustapp_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - trustapp_->clear(); - } - clear_has_trustapp(); -} -inline const ::std::string& OpenTrustletRequest::trustapp() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenTrustletRequest.trustapp) - return *trustapp_; -} -inline void OpenTrustletRequest::set_trustapp(const ::std::string& value) { - set_has_trustapp(); - if (trustapp_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - trustapp_ = new ::std::string; - } - trustapp_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenTrustletRequest.trustapp) -} -inline void OpenTrustletRequest::set_trustapp(const char* value) { - set_has_trustapp(); - if (trustapp_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - trustapp_ = new ::std::string; - } - trustapp_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.OpenTrustletRequest.trustapp) -} -inline void OpenTrustletRequest::set_trustapp(const void* value, size_t size) { - set_has_trustapp(); - if (trustapp_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - trustapp_ = new ::std::string; - } - trustapp_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.OpenTrustletRequest.trustapp) -} -inline ::std::string* OpenTrustletRequest::mutable_trustapp() { - set_has_trustapp(); - if (trustapp_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - trustapp_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.OpenTrustletRequest.trustapp) - return trustapp_; -} -inline ::std::string* OpenTrustletRequest::release_trustapp() { - clear_has_trustapp(); - if (trustapp_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = trustapp_; - trustapp_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void OpenTrustletRequest::set_allocated_trustapp(::std::string* trustapp) { - if (trustapp_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete trustapp_; - } - if (trustapp) { - set_has_trustapp(); - trustapp_ = trustapp; - } else { - clear_has_trustapp(); - trustapp_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.OpenTrustletRequest.trustapp) -} - -// optional bytes tci = 3; -inline bool OpenTrustletRequest::has_tci() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void OpenTrustletRequest::set_has_tci() { - _has_bits_[0] |= 0x00000004u; -} -inline void OpenTrustletRequest::clear_has_tci() { - _has_bits_[0] &= ~0x00000004u; -} -inline void OpenTrustletRequest::clear_tci() { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - clear_has_tci(); -} -inline const ::std::string& OpenTrustletRequest::tci() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenTrustletRequest.tci) - return *tci_; -} -inline void OpenTrustletRequest::set_tci(const ::std::string& value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenTrustletRequest.tci) -} -inline void OpenTrustletRequest::set_tci(const char* value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.OpenTrustletRequest.tci) -} -inline void OpenTrustletRequest::set_tci(const void* value, size_t size) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.OpenTrustletRequest.tci) -} -inline ::std::string* OpenTrustletRequest::mutable_tci() { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.OpenTrustletRequest.tci) - return tci_; -} -inline ::std::string* OpenTrustletRequest::release_tci() { - clear_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = tci_; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void OpenTrustletRequest::set_allocated_tci(::std::string* tci) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - if (tci) { - set_has_tci(); - tci_ = tci; - } else { - clear_has_tci(); - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.OpenTrustletRequest.tci) -} - -// ------------------------------------------------------------------- - -// OpenTrustletResponse - -// required uint32 id = 1; -inline bool OpenTrustletResponse::has_id() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void OpenTrustletResponse::set_has_id() { - _has_bits_[0] |= 0x00000001u; -} -inline void OpenTrustletResponse::clear_has_id() { - _has_bits_[0] &= ~0x00000001u; -} -inline void OpenTrustletResponse::clear_id() { - id_ = 0u; - clear_has_id(); -} -inline ::google::protobuf::uint32 OpenTrustletResponse::id() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.OpenTrustletResponse.id) - return id_; -} -inline void OpenTrustletResponse::set_id(::google::protobuf::uint32 value) { - set_has_id(); - id_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.OpenTrustletResponse.id) -} - -// ------------------------------------------------------------------- - -// CloseSessionRequest - -// required uint32 id = 1; -inline bool CloseSessionRequest::has_id() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void CloseSessionRequest::set_has_id() { - _has_bits_[0] |= 0x00000001u; -} -inline void CloseSessionRequest::clear_has_id() { - _has_bits_[0] &= ~0x00000001u; -} -inline void CloseSessionRequest::clear_id() { - id_ = 0u; - clear_has_id(); -} -inline ::google::protobuf::uint32 CloseSessionRequest::id() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.CloseSessionRequest.id) - return id_; -} -inline void CloseSessionRequest::set_id(::google::protobuf::uint32 value) { - set_has_id(); - id_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.CloseSessionRequest.id) -} - -// ------------------------------------------------------------------- - -// CloseSessionResponse - -// ------------------------------------------------------------------- - -// NotifyRequest_Buffers - -// required uint64 sva = 1; -inline bool NotifyRequest_Buffers::has_sva() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void NotifyRequest_Buffers::set_has_sva() { - _has_bits_[0] |= 0x00000001u; -} -inline void NotifyRequest_Buffers::clear_has_sva() { - _has_bits_[0] &= ~0x00000001u; -} -inline void NotifyRequest_Buffers::clear_sva() { - sva_ = GOOGLE_ULONGLONG(0); - clear_has_sva(); -} -inline ::google::protobuf::uint64 NotifyRequest_Buffers::sva() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.NotifyRequest.Buffers.sva) - return sva_; -} -inline void NotifyRequest_Buffers::set_sva(::google::protobuf::uint64 value) { - set_has_sva(); - sva_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.NotifyRequest.Buffers.sva) -} - -// required bytes data = 2; -inline bool NotifyRequest_Buffers::has_data() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void NotifyRequest_Buffers::set_has_data() { - _has_bits_[0] |= 0x00000002u; -} -inline void NotifyRequest_Buffers::clear_has_data() { - _has_bits_[0] &= ~0x00000002u; -} -inline void NotifyRequest_Buffers::clear_data() { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_->clear(); - } - clear_has_data(); -} -inline const ::std::string& NotifyRequest_Buffers::data() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.NotifyRequest.Buffers.data) - return *data_; -} -inline void NotifyRequest_Buffers::set_data(const ::std::string& value) { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - data_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.NotifyRequest.Buffers.data) -} -inline void NotifyRequest_Buffers::set_data(const char* value) { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - data_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.NotifyRequest.Buffers.data) -} -inline void NotifyRequest_Buffers::set_data(const void* value, size_t size) { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - data_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.NotifyRequest.Buffers.data) -} -inline ::std::string* NotifyRequest_Buffers::mutable_data() { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.NotifyRequest.Buffers.data) - return data_; -} -inline ::std::string* NotifyRequest_Buffers::release_data() { - clear_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = data_; - data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void NotifyRequest_Buffers::set_allocated_data(::std::string* data) { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete data_; - } - if (data) { - set_has_data(); - data_ = data; - } else { - clear_has_data(); - data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.NotifyRequest.Buffers.data) -} - -// ------------------------------------------------------------------- - -// NotifyRequest - -// required uint32 sid = 1; -inline bool NotifyRequest::has_sid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void NotifyRequest::set_has_sid() { - _has_bits_[0] |= 0x00000001u; -} -inline void NotifyRequest::clear_has_sid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void NotifyRequest::clear_sid() { - sid_ = 0u; - clear_has_sid(); -} -inline ::google::protobuf::uint32 NotifyRequest::sid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.NotifyRequest.sid) - return sid_; -} -inline void NotifyRequest::set_sid(::google::protobuf::uint32 value) { - set_has_sid(); - sid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.NotifyRequest.sid) -} - -// optional bytes tci = 2; -inline bool NotifyRequest::has_tci() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void NotifyRequest::set_has_tci() { - _has_bits_[0] |= 0x00000002u; -} -inline void NotifyRequest::clear_has_tci() { - _has_bits_[0] &= ~0x00000002u; -} -inline void NotifyRequest::clear_tci() { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - clear_has_tci(); -} -inline const ::std::string& NotifyRequest::tci() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.NotifyRequest.tci) - return *tci_; -} -inline void NotifyRequest::set_tci(const ::std::string& value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.NotifyRequest.tci) -} -inline void NotifyRequest::set_tci(const char* value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.NotifyRequest.tci) -} -inline void NotifyRequest::set_tci(const void* value, size_t size) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.NotifyRequest.tci) -} -inline ::std::string* NotifyRequest::mutable_tci() { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.NotifyRequest.tci) - return tci_; -} -inline ::std::string* NotifyRequest::release_tci() { - clear_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = tci_; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void NotifyRequest::set_allocated_tci(::std::string* tci) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - if (tci) { - set_has_tci(); - tci_ = tci; - } else { - clear_has_tci(); - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.NotifyRequest.tci) -} - -// repeated .com.trustonic.tee_proxy.NotifyRequest.Buffers buffers = 3; -inline int NotifyRequest::buffers_size() const { - return buffers_.size(); -} -inline void NotifyRequest::clear_buffers() { - buffers_.Clear(); -} -inline const ::com::trustonic::tee_proxy::NotifyRequest_Buffers& NotifyRequest::buffers(int index) const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.NotifyRequest.buffers) - return buffers_.Get(index); -} -inline ::com::trustonic::tee_proxy::NotifyRequest_Buffers* NotifyRequest::mutable_buffers(int index) { - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.NotifyRequest.buffers) - return buffers_.Mutable(index); -} -inline ::com::trustonic::tee_proxy::NotifyRequest_Buffers* NotifyRequest::add_buffers() { - // @@protoc_insertion_point(field_add:com.trustonic.tee_proxy.NotifyRequest.buffers) - return buffers_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::NotifyRequest_Buffers >& -NotifyRequest::buffers() const { - // @@protoc_insertion_point(field_list:com.trustonic.tee_proxy.NotifyRequest.buffers) - return buffers_; -} -inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::NotifyRequest_Buffers >* -NotifyRequest::mutable_buffers() { - // @@protoc_insertion_point(field_mutable_list:com.trustonic.tee_proxy.NotifyRequest.buffers) - return &buffers_; -} - -// ------------------------------------------------------------------- - -// NotifyResponse - -// ------------------------------------------------------------------- - -// WaitNotificationRequest - -// required uint32 sid = 1; -inline bool WaitNotificationRequest::has_sid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void WaitNotificationRequest::set_has_sid() { - _has_bits_[0] |= 0x00000001u; -} -inline void WaitNotificationRequest::clear_has_sid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void WaitNotificationRequest::clear_sid() { - sid_ = 0u; - clear_has_sid(); -} -inline ::google::protobuf::uint32 WaitNotificationRequest::sid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationRequest.sid) - return sid_; -} -inline void WaitNotificationRequest::set_sid(::google::protobuf::uint32 value) { - set_has_sid(); - sid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.WaitNotificationRequest.sid) -} - -// required sint32 timeout = 2; -inline bool WaitNotificationRequest::has_timeout() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void WaitNotificationRequest::set_has_timeout() { - _has_bits_[0] |= 0x00000002u; -} -inline void WaitNotificationRequest::clear_has_timeout() { - _has_bits_[0] &= ~0x00000002u; -} -inline void WaitNotificationRequest::clear_timeout() { - timeout_ = 0; - clear_has_timeout(); -} -inline ::google::protobuf::int32 WaitNotificationRequest::timeout() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationRequest.timeout) - return timeout_; -} -inline void WaitNotificationRequest::set_timeout(::google::protobuf::int32 value) { - set_has_timeout(); - timeout_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.WaitNotificationRequest.timeout) -} - -// required bool partial = 3; -inline bool WaitNotificationRequest::has_partial() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void WaitNotificationRequest::set_has_partial() { - _has_bits_[0] |= 0x00000004u; -} -inline void WaitNotificationRequest::clear_has_partial() { - _has_bits_[0] &= ~0x00000004u; -} -inline void WaitNotificationRequest::clear_partial() { - partial_ = false; - clear_has_partial(); -} -inline bool WaitNotificationRequest::partial() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationRequest.partial) - return partial_; -} -inline void WaitNotificationRequest::set_partial(bool value) { - set_has_partial(); - partial_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.WaitNotificationRequest.partial) -} - -// ------------------------------------------------------------------- - -// WaitNotificationResponse_Buffers - -// required uint64 sva = 1; -inline bool WaitNotificationResponse_Buffers::has_sva() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void WaitNotificationResponse_Buffers::set_has_sva() { - _has_bits_[0] |= 0x00000001u; -} -inline void WaitNotificationResponse_Buffers::clear_has_sva() { - _has_bits_[0] &= ~0x00000001u; -} -inline void WaitNotificationResponse_Buffers::clear_sva() { - sva_ = GOOGLE_ULONGLONG(0); - clear_has_sva(); -} -inline ::google::protobuf::uint64 WaitNotificationResponse_Buffers::sva() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.sva) - return sva_; -} -inline void WaitNotificationResponse_Buffers::set_sva(::google::protobuf::uint64 value) { - set_has_sva(); - sva_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.sva) -} - -// required bytes data = 2; -inline bool WaitNotificationResponse_Buffers::has_data() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void WaitNotificationResponse_Buffers::set_has_data() { - _has_bits_[0] |= 0x00000002u; -} -inline void WaitNotificationResponse_Buffers::clear_has_data() { - _has_bits_[0] &= ~0x00000002u; -} -inline void WaitNotificationResponse_Buffers::clear_data() { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_->clear(); - } - clear_has_data(); -} -inline const ::std::string& WaitNotificationResponse_Buffers::data() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.data) - return *data_; -} -inline void WaitNotificationResponse_Buffers::set_data(const ::std::string& value) { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - data_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.data) -} -inline void WaitNotificationResponse_Buffers::set_data(const char* value) { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - data_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.data) -} -inline void WaitNotificationResponse_Buffers::set_data(const void* value, size_t size) { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - data_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.data) -} -inline ::std::string* WaitNotificationResponse_Buffers::mutable_data() { - set_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - data_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.data) - return data_; -} -inline ::std::string* WaitNotificationResponse_Buffers::release_data() { - clear_has_data(); - if (data_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = data_; - data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void WaitNotificationResponse_Buffers::set_allocated_data(::std::string* data) { - if (data_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete data_; - } - if (data) { - set_has_data(); - data_ = data; - } else { - clear_has_data(); - data_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.WaitNotificationResponse.Buffers.data) -} - -// ------------------------------------------------------------------- - -// WaitNotificationResponse - -// optional bytes tci = 1; -inline bool WaitNotificationResponse::has_tci() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void WaitNotificationResponse::set_has_tci() { - _has_bits_[0] |= 0x00000001u; -} -inline void WaitNotificationResponse::clear_has_tci() { - _has_bits_[0] &= ~0x00000001u; -} -inline void WaitNotificationResponse::clear_tci() { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_->clear(); - } - clear_has_tci(); -} -inline const ::std::string& WaitNotificationResponse::tci() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationResponse.tci) - return *tci_; -} -inline void WaitNotificationResponse::set_tci(const ::std::string& value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.WaitNotificationResponse.tci) -} -inline void WaitNotificationResponse::set_tci(const char* value) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.WaitNotificationResponse.tci) -} -inline void WaitNotificationResponse::set_tci(const void* value, size_t size) { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - tci_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.WaitNotificationResponse.tci) -} -inline ::std::string* WaitNotificationResponse::mutable_tci() { - set_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - tci_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.WaitNotificationResponse.tci) - return tci_; -} -inline ::std::string* WaitNotificationResponse::release_tci() { - clear_has_tci(); - if (tci_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = tci_; - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void WaitNotificationResponse::set_allocated_tci(::std::string* tci) { - if (tci_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete tci_; - } - if (tci) { - set_has_tci(); - tci_ = tci; - } else { - clear_has_tci(); - tci_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.WaitNotificationResponse.tci) -} - -// repeated .com.trustonic.tee_proxy.WaitNotificationResponse.Buffers buffers = 2; -inline int WaitNotificationResponse::buffers_size() const { - return buffers_.size(); -} -inline void WaitNotificationResponse::clear_buffers() { - buffers_.Clear(); -} -inline const ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers& WaitNotificationResponse::buffers(int index) const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.WaitNotificationResponse.buffers) - return buffers_.Get(index); -} -inline ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers* WaitNotificationResponse::mutable_buffers(int index) { - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.WaitNotificationResponse.buffers) - return buffers_.Mutable(index); -} -inline ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers* WaitNotificationResponse::add_buffers() { - // @@protoc_insertion_point(field_add:com.trustonic.tee_proxy.WaitNotificationResponse.buffers) - return buffers_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers >& -WaitNotificationResponse::buffers() const { - // @@protoc_insertion_point(field_list:com.trustonic.tee_proxy.WaitNotificationResponse.buffers) - return buffers_; -} -inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::WaitNotificationResponse_Buffers >* -WaitNotificationResponse::mutable_buffers() { - // @@protoc_insertion_point(field_mutable_list:com.trustonic.tee_proxy.WaitNotificationResponse.buffers) - return &buffers_; -} - -// ------------------------------------------------------------------- - -// MapRequest_Buffers - -// required uint32 len = 1; -inline bool MapRequest_Buffers::has_len() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void MapRequest_Buffers::set_has_len() { - _has_bits_[0] |= 0x00000001u; -} -inline void MapRequest_Buffers::clear_has_len() { - _has_bits_[0] &= ~0x00000001u; -} -inline void MapRequest_Buffers::clear_len() { - len_ = 0u; - clear_has_len(); -} -inline ::google::protobuf::uint32 MapRequest_Buffers::len() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.MapRequest.Buffers.len) - return len_; -} -inline void MapRequest_Buffers::set_len(::google::protobuf::uint32 value) { - set_has_len(); - len_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.MapRequest.Buffers.len) -} - -// required uint32 flags = 2; -inline bool MapRequest_Buffers::has_flags() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void MapRequest_Buffers::set_has_flags() { - _has_bits_[0] |= 0x00000002u; -} -inline void MapRequest_Buffers::clear_has_flags() { - _has_bits_[0] &= ~0x00000002u; -} -inline void MapRequest_Buffers::clear_flags() { - flags_ = 0u; - clear_has_flags(); -} -inline ::google::protobuf::uint32 MapRequest_Buffers::flags() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.MapRequest.Buffers.flags) - return flags_; -} -inline void MapRequest_Buffers::set_flags(::google::protobuf::uint32 value) { - set_has_flags(); - flags_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.MapRequest.Buffers.flags) -} - -// ------------------------------------------------------------------- - -// MapRequest - -// required uint32 sid = 1; -inline bool MapRequest::has_sid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void MapRequest::set_has_sid() { - _has_bits_[0] |= 0x00000001u; -} -inline void MapRequest::clear_has_sid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void MapRequest::clear_sid() { - sid_ = 0u; - clear_has_sid(); -} -inline ::google::protobuf::uint32 MapRequest::sid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.MapRequest.sid) - return sid_; -} -inline void MapRequest::set_sid(::google::protobuf::uint32 value) { - set_has_sid(); - sid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.MapRequest.sid) -} - -// repeated .com.trustonic.tee_proxy.MapRequest.Buffers buffers = 2; -inline int MapRequest::buffers_size() const { - return buffers_.size(); -} -inline void MapRequest::clear_buffers() { - buffers_.Clear(); -} -inline const ::com::trustonic::tee_proxy::MapRequest_Buffers& MapRequest::buffers(int index) const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.MapRequest.buffers) - return buffers_.Get(index); -} -inline ::com::trustonic::tee_proxy::MapRequest_Buffers* MapRequest::mutable_buffers(int index) { - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.MapRequest.buffers) - return buffers_.Mutable(index); -} -inline ::com::trustonic::tee_proxy::MapRequest_Buffers* MapRequest::add_buffers() { - // @@protoc_insertion_point(field_add:com.trustonic.tee_proxy.MapRequest.buffers) - return buffers_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapRequest_Buffers >& -MapRequest::buffers() const { - // @@protoc_insertion_point(field_list:com.trustonic.tee_proxy.MapRequest.buffers) - return buffers_; -} -inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapRequest_Buffers >* -MapRequest::mutable_buffers() { - // @@protoc_insertion_point(field_mutable_list:com.trustonic.tee_proxy.MapRequest.buffers) - return &buffers_; -} - -// ------------------------------------------------------------------- - -// MapResponse_Buffers - -// required uint64 sva = 1; -inline bool MapResponse_Buffers::has_sva() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void MapResponse_Buffers::set_has_sva() { - _has_bits_[0] |= 0x00000001u; -} -inline void MapResponse_Buffers::clear_has_sva() { - _has_bits_[0] &= ~0x00000001u; -} -inline void MapResponse_Buffers::clear_sva() { - sva_ = GOOGLE_ULONGLONG(0); - clear_has_sva(); -} -inline ::google::protobuf::uint64 MapResponse_Buffers::sva() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.MapResponse.Buffers.sva) - return sva_; -} -inline void MapResponse_Buffers::set_sva(::google::protobuf::uint64 value) { - set_has_sva(); - sva_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.MapResponse.Buffers.sva) -} - -// ------------------------------------------------------------------- - -// MapResponse - -// repeated .com.trustonic.tee_proxy.MapResponse.Buffers buffers = 1; -inline int MapResponse::buffers_size() const { - return buffers_.size(); -} -inline void MapResponse::clear_buffers() { - buffers_.Clear(); -} -inline const ::com::trustonic::tee_proxy::MapResponse_Buffers& MapResponse::buffers(int index) const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.MapResponse.buffers) - return buffers_.Get(index); -} -inline ::com::trustonic::tee_proxy::MapResponse_Buffers* MapResponse::mutable_buffers(int index) { - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.MapResponse.buffers) - return buffers_.Mutable(index); -} -inline ::com::trustonic::tee_proxy::MapResponse_Buffers* MapResponse::add_buffers() { - // @@protoc_insertion_point(field_add:com.trustonic.tee_proxy.MapResponse.buffers) - return buffers_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapResponse_Buffers >& -MapResponse::buffers() const { - // @@protoc_insertion_point(field_list:com.trustonic.tee_proxy.MapResponse.buffers) - return buffers_; -} -inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::MapResponse_Buffers >* -MapResponse::mutable_buffers() { - // @@protoc_insertion_point(field_mutable_list:com.trustonic.tee_proxy.MapResponse.buffers) - return &buffers_; -} - -// ------------------------------------------------------------------- - -// UnmapRequest_Buffers - -// required uint64 sva = 1; -inline bool UnmapRequest_Buffers::has_sva() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void UnmapRequest_Buffers::set_has_sva() { - _has_bits_[0] |= 0x00000001u; -} -inline void UnmapRequest_Buffers::clear_has_sva() { - _has_bits_[0] &= ~0x00000001u; -} -inline void UnmapRequest_Buffers::clear_sva() { - sva_ = GOOGLE_ULONGLONG(0); - clear_has_sva(); -} -inline ::google::protobuf::uint64 UnmapRequest_Buffers::sva() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.UnmapRequest.Buffers.sva) - return sva_; -} -inline void UnmapRequest_Buffers::set_sva(::google::protobuf::uint64 value) { - set_has_sva(); - sva_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.UnmapRequest.Buffers.sva) -} - -// ------------------------------------------------------------------- - -// UnmapRequest - -// required uint32 sid = 1; -inline bool UnmapRequest::has_sid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void UnmapRequest::set_has_sid() { - _has_bits_[0] |= 0x00000001u; -} -inline void UnmapRequest::clear_has_sid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void UnmapRequest::clear_sid() { - sid_ = 0u; - clear_has_sid(); -} -inline ::google::protobuf::uint32 UnmapRequest::sid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.UnmapRequest.sid) - return sid_; -} -inline void UnmapRequest::set_sid(::google::protobuf::uint32 value) { - set_has_sid(); - sid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.UnmapRequest.sid) -} - -// repeated .com.trustonic.tee_proxy.UnmapRequest.Buffers buffers = 2; -inline int UnmapRequest::buffers_size() const { - return buffers_.size(); -} -inline void UnmapRequest::clear_buffers() { - buffers_.Clear(); -} -inline const ::com::trustonic::tee_proxy::UnmapRequest_Buffers& UnmapRequest::buffers(int index) const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.UnmapRequest.buffers) - return buffers_.Get(index); -} -inline ::com::trustonic::tee_proxy::UnmapRequest_Buffers* UnmapRequest::mutable_buffers(int index) { - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.UnmapRequest.buffers) - return buffers_.Mutable(index); -} -inline ::com::trustonic::tee_proxy::UnmapRequest_Buffers* UnmapRequest::add_buffers() { - // @@protoc_insertion_point(field_add:com.trustonic.tee_proxy.UnmapRequest.buffers) - return buffers_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::UnmapRequest_Buffers >& -UnmapRequest::buffers() const { - // @@protoc_insertion_point(field_list:com.trustonic.tee_proxy.UnmapRequest.buffers) - return buffers_; -} -inline ::google::protobuf::RepeatedPtrField< ::com::trustonic::tee_proxy::UnmapRequest_Buffers >* -UnmapRequest::mutable_buffers() { - // @@protoc_insertion_point(field_mutable_list:com.trustonic.tee_proxy.UnmapRequest.buffers) - return &buffers_; -} - -// ------------------------------------------------------------------- - -// UnmapResponse - -// ------------------------------------------------------------------- - -// GetErrorRequest - -// required uint32 sid = 1; -inline bool GetErrorRequest::has_sid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void GetErrorRequest::set_has_sid() { - _has_bits_[0] |= 0x00000001u; -} -inline void GetErrorRequest::clear_has_sid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void GetErrorRequest::clear_sid() { - sid_ = 0u; - clear_has_sid(); -} -inline ::google::protobuf::uint32 GetErrorRequest::sid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetErrorRequest.sid) - return sid_; -} -inline void GetErrorRequest::set_sid(::google::protobuf::uint32 value) { - set_has_sid(); - sid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetErrorRequest.sid) -} - -// ------------------------------------------------------------------- - -// GetErrorResponse - -// required sint32 exit_code = 1; -inline bool GetErrorResponse::has_exit_code() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void GetErrorResponse::set_has_exit_code() { - _has_bits_[0] |= 0x00000001u; -} -inline void GetErrorResponse::clear_has_exit_code() { - _has_bits_[0] &= ~0x00000001u; -} -inline void GetErrorResponse::clear_exit_code() { - exit_code_ = 0; - clear_has_exit_code(); -} -inline ::google::protobuf::int32 GetErrorResponse::exit_code() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetErrorResponse.exit_code) - return exit_code_; -} -inline void GetErrorResponse::set_exit_code(::google::protobuf::int32 value) { - set_has_exit_code(); - exit_code_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetErrorResponse.exit_code) -} - -// ------------------------------------------------------------------- - -// GetVersionRequest - -// ------------------------------------------------------------------- - -// GetVersionResponse - -// required string product_id = 1; -inline bool GetVersionResponse::has_product_id() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void GetVersionResponse::set_has_product_id() { - _has_bits_[0] |= 0x00000001u; -} -inline void GetVersionResponse::clear_has_product_id() { - _has_bits_[0] &= ~0x00000001u; -} -inline void GetVersionResponse::clear_product_id() { - if (product_id_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - product_id_->clear(); - } - clear_has_product_id(); -} -inline const ::std::string& GetVersionResponse::product_id() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.product_id) - return *product_id_; -} -inline void GetVersionResponse::set_product_id(const ::std::string& value) { - set_has_product_id(); - if (product_id_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - product_id_ = new ::std::string; - } - product_id_->assign(value); - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.product_id) -} -inline void GetVersionResponse::set_product_id(const char* value) { - set_has_product_id(); - if (product_id_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - product_id_ = new ::std::string; - } - product_id_->assign(value); - // @@protoc_insertion_point(field_set_char:com.trustonic.tee_proxy.GetVersionResponse.product_id) -} -inline void GetVersionResponse::set_product_id(const char* value, size_t size) { - set_has_product_id(); - if (product_id_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - product_id_ = new ::std::string; - } - product_id_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:com.trustonic.tee_proxy.GetVersionResponse.product_id) -} -inline ::std::string* GetVersionResponse::mutable_product_id() { - set_has_product_id(); - if (product_id_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - product_id_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:com.trustonic.tee_proxy.GetVersionResponse.product_id) - return product_id_; -} -inline ::std::string* GetVersionResponse::release_product_id() { - clear_has_product_id(); - if (product_id_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = product_id_; - product_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void GetVersionResponse::set_allocated_product_id(::std::string* product_id) { - if (product_id_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete product_id_; - } - if (product_id) { - set_has_product_id(); - product_id_ = product_id; - } else { - clear_has_product_id(); - product_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:com.trustonic.tee_proxy.GetVersionResponse.product_id) -} - -// required uint32 mci = 2; -inline bool GetVersionResponse::has_mci() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void GetVersionResponse::set_has_mci() { - _has_bits_[0] |= 0x00000002u; -} -inline void GetVersionResponse::clear_has_mci() { - _has_bits_[0] &= ~0x00000002u; -} -inline void GetVersionResponse::clear_mci() { - mci_ = 0u; - clear_has_mci(); -} -inline ::google::protobuf::uint32 GetVersionResponse::mci() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.mci) - return mci_; -} -inline void GetVersionResponse::set_mci(::google::protobuf::uint32 value) { - set_has_mci(); - mci_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.mci) -} - -// required uint32 so = 3; -inline bool GetVersionResponse::has_so() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void GetVersionResponse::set_has_so() { - _has_bits_[0] |= 0x00000004u; -} -inline void GetVersionResponse::clear_has_so() { - _has_bits_[0] &= ~0x00000004u; -} -inline void GetVersionResponse::clear_so() { - so_ = 0u; - clear_has_so(); -} -inline ::google::protobuf::uint32 GetVersionResponse::so() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.so) - return so_; -} -inline void GetVersionResponse::set_so(::google::protobuf::uint32 value) { - set_has_so(); - so_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.so) -} - -// required uint32 mclf = 4; -inline bool GetVersionResponse::has_mclf() const { - return (_has_bits_[0] & 0x00000008u) != 0; -} -inline void GetVersionResponse::set_has_mclf() { - _has_bits_[0] |= 0x00000008u; -} -inline void GetVersionResponse::clear_has_mclf() { - _has_bits_[0] &= ~0x00000008u; -} -inline void GetVersionResponse::clear_mclf() { - mclf_ = 0u; - clear_has_mclf(); -} -inline ::google::protobuf::uint32 GetVersionResponse::mclf() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.mclf) - return mclf_; -} -inline void GetVersionResponse::set_mclf(::google::protobuf::uint32 value) { - set_has_mclf(); - mclf_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.mclf) -} - -// required uint32 container = 5; -inline bool GetVersionResponse::has_container() const { - return (_has_bits_[0] & 0x00000010u) != 0; -} -inline void GetVersionResponse::set_has_container() { - _has_bits_[0] |= 0x00000010u; -} -inline void GetVersionResponse::clear_has_container() { - _has_bits_[0] &= ~0x00000010u; -} -inline void GetVersionResponse::clear_container() { - container_ = 0u; - clear_has_container(); -} -inline ::google::protobuf::uint32 GetVersionResponse::container() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.container) - return container_; -} -inline void GetVersionResponse::set_container(::google::protobuf::uint32 value) { - set_has_container(); - container_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.container) -} - -// required uint32 mc_config = 6; -inline bool GetVersionResponse::has_mc_config() const { - return (_has_bits_[0] & 0x00000020u) != 0; -} -inline void GetVersionResponse::set_has_mc_config() { - _has_bits_[0] |= 0x00000020u; -} -inline void GetVersionResponse::clear_has_mc_config() { - _has_bits_[0] &= ~0x00000020u; -} -inline void GetVersionResponse::clear_mc_config() { - mc_config_ = 0u; - clear_has_mc_config(); -} -inline ::google::protobuf::uint32 GetVersionResponse::mc_config() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.mc_config) - return mc_config_; -} -inline void GetVersionResponse::set_mc_config(::google::protobuf::uint32 value) { - set_has_mc_config(); - mc_config_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.mc_config) -} - -// required uint32 tl_api = 7; -inline bool GetVersionResponse::has_tl_api() const { - return (_has_bits_[0] & 0x00000040u) != 0; -} -inline void GetVersionResponse::set_has_tl_api() { - _has_bits_[0] |= 0x00000040u; -} -inline void GetVersionResponse::clear_has_tl_api() { - _has_bits_[0] &= ~0x00000040u; -} -inline void GetVersionResponse::clear_tl_api() { - tl_api_ = 0u; - clear_has_tl_api(); -} -inline ::google::protobuf::uint32 GetVersionResponse::tl_api() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.tl_api) - return tl_api_; -} -inline void GetVersionResponse::set_tl_api(::google::protobuf::uint32 value) { - set_has_tl_api(); - tl_api_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.tl_api) -} - -// required uint32 dr_api = 8; -inline bool GetVersionResponse::has_dr_api() const { - return (_has_bits_[0] & 0x00000080u) != 0; -} -inline void GetVersionResponse::set_has_dr_api() { - _has_bits_[0] |= 0x00000080u; -} -inline void GetVersionResponse::clear_has_dr_api() { - _has_bits_[0] &= ~0x00000080u; -} -inline void GetVersionResponse::clear_dr_api() { - dr_api_ = 0u; - clear_has_dr_api(); -} -inline ::google::protobuf::uint32 GetVersionResponse::dr_api() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.dr_api) - return dr_api_; -} -inline void GetVersionResponse::set_dr_api(::google::protobuf::uint32 value) { - set_has_dr_api(); - dr_api_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.dr_api) -} - -// required uint32 nwd = 9; -inline bool GetVersionResponse::has_nwd() const { - return (_has_bits_[0] & 0x00000100u) != 0; -} -inline void GetVersionResponse::set_has_nwd() { - _has_bits_[0] |= 0x00000100u; -} -inline void GetVersionResponse::clear_has_nwd() { - _has_bits_[0] &= ~0x00000100u; -} -inline void GetVersionResponse::clear_nwd() { - nwd_ = 0u; - clear_has_nwd(); -} -inline ::google::protobuf::uint32 GetVersionResponse::nwd() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GetVersionResponse.nwd) - return nwd_; -} -inline void GetVersionResponse::set_nwd(::google::protobuf::uint32 value) { - set_has_nwd(); - nwd_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GetVersionResponse.nwd) -} - -// ------------------------------------------------------------------- - -// GpRequestCancellationRequest - -// required uint32 sid = 1; -inline bool GpRequestCancellationRequest::has_sid() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void GpRequestCancellationRequest::set_has_sid() { - _has_bits_[0] |= 0x00000001u; -} -inline void GpRequestCancellationRequest::clear_has_sid() { - _has_bits_[0] &= ~0x00000001u; -} -inline void GpRequestCancellationRequest::clear_sid() { - sid_ = 0u; - clear_has_sid(); -} -inline ::google::protobuf::uint32 GpRequestCancellationRequest::sid() const { - // @@protoc_insertion_point(field_get:com.trustonic.tee_proxy.GpRequestCancellationRequest.sid) - return sid_; -} -inline void GpRequestCancellationRequest::set_sid(::google::protobuf::uint32 value) { - set_has_sid(); - sid_ = value; - // @@protoc_insertion_point(field_set:com.trustonic.tee_proxy.GpRequestCancellationRequest.sid) -} - -// ------------------------------------------------------------------- - -// GpRequestCancellationResponse - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace tee_proxy -} // namespace trustonic -} // namespace com - -// @@protoc_insertion_point(global_scope) - -#endif // PROTOBUF_mc_2eproto__INCLUDED diff --git a/mobicore/ClientLib/src/mc_client_api.cpp b/mobicore/ClientLib/src/mc_client_api.cpp deleted file mode 100644 index 1d356a6..0000000 --- a/mobicore/ClientLib/src/mc_client_api.cpp +++ /dev/null @@ -1,794 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#undef LOG_TAG -#define LOG_TAG "TeeMcClient" -#include "log.h" -#include "MobiCoreDriverApi.h" -#include "common_client.h" -#include "buildTag.h" - -static const __attribute__((used)) char* buildtag = - MOBICORE_COMPONENT_BUILD_TAG; - -//------------------------------------------------------------------------------ - -/* - * On mcCloseDevice(), all mappings need to be removed, which means we need to - * keep them somewhere. We keep them in an array, resized when needed. - * Both map and length must be kept in user-space, as after a fork another - * mapping with same address may have appeared from the other process(es). - */ -struct maplen { - uint8_t* wsm; - uint32_t len; -}; - -static struct maplen* wsms; -static size_t wsms_capacity, wsms_length; -static pthread_mutex_t wsms_mutex = PTHREAD_MUTEX_INITIALIZER; - -static CommonClient& client = CommonClient::getInstance(); - -static inline int wsms_add(uint8_t* wsm, uint32_t len) { - int ret = 0; - pthread_mutex_lock(&wsms_mutex); - if (wsms_length == wsms_capacity) { - size_t new_wsms_capacity = wsms_capacity; - /* Need some room */ - if (new_wsms_capacity == 0) { - new_wsms_capacity = 16; - } else { - new_wsms_capacity *= 2; - } - struct maplen* new_wsms = static_cast(realloc(wsms, - new_wsms_capacity * sizeof(*wsms))); - if (!new_wsms) { - LOG_ERRNO("resize WSMs array"); - ret = -1; - } else { - wsms = new_wsms; - wsms_capacity = new_wsms_capacity; - } - } - if (ret == 0) { - wsms[wsms_length].wsm = wsm; - wsms[wsms_length].len = len; - wsms_length++; - LOG_D("add %p %d", wsm, len); - } - pthread_mutex_unlock(&wsms_mutex); - return ret; -} - -static inline int wsms_remove(uint8_t* wsm) { - int ret = 0; - pthread_mutex_lock(&wsms_mutex); - /* Find position of WSM */ - size_t i; - for (i = 0; i < wsms_length; i++) { - if (wsms[i].wsm == wsm) { - break; - } - } - if (i == wsms_length) { - LOG_E("WSM %p not found in array", wsm); - ret = -1; - } else { - /* Replace WSM with last so the first free element remains wsms[wsms_length] */ - wsms[i] = wsms[--wsms_length]; - LOG_D("rm %p", wsm); - } - pthread_mutex_unlock(&wsms_mutex); - return ret; -} - -static inline int wsms_len(uint8_t* wsm) { - int len = -1; - pthread_mutex_lock(&wsms_mutex); - for (size_t i = 0; i < wsms_length; i++) { - if (wsms[i].wsm == wsm) { - len = wsms[i].len; - LOG_D("rm len %p %d", wsm, len); - break; - } - } - pthread_mutex_unlock(&wsms_mutex); - return len; -} - -static inline struct maplen wsms_getLast(void) { - struct maplen wsm; - pthread_mutex_lock(&wsms_mutex); - if (wsms_length > 0) { - wsm = wsms[wsms_length - 1]; - LOG_D("rm last %p", wsm.wsm); - } else { - wsm.wsm = NULL; - // To make Coverity happy - wsm.len = 0; - } - pthread_mutex_unlock(&wsms_mutex); - return wsm; -} - -/* Only 1 device is supported */ -static inline bool isValidDevice(uint32_t deviceId) { - return (MC_DEVICE_ID_DEFAULT == deviceId); -} - -/* Convert driver errors into tbase set */ -static mcResult_t convert_syscall_error(int32_t ret) { - switch (ret) { - case 0: - return MC_DRV_OK; - case -1: - switch (errno) { - case ENOMSG: - return MC_DRV_NO_NOTIFICATION; - case EBADMSG: - return MC_DRV_ERR_NOTIFICATION; - case ENOSPC: - return MC_DRV_ERR_OUT_OF_RESOURCES; - case EHOSTDOWN: - return MC_DRV_ERR_INIT; - case ENODEV: - return MC_DRV_ERR_UNKNOWN_DEVICE; - case ENXIO: - return MC_DRV_ERR_UNKNOWN_SESSION; - case EPERM: - return MC_DRV_ERR_INVALID_OPERATION; - case EBADE: - return MC_DRV_ERR_INVALID_RESPONSE; - case ETIME: - return MC_DRV_ERR_TIMEOUT; - case ENOMEM: - return MC_DRV_ERR_NO_FREE_MEMORY; - case EUCLEAN: - return MC_DRV_ERR_FREE_MEMORY_FAILED; - case ENOTEMPTY: - return MC_DRV_ERR_SESSION_PENDING; - case EHOSTUNREACH: - return MC_DRV_ERR_DAEMON_UNREACHABLE; - case ENOENT: - return MC_DRV_ERR_INVALID_DEVICE_FILE; - case EINVAL: - return MC_DRV_ERR_INVALID_PARAMETER; - case EPROTO: - return MC_DRV_ERR_KERNEL_MODULE; - case EADDRINUSE: - return MC_DRV_ERR_BULK_MAPPING; - case EADDRNOTAVAIL: - return MC_DRV_ERR_BULK_UNMAPPING; - case ECOMM: - return MC_DRV_INFO_NOTIFICATION; - case EUNATCH: - return MC_DRV_ERR_NQ_FAILED; - case EBADF: - return MC_DRV_ERR_DAEMON_DEVICE_NOT_OPEN; - case EINTR: - return MC_DRV_ERR_INTERRUPTED_BY_SIGNAL; - case EKEYREJECTED: - return MC_DRV_ERR_WRONG_PUBLIC_KEY; - case ECONNREFUSED: - return MC_DRV_ERR_SERVICE_BLOCKED; - case ECONNABORTED: - return MC_DRV_ERR_SERVICE_LOCKED; - case ECONNRESET: - return MC_DRV_ERR_SERVICE_KILLED; - default: - LOG_ERRNO("syscall"); - return MC_DRV_ERR_UNKNOWN; - } - default: - LOG_E("Unknown code %d", ret); - return MC_DRV_ERR_UNKNOWN; - } -} - -//------------------------------------------------------------------------------ -// CLIENT API -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcOpenDevice( - uint32_t deviceId -) { - LOG_D("===%s(%i)===", __FUNCTION__, deviceId); - - // Check parameters - if (!isValidDevice(deviceId) && - (deviceId != CommonClient::DRIVER) && - (deviceId != CommonClient::PROXY)) { - return MC_DRV_ERR_UNKNOWN_DEVICE; - } - - // For test purpose - switch (deviceId) { - case CommonClient::DRIVER: - client.setOpenMode(CommonClient::DRIVER); - break; - case CommonClient::PROXY: - client.setOpenMode(CommonClient::PROXY); - break; - } - - if (client.open()) { - return convert_syscall_error(-1); - } - - return MC_DRV_OK; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcCloseDevice( - uint32_t deviceId -) { - LOG_D("===%s(%i)===", __FUNCTION__, deviceId); - - // Check parameters - if (!isValidDevice(deviceId)) { - return MC_DRV_ERR_UNKNOWN_DEVICE; - } - - // Check whether there are still some 'devices open' - if (client.closeCheck() == 0) { - return MC_DRV_OK; - } - - // Check that all sessions are closed for client - mcResult_t mcResult = convert_syscall_error(client.hasOpenSessions()); - if (mcResult != MC_DRV_OK) { - return mcResult; - } - - // Free all remaining WSMs - while (true) { - struct maplen wsm = wsms_getLast(); - if (wsm.wsm == NULL) { - break; - } - mcFreeWsm(deviceId, wsm.wsm); - } - - // Close the device - client.close(); - return MC_DRV_OK; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcOpenSession( - mcSessionHandle_t* session, - const mcUuid_t* uuid, - uint8_t* tci, - uint32_t len -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - struct mc_ioctl_open_session sess; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!uuid) { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - - // Call ioctl - sess.sid = 0; - memcpy( (void*)&sess.uuid, uuid, sizeof(sess.uuid) ); - sess.tci = (uintptr_t)tci; - sess.tcilen = len; - sess.is_gp_uuid = false; - sess.identity.login_type = LOGIN_PUBLIC; - sess.identity.pid = 0; - ret = client.openSession(sess); - mcResult = convert_syscall_error(ret); - if (MC_DRV_OK != mcResult) { - break; - } - - // Fill in return parameters - session->sessionId = sess.sid; - } while (false); - - /* Legacy error matching */ - if (MC_DRV_OK != mcResult) { - if (MC_DRV_ERR_UNKNOWN == mcResult) { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - } - - LOG_E("return 0x%x", mcResult); - } - - return mcResult; -} - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcOpenTrustlet( - mcSessionHandle_t* session, - mcSpid_t spid, - uint8_t* trustlet, - uint32_t tLen, - uint8_t* tci, - uint32_t tciLen -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - struct mc_ioctl_open_trustlet trus; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - - // Call ioctl - trus.sid = 0; - trus.spid = spid; - trus.buffer = (uintptr_t)trustlet; - trus.tlen = tLen; - trus.tci = (uintptr_t)tci; - trus.tcilen = tciLen; - ret = client.openTrustlet(trus); - mcResult = convert_syscall_error(ret); - - // Fill in return parameters - if (MC_DRV_OK == mcResult) { - session->sessionId = trus.sid; - } - - } while (false); - - /* Legacy error matching */ - if (MC_DRV_OK != mcResult) { - if (MC_DRV_ERR_UNKNOWN == mcResult) { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - } - - LOG_E("return 0x%x", mcResult); - } - - return mcResult; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcCloseSession( - mcSessionHandle_t* session -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - - // Call ioctl - ret = client.closeSession(session->sessionId); - mcResult = convert_syscall_error(ret); - - } while (false); - - return mcResult; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcNotify( - mcSessionHandle_t* session -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - - // Call ioctl - ret = client.notify(session->sessionId); - mcResult = convert_syscall_error(ret); - - } while (false); - - return mcResult; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcWaitNotification( - mcSessionHandle_t* session, - int32_t timeout -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - struct mc_ioctl_wait wait; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - - // Call ioctl - wait.sid = session->sessionId; - wait.timeout = timeout; - do { - ret = client.waitNotification(wait); - mcResult = convert_syscall_error(ret); - } while (MC_INFINITE_TIMEOUT == timeout && - MC_DRV_ERR_INTERRUPTED_BY_SIGNAL == mcResult); - - } while (false); - - return mcResult; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcMallocWsm( - uint32_t deviceId, - uint32_t align, - uint32_t len, - uint8_t** wsm, - uint32_t wsmFlags -) { - (void) align; - (void) wsmFlags; - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - LOG_D("===%s(len=%i)===", __FUNCTION__, len); - - do { - // Check parameters - if (!isValidDevice(deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!client.isOpen()) { - LOG_E("Client not open"); - mcResult = MC_DRV_ERR_DAEMON_DEVICE_NOT_OPEN; - break; - } - if (!wsm) { - LOG_E("Wsm pointer is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - // Alloc and map kernel buffer into user space - if (client.malloc(wsm, len)) { - mcResult = convert_syscall_error(-1); - break; - } - wsms_add(*wsm, len); - mcResult = MC_DRV_OK; - - } while (false); - - return mcResult; -} - - -//------------------------------------------------------------------------------ -// Note: mcFreeWsm() only succeeds if wsm is as returned by mcMallocWsm(). -__MC_CLIENT_LIB_API mcResult_t mcFreeWsm( - uint32_t deviceId, - uint8_t* wsm -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - - LOG_D("===%s(%p)===", __FUNCTION__, wsm); - - do { - // Check parameters - if (!isValidDevice(deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!client.isOpen()) { - LOG_E("Client not open"); - mcResult = MC_DRV_ERR_DAEMON_DEVICE_NOT_OPEN; - break; - } - // Get mapping length - int len = wsms_len(wsm); - if (len == -1) { - LOG_E("wsm %p buffer not available", wsm); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - } else { - // Unmap and free kernel buffer - int ret = client.free(wsm, len); - mcResult = convert_syscall_error(ret); - if (ret == 0) { - wsms_remove(wsm); - } - } - } while (false); - - return mcResult; -} - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcMap( - mcSessionHandle_t* session, - void* buf, - uint32_t bufLen, - mcBulkMap_t* mapInfo -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - struct mc_ioctl_map map; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!mapInfo) { - LOG_E("mapInfo pointer is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - - // Call ioctl - map.sid = session->sessionId; - map.bufs[0].va = (uintptr_t)buf; - map.bufs[0].len = bufLen; - map.bufs[0].flags = MC_IO_MAP_INPUT_OUTPUT; - LOG_D("map va=%llx len=%u", map.bufs[0].va, map.bufs[0].len); - for (int i = 1; i < MC_MAP_MAX; i++) { - map.bufs[i].va = 0; - } - ret = client.map(map); - mcResult = convert_syscall_error(ret); - if (MC_DRV_OK != mcResult) { - break; - } - LOG_D("map'd va=%llx len=%u sva=%llx", - map.bufs[0].va, map.bufs[0].len, map.bufs[0].sva); - - // Fill in return parameters -#if ( __WORDSIZE != 64 ) - mapInfo->sVirtualAddr = (void*)(uintptr_t)map.bufs[0].sva; -#else - mapInfo->sVirtualAddr = (uint32_t)map.bufs[0].sva; -#endif - mapInfo->sVirtualLen = map.bufs[0].len; - } while (false); - - /* Legacy error matching */ - if (MC_DRV_OK != mcResult) { - if (MC_DRV_ERR_UNKNOWN == mcResult) { - mcResult = MC_DRV_ERR_BULK_MAPPING; - } - - LOG_E("return 0x%x", mcResult); - } - - return mcResult; -} - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcUnmap( - mcSessionHandle_t* session, - void* buf, - mcBulkMap_t* mapInfo -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - struct mc_ioctl_map map; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!mapInfo) { - LOG_E("mapInfo pointer is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - - // Call ioctl - map.sid = session->sessionId; - map.bufs[0].va = (uintptr_t)buf; - map.bufs[0].sva = (uintptr_t)mapInfo->sVirtualAddr; - map.bufs[0].len = mapInfo->sVirtualLen; - LOG_D("unmap va=%llx len=%u sva=%llx", - map.bufs[0].va, map.bufs[0].len, map.bufs[0].sva); - for (int i = 1; i < MC_MAP_MAX; i++) { - map.bufs[i].va = 0; - } - ret = client.unmap(map); - mcResult = convert_syscall_error(ret); - - } while (false); - - if (MC_DRV_OK != mcResult) { - if (MC_DRV_ERR_UNKNOWN == mcResult) { - mcResult = MC_DRV_ERR_BULK_UNMAPPING; - } - - LOG_E("return 0x%x", mcResult); - } - - return mcResult; -} - - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcGetSessionErrorCode( - mcSessionHandle_t* session, - int32_t* lastErr -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - struct mc_ioctl_geterr err; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!session) { - LOG_E("Session handle is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - if (!isValidDevice(session->deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!lastErr) { - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - - // Call ioctl - err.sid = session->sessionId; - ret = client.getError(err); - mcResult = convert_syscall_error(ret); - if (MC_DRV_OK != mcResult) { - break; - } - - // Fill in return parameters - *lastErr = err.value; - - } while (false); - - return mcResult; -} - -//------------------------------------------------------------------------------ -__MC_CLIENT_LIB_API mcResult_t mcGetMobiCoreVersion( - uint32_t deviceId, - mcVersionInfo_t* versionInfo -) { - mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; - int ret; - - LOG_D("===%s()===", __FUNCTION__); - - do { - // Check parameters - if (!isValidDevice(deviceId)) { - mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; - break; - } - if (!versionInfo) { - LOG_E("versionInfo pointer is null"); - mcResult = MC_DRV_ERR_INVALID_PARAMETER; - break; - } - - struct mc_version_info version_info; - ret = client.getVersion(version_info); - if (!ret) { - memcpy(versionInfo, &version_info, sizeof(*versionInfo)); - } - mcResult = convert_syscall_error(ret); - } while (false); - - return mcResult; -} diff --git a/mobicore/ClientLib/src/mc_user.h b/mobicore/ClientLib/src/mc_user.h deleted file mode 100644 index e8ac3d6..0000000 --- a/mobicore/ClientLib/src/mc_user.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_USER_H_ -#define _MC_USER_H_ - -#define MCDRVMODULEAPI_VERSION_MAJOR 2 -#define MCDRVMODULEAPI_VERSION_MINOR 10 - -#include - -#define MC_USER_DEVNODE "mobicore-user" - -/** Maximum length of MobiCore product ID string. */ -#define MC_PRODUCT_ID_LEN 64 - -/** Number of buffers that can be mapped at once */ -#define MC_MAP_MAX 4 - -/** Max length for buffers */ -#define BUFFER_LENGTH_MAX 0x100000 - -/** Flags for buffers to map (aligned on GP) */ -#define MC_IO_MAP_INPUT 0x1 -#define MC_IO_MAP_OUTPUT 0x2 -#define MC_IO_MAP_INPUT_OUTPUT (MC_IO_MAP_INPUT | MC_IO_MAP_OUTPUT) - -/* - * Universally Unique Identifier (UUID) according to ISO/IEC 11578. - */ -struct mc_uuid_t { - __u8 value[16]; /* Value of the UUID. */ -}; - -/* - * GP TA login types. - */ -enum mc_login_type { - LOGIN_PUBLIC = 0, - LOGIN_USER, - LOGIN_GROUP, - LOGIN_APPLICATION = 4, - LOGIN_USER_APPLICATION, - LOGIN_GROUP_APPLICATION, -}; - -/* - * GP TA identity structure. - */ -struct mc_identity { - enum mc_login_type login_type; - union { - __u8 login_data[16]; - gid_t gid; /* Requested group id */ - struct { - uid_t euid; - uid_t ruid; - } uid; - }; - pid_t pid; /* Client, when using proxy */ -}; - -/* - * Data exchange structure of the MC_IO_OPEN_SESSION ioctl command. - */ -struct mc_ioctl_open_session { - struct mc_uuid_t uuid; /* trustlet uuid */ - __u32 is_gp_uuid; /* uuid is for GP TA */ - __u32 sid; /* session id (out) */ - __u64 tci; /* tci buffer pointer */ - __u32 tcilen; /* tci length */ - struct mc_identity identity; /* GP TA identity */ -}; - -/* - * Data exchange structure of the MC_IO_OPEN_TRUSTLET ioctl command. - */ -struct mc_ioctl_open_trustlet { - __u32 sid; /* session id (out) */ - __u32 spid; /* trustlet spid */ - __u64 buffer; /* trustlet binary pointer */ - __u32 tlen; /* binary length */ - __u64 tci; /* tci buffer pointer */ - __u32 tcilen; /* tci length */ -}; - -/* - * Data exchange structure of the MC_IO_WAIT ioctl command. - */ -struct mc_ioctl_wait { - __u32 sid; /* session id (in) */ - __s32 timeout; /* notification timeout */ - __u32 partial; /* for proxy server to retry silently */ -}; - -/* - * Data exchange structure of the MC_IO_ALLOC ioctl command. - */ -struct mc_ioctl_alloc { - __u32 len; /* buffer length */ - __u32 handle; /* user handle for the buffer (out) */ -}; - -/* - * Buffer mapping incoming and outgoing information. - */ -struct mc_ioctl_buffer { - __u64 va; /* user space address of buffer */ - __u32 len; /* buffer length */ - __u64 sva; /* SWd virt address of buffer (out) */ - __u32 flags; /* buffer flags */ -}; - -/* - * Data exchange structure of the MC_IO_MAP and MC_IO_UNMAP ioctl commands. - */ -struct mc_ioctl_map { - __u32 sid; /* session id */ - struct mc_ioctl_buffer bufs[MC_MAP_MAX]; /* buffers info */ -}; - -/* - * Data exchange structure of the MC_IO_ERR ioctl command. - */ -struct mc_ioctl_geterr { - __u32 sid; /* session id */ - __s32 value; /* error value (out) */ -}; - -/* - * Global MobiCore Version Information. - */ -struct mc_version_info { - char product_id[MC_PRODUCT_ID_LEN]; /** Product ID string */ - __u32 version_mci; /** Mobicore Control Interface */ - __u32 version_so; /** Secure Objects */ - __u32 version_mclf; /** MobiCore Load Format */ - __u32 version_container; /** MobiCore Container Format */ - __u32 version_mc_config; /** MobiCore Config. Block Format */ - __u32 version_tl_api; /** MobiCore Trustlet API */ - __u32 version_dr_api; /** MobiCore Driver API */ - __u32 version_nwd; /** This Driver */ -}; - -/* - * defines for the ioctl mobicore driver module function call from user space. - */ -/* MobiCore IOCTL magic number */ -#define MC_IOC_MAGIC 'M' - -/* - * Implement corresponding functions from user api - */ -#define MC_IO_OPEN_SESSION \ - _IOWR(MC_IOC_MAGIC, 0, struct mc_ioctl_open_session) -#define MC_IO_OPEN_TRUSTLET \ - _IOWR(MC_IOC_MAGIC, 1, struct mc_ioctl_open_trustlet) -#define MC_IO_CLOSE_SESSION _IO(MC_IOC_MAGIC, 2) -#define MC_IO_NOTIFY _IO(MC_IOC_MAGIC, 3) -#define MC_IO_WAIT _IOW(MC_IOC_MAGIC, 4, struct mc_ioctl_wait) -#define MC_IO_MAP _IOWR(MC_IOC_MAGIC, 5, struct mc_ioctl_map) -#define MC_IO_UNMAP _IOW(MC_IOC_MAGIC, 6, struct mc_ioctl_map) -#define MC_IO_ERR _IOWR(MC_IOC_MAGIC, 7, struct mc_ioctl_geterr) -#define MC_IO_HAS_SESSIONS _IO(MC_IOC_MAGIC, 8) -#define MC_IO_VERSION _IOR(MC_IOC_MAGIC, 9, struct mc_version_info) - -#endif /* _MC_USER_H_ */ diff --git a/mobicore/ClientLib/src/proxy_client.cpp b/mobicore/ClientLib/src/proxy_client.cpp deleted file mode 100644 index 356f492..0000000 --- a/mobicore/ClientLib/src/proxy_client.cpp +++ /dev/null @@ -1,812 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include - -#include // strncpy -#include // mmap, munmap -#include -#include - -#undef LOG_TAG -#define LOG_TAG "TeeProxyClient" -#include "log.h" -#include "mcVersionHelper.h" -#include "proxy_common.h" -#include "proxy_client.h" - -using namespace com::trustonic::tee_proxy; - -class ClientConnection { - std::string buffer_; - std::mutex comm_mutex_; - std::mutex comm_queue_mutex_; - int socket_ = -1; - bool is_open_ = false; - bool is_broken_ = false; - Session* session_ = nullptr; -public: - ~ClientConnection() { - if (is_open_) { - close(); - } - delete session_; - } - int open() { - socket_ = ::socket(AF_UNIX, SOCK_STREAM, 0); - if (socket_ < 0) { - LOG_ERRNO("socket"); - return -1; - } - struct sockaddr_un sock_un; - sock_un.sun_family = AF_UNIX; - ::strncpy(sock_un.sun_path, SOCKET_PATH, sizeof(sock_un.sun_path) - 1); - socklen_t len = static_cast(strlen(sock_un.sun_path) + - sizeof(sock_un.sun_family)); - sock_un.sun_path[0] = '\0'; // Abstract - if (::connect(socket_, reinterpret_cast(&sock_un), - len) < 0) { - LOG_ERRNO("connect"); - return -1; - } - is_open_ = true; - LOG_D("socket %d connected", socket_); - return 0; - } - int close() { - ::close(socket_); - is_open_ = false; - LOG_D("socket %d session %x closed", socket_, session_ ? session_->id() : 0); - return 0; - } - bool isBroken() const { - return is_broken_; - } - void setSession(Session* session) { - session_ = session; - } - Session* session() const { - return session_; - } - int call(RpcMethod method, const ::google::protobuf::MessageLite& request, - ::google::protobuf::MessageLite& response) { - // Trick to ensure round-robin access to two callers - comm_queue_mutex_.lock(); - std::lock_guard comm_lock(comm_mutex_); - comm_queue_mutex_.unlock(); - LOG_D("socket %d session %x call %s", socket_, - session_ ? session_->id() : 0, methodToString(method)); - - // Request - { - // Serialize request - if (!request.SerializeToString(&buffer_)) { - LOG_E("Failed to serialize"); - is_broken_ = true; - return -1; - } - - // Send request header - RequestHeader header; - ::memcpy(header.magic, PROTOCOL_MAGIC, sizeof(header.magic)); - header.version = PROTOCOL_VERSION; - header.method = static_cast(method); - header.length = static_cast(buffer_.length()); - if (send_all(socket_, "header", &header, sizeof(header))) { - is_broken_ = true; - return -1; - } - - // Send request data - LOG_D("send %u bytes of data", header.length); - if (send_all(socket_, "data", &buffer_[0], header.length)) { - is_broken_ = true; - return -1; - } - } - - // Response - { - // Receive response header - ResponseHeader header; - if (recv_all(socket_, "header", &header, sizeof(header))) { - is_broken_ = true; - return -1; - } - - // Check header - if (::memcmp(header.magic, PROTOCOL_MAGIC, sizeof(header.magic))) { - LOG_E("Wrong magic"); - is_broken_ = true; - return -1; - } - if (header.version != PROTOCOL_VERSION) { - LOG_E("Wrong version"); - is_broken_ = true; - return -1; - } - if (header.proto_rc < 0) { - errno = -header.proto_rc; - LOG_E("Protocol error reported: %s", - strerror(-header.proto_rc)); - is_broken_ = true; - return -1; - } - - // Receive response data - LOG_D("receive %d bytes of data", header.proto_rc); - if (header.proto_rc != 0) { - // Receive response data - int length = header.proto_rc; - buffer_.resize(length); - if (recv_all(socket_, "data", &buffer_[0], length)) { - is_broken_ = true; - return -1; - } - - // Parse response - if (!response.ParseFromString(buffer_)) { - LOG_E("Failed to parse"); - is_broken_ = true; - return -1; - } - } - - // Method errors do not require specific method action - if (header.method_rc) { - errno = header.method_rc; - LOG_D("Error reported: %s", strerror(errno)); - return -1; - } - } - LOG_D("socket %d session %x call done", socket_, - session_ ? session_->id() : 0); - return 0; - } -}; - -class SessionConnectionsList { - std::mutex mutex_; - std::vector connections_; -public: - ClientConnection* find(uint32_t id) { - std::lock_guard lock(mutex_); - for (auto& connection: connections_) { - if (connection->session()->id() == id) { - return connection; - } - } - return nullptr; - } - int deleteConnection(uint32_t id) { - LOG_D("%s %p: %x", __FUNCTION__, this, id); - std::lock_guard lock(mutex_); - auto it = std::find_if(connections_.begin(), connections_.end(), - [this, id](ClientConnection* connection) { - return connection->session()->id() == id; - }); - if (it == connections_.end()) { - // Not found - return -1; - } - delete *it; - connections_.erase(it); - return 0; - } - void push_back(ClientConnection* connection) { - LOG_D("%s %p: %x", __FUNCTION__, this, connection->session()->id()); - std::lock_guard lock(mutex_); - connections_.push_back(connection); - } - bool empty() const { - return connections_.empty(); - } -}; - -struct ProxyClient::Impl { - bool is_open_; - // Versions - mc_version_info version_info; - // Sessions - SessionConnectionsList connections; - Impl(): is_open_(false) { - ::memset(&version_info, 0, sizeof(version_info)); - } - int getVersion(ClientConnection& conn, struct mc_version_info& version_info); -}; - -ProxyClient::ProxyClient(): pimpl_(new Impl) { -} - -ProxyClient::~ProxyClient() { - delete pimpl_; -} - -int ProxyClient::open() { - ClientConnection conn; - if (conn.open()) { - return -1; - } - // Cache versions - if (pimpl_->getVersion(conn, pimpl_->version_info)) { - return -1; - } - conn.close(); - pimpl_->is_open_ = true; - LOG_I("proxy client open"); - return 0; -} - -int ProxyClient::close() { - pimpl_->is_open_ = false; - LOG_I("proxy client closed"); - return 0; -} - -bool ProxyClient::isOpen() const { - return pimpl_->is_open_; -} - -int ProxyClient::hasOpenSessions() const { - int ret = 0; - if (!pimpl_->connections.empty()) { - ret = -1; - errno = ENOTEMPTY; - } - LOG_D("%s rc=%d", __FUNCTION__, ret); - return ret; -} - -int ProxyClient::openSession(struct mc_ioctl_open_session& session) { - LOG_D("tci 0x%llx len %u", session.tci, session.tcilen); - if ((session.tci && !session.tcilen) || - (!session.tci && session.tcilen)) { - LOG_E("TCI and its length are inconsistent"); - errno = EINVAL; - return -1; - } - // So we return the correct error code - if (session.tcilen > BUFFER_LENGTH_MAX) { - errno = EINVAL; - return -1; - } - // Open the session - void* tci = reinterpret_cast(static_cast(session.tci)); - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - OpenSessionRequest request; - request.set_uuid(static_cast(&session.uuid), sizeof(session.uuid)); - request.set_is_gp_uuid(session.is_gp_uuid); - if (tci) { - request.set_tci(tci, session.tcilen); - } - request.set_login_type(static_cast(session.identity.login_type)); - request.set_login_data(static_cast(session.identity.login_data), - sizeof(session.identity.login_data)); - // Create connection - std::unique_ptr conn(new ClientConnection); - if (conn->open()) { - LOG_E("Failed to open connection"); - return -1; - } - // Exchange - OpenSessionResponse response; - if (conn->call(OPEN_SESSION, request, response)) { - // Error logged in call() - return -1; - } - // Response - if (!response.has_id()) { - LOG_E("Required parameter missing"); - return -1; - } - // Success - errno = saved_errno; - session.sid = response.id(); - LOG_D("session %x open", session.sid); - Session::Buffer* buffer; - if (tci) { - buffer = new Session::Buffer(tci, session.tcilen); - } else { - buffer = nullptr; - } - conn->setSession(new Session(session.sid, buffer)); - pimpl_->connections.push_back(conn.release()); - return 0; -} - -int ProxyClient::openTrustlet(struct mc_ioctl_open_trustlet& trustlet) { - LOG_D("tci 0x%llx len %u", trustlet.tci, trustlet.tcilen); - if ((trustlet.tci && !trustlet.tcilen) || - (!trustlet.tci && trustlet.tcilen)) { - LOG_E("TCI and its length are inconsistent"); - return -1; - } - // So we return the correct error code - if (trustlet.tcilen > BUFFER_LENGTH_MAX) { - errno = EINVAL; - return -1; - } - // Open the trustlet - void* app = reinterpret_cast(static_cast(trustlet.buffer)); - void* tci = reinterpret_cast(static_cast(trustlet.tci)); - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - OpenTrustletRequest request; - request.set_spid(trustlet.spid); - request.set_trustapp(app, trustlet.tlen); - if (tci) { - request.set_tci(tci, trustlet.tcilen); - } - // Create connection - std::unique_ptr conn(new ClientConnection); - if (conn->open()) { - LOG_E("Failed to open connection"); - return -1; - } - // Exchange - OpenTrustletResponse response; - if (conn->call(OPEN_TRUSTLET, request, response)) { - // Error logged in call() - return -1; - } - // Response - if (!response.has_id()) { - LOG_E("Required parameter missing"); - return -1; - } - // Success - errno = saved_errno; - trustlet.sid = response.id(); - LOG_D("session %x open", trustlet.sid); - // Create session management object - Session::Buffer* buffer; - if (tci) { - buffer = new Session::Buffer(tci, trustlet.tcilen); - } else { - buffer = nullptr; - } - conn->setSession(new Session(trustlet.sid, buffer)); - pimpl_->connections.push_back(conn.release()); - return 0; -} - -int ProxyClient::closeSession(uint32_t session_id) { - LOG_D("session %x close", session_id); - // Find session connection - auto connection = pimpl_->connections.find(session_id); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - CloseSessionRequest request; - request.set_id(session_id); - // Exchange - CloseSessionResponse response; - if (connection->call(CLOSE_SESSION, request, response)) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(session_id); - } - return -1; - } - // No response - // Success - errno = saved_errno; - if (pimpl_->connections.deleteConnection(session_id)) { - errno = ENXIO; - return -1; - } - LOG_D("session %x closed", session_id); - return 0; -} - -int ProxyClient::notify(uint32_t session_id) { - LOG_D("session %x notify", session_id); - // Find session connection - auto connection = pimpl_->connections.find(session_id); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - NotifyRequest request; - request.set_sid(session_id); - auto session = connection->session(); - if (session->hasTci()) { - request.set_tci(session->tci(), session->tciLen()); - } - std::lock_guard buffers_lock(session->buffersMutex()); - auto& buffers = session->buffers(); - for (auto& buf: buffers) { - if (buf->info().flags & MC_IO_MAP_INPUT) { - NotifyRequest_Buffers* buffer = request.add_buffers(); - buffer->set_sva(buf->info().sva); - buffer->set_data(buf->address(), buf->info().len); - } - } - // Exchange - NotifyResponse response; - if (connection->call(NOTIFY, request, response)) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(session_id); - } - return -1; - } - // No response - // Success - errno = saved_errno; - LOG_D("session %x notification sent", session_id); - return 0; -} - -int ProxyClient::waitNotification(const struct mc_ioctl_wait& wait) { - LOG_D("session %x wait for notification", wait.sid); - // Find session connection - auto connection = pimpl_->connections.find(wait.sid); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - WaitNotificationRequest request; - request.set_sid(wait.sid); - // Timeout to server cannot exceed a few seconds, retry every 5s - int32_t timeout_left = wait.timeout; - WaitNotificationResponse response; - bool failed = false; - while (true) { - if (wait.timeout < 0) { - // Infinite - request.set_timeout(timeout_max); - request.set_partial(true); - } else if (timeout_left > timeout_max) { - // Big - request.set_timeout(timeout_max); - request.set_partial(true); - timeout_left -= timeout_max; - } else { - // Small enough - request.set_timeout(timeout_left); - request.set_partial(false); - timeout_left = 0; - } - LOG_D("timeout: asked=%d left=%d set=%d", - wait.timeout, timeout_left, request.timeout()); - // Exchange - if (!connection->call(WAIT, request, response)) { - LOG_D("done"); - break; - } - // Real timeout or other error - if ((errno != ETIME) || !request.partial()) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(wait.sid); - LOG_D("abort"); - return -1; - } - LOG_D("give up, but update buffers"); - failed = true; - break; - } - LOG_D("retry"); - } - // Response - auto session = connection->session(); - if (response.has_tci() && session->updateTci(response.tci())) { - LOG_E("Could not update TCI"); - return -1; - } - for (int i = 0; i < response.buffers_size(); i++) { - const WaitNotificationResponse_Buffers& buffer = response.buffers(i); - if (!buffer.has_sva() || !buffer.has_data()) { - LOG_E("Required parameter missing"); - return -1; - } - std::lock_guard buffers_lock(session->buffersMutex()); - auto buf = session->findBuffer(buffer.sva()); - if (!buf) { - LOG_E("Buffer not found for SVA %jx", buffer.sva()); - return -1; - } - if (buffer.data().length() != buf->info().len) { - LOG_E("Buffer sizes differ for SVA %jx: %zu != %u", - buffer.sva(), buffer.data().length(), buf->info().len); - return -1; - } - ::memcpy(buf->address(), buffer.data().c_str(), buf->info().len); - } - if (failed) { - return -1; - } - // Success - errno = saved_errno; - LOG_D("session %x notification received", wait.sid); - return 0; -} - -int ProxyClient::malloc(uint8_t** buffer, uint32_t length) { - // Cannot share kernel buffers through the proxy - *buffer = (uint8_t*)::mmap(0, length, PROT_READ | PROT_WRITE, - MAP_SHARED | MAP_ANONYMOUS, -1, 0); - if (*buffer == MAP_FAILED) { - errno = ENOMEM; - return -1; - } - LOG_D("mmap'd buffer %p len %u", *buffer, length); - return 0; -} - -int ProxyClient::free(uint8_t* buffer, uint32_t length) { - LOG_D("munmap'd buffer %p len %u", buffer, length); - ::munmap(buffer, length); - return 0; -} - -int ProxyClient::map(struct mc_ioctl_map& map) { - LOG_D("map buffer(s) to session %x", map.sid); - // Find session connection - auto connection = pimpl_->connections.find(map.sid); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - MapRequest request; - request.set_sid(map.sid); - for (int i = 0; i < MC_MAP_MAX; i++) { - if (map.bufs[i].va) { - if (map.bufs[i].len > BUFFER_LENGTH_MAX) { - LOG_E("Incorrect length for buffer: %u", map.bufs[i].len); - errno = -EINVAL; - return -1; - } - auto buffer = request.add_buffers(); - buffer->set_len(map.bufs[i].len); - buffer->set_flags(map.bufs[i].flags); - } - } - // Exchange - MapResponse response; - if (connection->call(MAP, request, response)) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(map.sid); - } - return -1; - } - // Response - if (response.buffers_size() != request.buffers_size()) { - LOG_E("Response buffers size (%d) does not match request's (%d)", - response.buffers_size(), request.buffers_size()); - return -1; - } - int buffer_index = 0; - for (int i = 0; i < MC_MAP_MAX; i++) { - if (map.bufs[i].va) { - const MapResponse_Buffers& buf = response.buffers(buffer_index++); - if (!buf.has_sva()) { - LOG_E("Required parameter missing"); - return -1; - } - map.bufs[i].sva = buf.sva(); - } - } - // Success - errno = saved_errno; - auto session = connection->session(); - for (int i = 0; i < MC_MAP_MAX; i++) { - if (map.bufs[i].va) { - session->addBuffer(map.bufs[i]); - } - } - LOG_D("session %x buffer(s) mapped", map.sid); - return 0; -} - -int ProxyClient::unmap(const struct mc_ioctl_map& map) { - LOG_D("unmap buffer(s) to session %x", map.sid); - // Find session connection - auto connection = pimpl_->connections.find(map.sid); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - UnmapRequest request; - request.set_sid(map.sid); - for (int i = 0; i < MC_MAP_MAX; i++) { - if (map.bufs[i].va) { - if (!map.bufs[i].sva) { - errno = EINVAL; - return -1; - } - UnmapRequest_Buffers* buffer = request.add_buffers(); - buffer->set_sva(map.bufs[i].sva); - } - } - // Exchange - UnmapResponse response; - if (connection->call(UNMAP, request, response)) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(map.sid); - } - return -1; - } - // No response - // Success - errno = saved_errno; - auto session = connection->session(); - for (int i = 0; i < MC_MAP_MAX; i++) { - if (map.bufs[i].va) { - if (session->removeBuffer(map.bufs[i].sva)) { - LOG_E("Unmapped buffer not found in session: %llu", - map.bufs[i].sva); - return -1; - } - } - } - LOG_D("session %x buffer(s) unmapped", map.sid); - return 0; -} - -int ProxyClient::getError(struct mc_ioctl_geterr& err) { - LOG_D("get session %x exit code", err.sid); - // Find session connection - auto connection = pimpl_->connections.find(err.sid); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - GetErrorRequest request; - request.set_sid(err.sid); - // Exchange - GetErrorResponse response; - if (connection->call(GET_ERROR, request, response)) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(err.sid); - } - return -1; - } - // Response - if (!response.has_exit_code()) { - LOG_E("Required parameter missing"); - return -1; - } - // Success - errno = saved_errno; - err.value = response.exit_code(); - LOG_D("session %x exit code %d", err.sid, err.value); - return 0; -} - -int ProxyClient::Impl::getVersion(ClientConnection& conn, - struct mc_version_info& version_info) { - LOG_D("get version"); - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - GetVersionRequest request; - // No inputs to set - // Exchange - GetVersionResponse response; - if (conn.call(GET_VERSION, request, response)) { - // Error logged in call() - return -1; - } - // Response - if (!response.has_product_id() || - !response.has_mci() || - !response.has_so() || - !response.has_mclf() || - !response.has_container() || - !response.has_mc_config() || - !response.has_tl_api() || - !response.has_dr_api() || - !response.has_nwd()) { - LOG_E("Required parameter missing"); - return -1; - } - // Success - errno = saved_errno; - ::strncpy(version_info.product_id, response.product_id().c_str(), - MC_PRODUCT_ID_LEN); - version_info.product_id[MC_PRODUCT_ID_LEN - 1] = '\0'; - version_info.version_mci = response.mci(); - version_info.version_so = response.so(); - version_info.version_mclf = response.mclf(); - version_info.version_container = response.container(); - version_info.version_mc_config = response.mc_config(); - version_info.version_tl_api = response.tl_api(); - version_info.version_dr_api = response.dr_api(); - version_info.version_nwd = response.nwd(); - return 0; -} - -int ProxyClient::getVersion(struct mc_version_info& version_info) { - if (!pimpl_->is_open_) { - errno = EBADF; - return -1; - } - version_info = pimpl_->version_info; - return 0; -} - -int ProxyClient::gpRequestCancellation(uint32_t session_id) { - LOG_D("cancel GP operation on session %x", session_id); - // Find session connection - auto connection = pimpl_->connections.find(session_id); - if (!connection) { - errno = ENXIO; - return -1; - } - int saved_errno = errno; - errno = EHOSTUNREACH; - // Request - GpRequestCancellationRequest request; - request.set_sid(session_id); - // Exchange - GpRequestCancellationResponse response; - if (connection->call(GP_REQUESTCANCELLATION, request, response)) { - // Error logged in call() - if (connection->isBroken()) { - pimpl_->connections.deleteConnection(session_id); - } - return -1; - } - // No response - // Success - errno = saved_errno; - return 0; -} diff --git a/mobicore/ClientLib/src/proxy_client.h b/mobicore/ClientLib/src/proxy_client.h deleted file mode 100644 index 7fee59f..0000000 --- a/mobicore/ClientLib/src/proxy_client.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __PROXY_CLIENT_H__ -#define __PROXY_CLIENT_H__ - -#include "iclient.h" - -class ProxyClient: public IClient { - struct Impl; - Impl* const pimpl_; -public: - ProxyClient(); - ~ProxyClient(); - virtual int open() override; - virtual int close() override; - virtual bool isOpen() const override; - virtual int hasOpenSessions() const override; - virtual int openSession(struct mc_ioctl_open_session& session) override; - virtual int openTrustlet(struct mc_ioctl_open_trustlet& trustlet) override; - virtual int closeSession(uint32_t session_id) override; - virtual int notify(uint32_t session_id) override; - virtual int waitNotification(const struct mc_ioctl_wait& wait) override; - virtual int malloc(uint8_t** buffer, uint32_t length) override; - virtual int free(uint8_t* buffer, uint32_t length) override; - virtual int map(struct mc_ioctl_map& map) override; - virtual int unmap(const struct mc_ioctl_map& map) override; - virtual int getError(struct mc_ioctl_geterr& err) override; - virtual int getVersion(struct mc_version_info& version_info) override; - virtual int gpRequestCancellation(uint32_t session_id) override; -}; - -#endif // __PROXY_CLIENT_H__ diff --git a/mobicore/ClientLib/src/proxy_common.h b/mobicore/ClientLib/src/proxy_common.h deleted file mode 100644 index b2c7ca8..0000000 --- a/mobicore/ClientLib/src/proxy_common.h +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include - -#include // malloc, free -#include // mmap, munmap - -#include "mc_user.h" // mc_ioctl_buffer - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#include "mc.pb.h" -#pragma GCC diagnostic pop - -#define SOCKET_PATH "@/com/trustonic/tee_proxy" -#define PROTOCOL_MAGIC "T7e3" -#define PROTOCOL_VERSION 1 - -/* - * ProtoBuf gives us the serialisation mechanism, but that's not enough to send - * our RPC messages: we also need to pass the method we want to call, the total - * length of the data, and a magic number is usually welcome too. While at it, - * we'll throw a version number just in case. - * - * Hence: - * ---------------------- - * | Magic number | 4 bytes (text) - * ---------------------- - * | Method | Version | 2 + 2 bytes (LE) - * ---------------------- - * | Message length | 4 bytes (LE) - * ---------------------- - * | | - * | Message data | N bytes (text) - * ~ ~ - * | | - * ---------------------- - */ - -namespace com { -namespace trustonic { -namespace tee_proxy { - -struct RequestHeader { - char magic[4]; - uint16_t version; - uint16_t method; - uint32_t length; -}; - -struct ResponseHeader { - char magic[4]; - uint16_t version; - uint16_t method; - int32_t proto_rc; // -errno if negative, length of data otherwise - uint32_t method_rc; // errno from called method on server side -}; - -enum RpcMethod { - OPEN_SESSION = 0, - OPEN_TRUSTLET = 1, - CLOSE_SESSION = 2, - NOTIFY = 3, - WAIT = 4, - MAP = 5, - UNMAP = 6, - GET_ERROR = 7, - GET_VERSION = 9, - GP_REQUESTCANCELLATION = 27, -}; - -class Session { -public: - class Buffer { - enum Type { - NONE, // No buffer - CLIENT, // Buffer managed by caller (client side) - SERVER, // Buffer mmap'd (server side) - }; - mc_ioctl_buffer info_; - void* address_; - Type type_; - int alloc(size_t length, uint32_t flags = MC_IO_MAP_INPUT_OUTPUT) { - // No posix_memalign, aligned_alloc, valloc, memalign, pvalloc in - // Android so we rely on mmap to give us page-aligned memory - size_t page_mask = sysconf(_SC_PAGESIZE) - 1; - size_t aligned_length = (length + page_mask) & ~page_mask; - void* buf = ::mmap(0, aligned_length, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if (buf == MAP_FAILED) { - LOG_E("Failed to allocate"); - return -1; - } - type_ = SERVER; - address_ = buf; - info_.va = reinterpret_cast(address_); - info_.len = static_cast(length); - info_.flags = flags; - LOG_D("alloc'd buffer %p:%u:%x", address_, info_.len, info_.flags); - return 0; - } - public: - Buffer(const Buffer&) = delete; - Buffer& operator=(const Buffer&) = delete; - // Constructor from buffer: allocate and fill in - Buffer(std::string buffer): address_(nullptr) { - if (!alloc(buffer.length())) { - update(buffer); - } - } - // Constructor for client TCI: pointer and length (can be null) given - Buffer(void* address, size_t length): address_(address) { - if (address_) { - info_.va = reinterpret_cast(address_); - info_.len = static_cast(length); - info_.flags = MC_IO_MAP_INPUT_OUTPUT; - type_ = CLIENT; - LOG_D("use buffer %p:%u:%x", address_, info_.len, info_.flags); - } else { - info_.va = 0; - info_.len = 0; - info_.flags = 0; - type_ = NONE; - } - info_.sva = 0; - } - // Constructor for server buffer: allocate - Buffer(uint32_t length, uint32_t flags): address_(nullptr) { - alloc(length, flags); - } - // Constructor for client buffer: info given - Buffer(mc_ioctl_buffer info): info_(info) { - address_ = reinterpret_cast( - static_cast(info_.va)); - type_ = CLIENT; - LOG_D("use buffer %p:%u:%x", address_, info_.len, info_.flags); - } - ~Buffer() { - if (type_ == Buffer::SERVER) { - LOG_D("unmap buffer %p:%u:%x", address_, info_.len, - info_.flags); - ::munmap(address_, info_.len); - } - } - // Accessors - const mc_ioctl_buffer& info() const { - return info_; - } - void* address() const { - return address_; - } - void setSva(uint64_t sva) { - info_.sva = sva; - } - int update(const std::string& buf) { - if (buf.length() != info_.len) { - LOG_E("Failed to update TCI"); - return -1; - } - if (type_ != NONE) { - ::memcpy(address_, buf.c_str(), info_.len); - } - return 0; - } - }; -private: - uint32_t id_; - Buffer* tci_; - std::mutex buffers_mutex_; - std::vector buffers_; -public: - Session(uint32_t id, Buffer* tci): id_(id), tci_(tci) {} - ~Session() { - delete tci_; - for (auto& buf: buffers_) { - delete buf; - } - } - uint32_t id() const { - return id_; - } - bool hasTci() const { - return tci_; - } - const void* tci() const { - return tci_->address(); - } - size_t tciLen() const { - return tci_->info().len; - } - int updateTci(const std::string& buf) { - return tci_->update(buf); - } - void addBuffer(Buffer* buffer) { - LOG_D("%p %s: 0x%llx", this, __FUNCTION__, buffer->info().sva); - std::lock_guard buffers_lock(buffers_mutex_); - buffers_.push_back(buffer); - } - void addBuffer(mc_ioctl_buffer& info) { - LOG_D("%p %s: 0x%llx", this, __FUNCTION__, info.sva); - std::lock_guard buffers_lock(buffers_mutex_); - auto buffer = new Buffer(info); - buffers_.push_back(buffer); - } - int removeBuffer(uint64_t sva) { - LOG_D("%p %s: %jx", this, __FUNCTION__, sva); - std::lock_guard buffers_lock(buffers_mutex_); - auto it = std::find_if(buffers_.begin(), buffers_.end(), - [this, sva](Buffer* buffer) { - return buffer->info().sva == sva; - }); - if (it == buffers_.end()) { - // Not found - return -1; - } - delete *it; - buffers_.erase(it); - return 0; - } - // Must be called under buffers_mutex_ - Buffer* findBuffer(uint64_t sva) { - for (auto& buf: buffers_) { - if (buf->info().sva == sva) { - return buf; - } - } - return nullptr; - } - std::mutex& buffersMutex() { - return buffers_mutex_; - } - const std::vector& buffers() { - return buffers_; - } -}; - -static int recv_all(int sock, const char* what, void* buffer, size_t length, - bool may_close = false) { - auto cbuffer = static_cast(buffer); - size_t count = 0; - while (count < length) { - ssize_t rc = ::recv(sock, &cbuffer[count], length - count, 0); - if (rc <= 0) { - if (rc == 0) { - if (may_close) { - LOG_D("socket closed"); - } else { - LOG_E("socket closed while receiving %s", what); - } - return -1; - } - if (errno != EINTR) { - LOG_ERRNO(what); - return -1; - } - LOG_D("signal ignored while sending %s", what); - continue; - } else { - count += rc; - } - } - return 0; -} - -static const int32_t timeout_max = 1000; // 1s - -static int send_all(int sock, const char* what, const void* buffer, - size_t length) { - auto cbuffer = static_cast(buffer); - size_t count = 0; - while (count < length) { - ssize_t rc = ::send(sock, &cbuffer[count], length - count, - MSG_NOSIGNAL); - if (rc <= 0) { - if (rc == 0) { - LOG_E("socket closed while sending %s", what); - return -1; - } - if (errno != EINTR) { - LOG_ERRNO(what); - return -1; - } - LOG_D("signal ignored while sending %s", what); - continue; - } else { - count += rc; - } - } - return 0; -} - -#ifndef NDEBUG -static const char* methodToString(enum RpcMethod method) { - switch (method) { - case OPEN_SESSION: - return "openSession"; - case OPEN_TRUSTLET: - return "openTruslet"; - case CLOSE_SESSION: - return "closeSession"; - case NOTIFY: - return "notify"; - case WAIT: - return "waitNotification"; - case MAP: - return "map"; - case UNMAP: - return "unmap"; - case GET_ERROR: - return "getError"; - case GET_VERSION: - return "getVersion"; - case GP_REQUESTCANCELLATION: - return "gpRequestCancellation"; - } - return "unknown"; -} -#endif - -} // namespace tee_proxy -} // namespace trustonic -} // namespace com diff --git a/mobicore/ClientLib/src/proxy_server.cpp b/mobicore/ClientLib/src/proxy_server.cpp deleted file mode 100644 index f307484..0000000 --- a/mobicore/ClientLib/src/proxy_server.cpp +++ /dev/null @@ -1,905 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include - -#include -#include -#include - -#include "driver_client.h" -#undef LOG_TAG -#define LOG_TAG "TeeProxyServer" -#include "log.h" -#include "proxy_common.h" -#include "proxy_server.h" - -using namespace com::trustonic::tee_proxy; - -template -class FreeMe { - T* t_; -public: - FreeMe(T* t): t_(t) {} - ~FreeMe() { - ::free(t_); - } - operator T* () { - return t_; - } - operator uintptr_t () { - return reinterpret_cast(t_); - } -}; - -class ServerConnection { - int listen_socket_; - int socket_ = -1; - pid_t pid_ = 0; - DriverClient driver; - std::mutex connection_mutex; // Protects is_running_ and session_ - bool is_running_ = false; - Session* session_ = nullptr; - std::thread thread_; - int receiveCredentials() { - // Make sure we can receive credentials - int enable = 1; - if (::setsockopt(socket_, SOL_SOCKET, SO_PASSCRED, &enable, - sizeof(enable))) { - LOG_ERRNO("setsockopt"); - return -1; - } - - struct ucred credentials; - char ctrl[CMSG_SPACE(sizeof(credentials))]; - struct iovec iov[1] = { { 0, 0 } }; - struct msghdr msg = { 0, 0, iov, 1, ctrl, sizeof(ctrl), 0 }; - - msg.msg_iov->iov_base = nullptr; - msg.msg_iov->iov_len = 0; - do { - if (::recvmsg(socket_, &msg, 0) == 0) { - break; - } - if ((errno != EINTR) && (errno != EAGAIN)) { - LOG_ERRNO("recvmsg"); - return -1; - } - } while (true); - - if (msg.msg_controllen < sizeof(struct cmsghdr)) { - errno = EINVAL; - LOG_ERRNO("check"); - return -1; - } - struct cmsghdr* cmptr = CMSG_FIRSTHDR(&msg); - size_t size = sizeof(credentials); - if ((cmptr->cmsg_len != CMSG_LEN(size)) || - (cmptr->cmsg_level != SOL_SOCKET) || - (cmptr->cmsg_type != SCM_CREDENTIALS)) { - errno = EINVAL; - LOG_ERRNO("check"); - return -1; - } - - credentials = *(struct ucred*)CMSG_DATA(cmptr); - pid_ = credentials.pid; - return 0; - } - void connectionThread() { - LOG_D("thread entered %p", this); - std::string buffer; - do { - // Request - RpcMethod method; - { - // Receive request header - RequestHeader header; - if (recv_all(socket_, "header", &header, sizeof(header), - true)) { - break; - } - if (::memcmp(header.magic, PROTOCOL_MAGIC, - sizeof(header.magic))) { - LOG_E("Wrong magic"); - break; - } - if (header.version != PROTOCOL_VERSION) { - LOG_E("Wrong version"); - break; - } - method = static_cast(header.method); - buffer.resize(header.length); - LOG_D("receive %u bytes of data for method %s", - header.length, methodToString(method)); - - // Receive request data - if (recv_all(socket_, "data", &buffer[0], header.length)) { - break; - } - } - - // Dispatch: - // * method_rc is return code from lower layer - // * call returns -errno in case of error, length of data otherwise - int method_rc = 0; - int proto_rc = call(method, buffer, method_rc); - - // Response - { - // Send response header - ResponseHeader header; - ::memcpy(header.magic, PROTOCOL_MAGIC, sizeof(header.magic)); - header.version = PROTOCOL_VERSION; - header.method = static_cast(method); - header.proto_rc = proto_rc; - header.method_rc = method_rc; - if (send_all(socket_, "header", &header, sizeof(header))) { - break; - } - - // Send response data - if (header.proto_rc > 0) { - LOG_D("send %d bytes of data", header.proto_rc); - if (send_all(socket_, "data", &buffer[0], - header.proto_rc)) { - break; - } - } - } - } while (driver.isOpen()); - LOG_D("thread exiting %p", this); - - // Close associated client - driver.close(); - ::close(socket_); - is_running_ = false; - LOG_D("thread exited %p", this); - } -public: - ServerConnection(int listen_socket): listen_socket_(listen_socket) {} - ~ServerConnection() { - delete session_; - } - int open() { - socket_ = ::accept(listen_socket_, nullptr, nullptr); - if (socket_ < 0) { - return -1; - } - if (receiveCredentials() < 0) { - ::close(socket_); - return -1; - } - // Create specific client for this connection - if (driver.open()) { - LOG_ERRNO("open driver"); - ::close(socket_); - return -1; - } - // Start thread - is_running_ = true; - thread_ = std::thread(&ServerConnection::connectionThread, this); - LOG_I("proxy server open, client PID: %d", pid_); - return 0; - } - int close() { - thread_.join(); - // driver and socket are closed at end of thread - LOG_I("proxy server closed, client PID: %d", pid_); - return 0; - } - bool isRunning() const { - return is_running_; - } - int call(RpcMethod method, std::string& buffer, int& method_rc) { - switch (method) { - case OPEN_SESSION: - return openSession(buffer, method_rc); - case OPEN_TRUSTLET: - return openTrustlet(buffer, method_rc); - case CLOSE_SESSION: - return closeSession(buffer, method_rc); - case NOTIFY: - return notify(buffer, method_rc); - case WAIT: - return waitNotification(buffer, method_rc); - case MAP: - return map(buffer, method_rc); - case UNMAP: - return unmap(buffer, method_rc); - case GET_ERROR: - return getError(buffer, method_rc); - case GET_VERSION: - return getVersion(buffer, method_rc); - case GP_REQUESTCANCELLATION: - return gpRequestCancellation(buffer, method_rc); - } - LOG_E("unkown method %d", method); - return -1; - } - // Actions - int openSession(std::string& buffer, int& method_rc); - int openTrustlet(std::string& buffer, int& method_rc); - int closeSession(std::string& buffer, int& method_rc); - int notify(std::string& buffer, int& method_rc); - int waitNotification(std::string& buffer, int& method_rc); - int map(std::string& buffer, int& method_rc); - int unmap(std::string& buffer, int& method_rc); - int getError(std::string& buffer, int& method_rc); - int getVersion(std::string& buffer, int& method_rc); - int gpRequestCancellation(std::string& buffer, int& method_rc); -}; - -struct ProxyServer::Impl { - int listen_socket = -1; - int signal_pipe[2]; - std::thread thread; -}; - -ProxyServer::ProxyServer(): pimpl_(new Impl) { -} - -ProxyServer::~ProxyServer() { - delete pimpl_; -} - -int ProxyServer::open() { - // Make sure we have access to the driver - DriverClient driver; - if (driver.open()) { - LOG_ERRNO("open driver"); - return -1; - } - driver.close(); - - // Make sure we're alone - int sock = ::socket(AF_UNIX, SOCK_STREAM, 0); - if (sock < 0) { - LOG_ERRNO("socket"); - return -1; - } - struct sockaddr_un sock_un; - sock_un.sun_family = AF_UNIX; - ::strncpy(sock_un.sun_path, SOCKET_PATH, sizeof(sock_un.sun_path) - 1); - socklen_t len = static_cast(strlen(sock_un.sun_path) + - sizeof(sock_un.sun_family)); - sock_un.sun_path[0] = '\0'; // Abstract - if (::bind(sock, reinterpret_cast(&sock_un), len) == 0) { - if (::listen(sock, 5) == 0) { - if (pipe(pimpl_->signal_pipe) == 0) { - pimpl_->listen_socket = sock; - pimpl_->thread = std::thread(&ProxyServer::run, this); - LOG_D("proxy open"); - return 0; - } else { - LOG_ERRNO("pipe"); - } - } else { - LOG_ERRNO("listen"); - } - } else { - LOG_ERRNO("bind"); - } - ::close(sock); - return -1; -} - -int ProxyServer::close() { - if (pimpl_->listen_socket < 0) { - errno = EBADF; - return -1; - } - ::close(pimpl_->listen_socket); - pimpl_->listen_socket = -1; - // Make thread stop - if (pimpl_->thread.joinable()) { - ::write(pimpl_->signal_pipe[1], "c", 1); - ::close(pimpl_->signal_pipe[1]); - pimpl_->thread.join(); - } - LOG_D("proxy closed"); - return 0; -} - -void ProxyServer::run() { - std::vector connections; - - LOG_D("proxy ready"); - while (pimpl_->listen_socket >= 0) { - // Wait for new connections - fd_set fds; - FD_ZERO(&fds); -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wold-style-cast" - FD_SET(pimpl_->signal_pipe[0], &fds); - FD_SET(pimpl_->listen_socket, &fds); -#pragma GCC diagnostic pop - if ((::select(FD_SETSIZE, &fds, nullptr, nullptr, nullptr) < 0) && - (errno != EINTR)) { - LOG_ERRNO("listen on server socket"); - break; - } -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wold-style-cast" - if (FD_ISSET(pimpl_->signal_pipe[0], &fds)) { -#pragma GCC diagnostic pop - LOG_I("thread received stop message"); - // Wait for client threads to stop - for (auto& connection: connections) { - connection->close(); - LOG_D("delete connection %p", connection); - delete connection; - } - break; - } - auto connection = new ServerConnection(pimpl_->listen_socket); - if (connection->open() < 0) { - LOG_ERRNO("new connection"); - delete connection; - // Relax - usleep(100000); - } else { - LOG_D("new connection %p", connection); - connections.push_back(connection); - } - // Cleanup dead connections - auto it = connections.begin(); - while (it != connections.end()) { - auto connection = *it; - if (!connection->isRunning()) { - it = connections.erase(it); - connection->close(); - LOG_D("delete connection %p", connection); - delete connection; - } else { - it++; - } - } - } - LOG_D("proxy exited"); -} - -int ServerConnection::openSession(std::string& buffer, int& method_rc) { - LOG_D("enter %s", __FUNCTION__); - std::lock_guard connection_lock(connection_mutex); - if (session_) { - LOG_E("Session exists"); - return -EBUSY; - } - // Request - OpenSessionRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_uuid() || !request.has_is_gp_uuid() || - !request.has_login_type() || !request.has_login_data()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - // Call driver - struct mc_ioctl_open_session session; - if (request.uuid().length() != sizeof(session.uuid)) { - LOG_E("Incorrect parameter uuid"); - return -EINVAL; - } - ::memcpy(&session.uuid, request.uuid().c_str(), sizeof(session.uuid)); - session.is_gp_uuid = request.is_gp_uuid(); - Session::Buffer* tci; - if (request.has_tci()) { - tci = new Session::Buffer(request.tci()); - session.tcilen = tci->info().len; - session.tci = tci->info().va; - } else { - tci = nullptr; - session.tcilen = 0; - session.tci = 0; - } - std::unique_ptr tci_ptr(tci); - session.identity.login_type = - static_cast(request.login_type()); - session.identity.pid = pid_; - if (request.login_data().length() != sizeof(session.identity.login_data)) { - LOG_E("Incorrect parameter login_data"); - return -EINVAL; - } - ::memcpy(&session.identity.login_data, request.login_data().c_str(), - sizeof(session.identity.login_data)); - - // Call - if (driver.openSession(session)) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // Response - OpenSessionResponse response; - response.set_id(session.sid); - if (!response.SerializeToString(&buffer)) { - LOG_E("Failed to serialize"); - return -EPIPE; - } - LOG_D("session %x open", session.sid); - session_ = new Session(session.sid, tci_ptr.release()); - return static_cast(buffer.length()); -} - -int ServerConnection::openTrustlet(std::string& buffer, int& method_rc) { - LOG_D("enter %s", __FUNCTION__); - std::lock_guard connection_lock(connection_mutex); - if (session_) { - LOG_E("Session exists"); - return -EBUSY; - } - // Request - OpenTrustletRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_spid() || !request.has_trustapp()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - // Call driver - struct mc_ioctl_open_trustlet trustlet; - trustlet.spid = request.spid(); - trustlet.tlen = static_cast(request.trustapp().length()); - // Create TrustApp buffer - FreeMe trustapp = ::malloc(trustlet.tlen); - if (!trustapp) { - LOG_E("Failed to allocate TrustApp"); - return -ENOMEM; - } - ::memcpy(trustapp, request.trustapp().c_str(), trustlet.tlen); - trustlet.buffer = trustapp; - Session::Buffer* tci; - if (request.has_tci()) { - tci = new Session::Buffer(request.tci()); - trustlet.tcilen = tci->info().len; - trustlet.tci = tci->info().va; - } else { - tci = nullptr; - trustlet.tcilen = 0; - trustlet.tci = 0; - } - std::unique_ptr tci_ptr(tci); - - // Call - if (driver.openTrustlet(trustlet)) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // Response - OpenTrustletResponse response; - response.set_id(trustlet.sid); - if (!response.SerializeToString(&buffer)) { - LOG_E("Failed to serialize"); - return -EPIPE; - } - LOG_D("session %x open", trustlet.sid); - session_ = new Session(trustlet.sid, tci_ptr.release()); - return static_cast(buffer.length()); -} - -int ServerConnection::closeSession(std::string& buffer, int& method_rc) { - // Request - CloseSessionRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_id()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - // Check session - std::lock_guard connection_lock(connection_mutex); - if (!session_) { - LOG_E("No session"); - return -ENOENT; - } - - // Call - if (driver.closeSession(request.id())) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // No response - LOG_D("session %x closed", request.id()); - delete session_; - session_ = nullptr; - return 0; -} - -int ServerConnection::notify(std::string& buffer, int& method_rc) { - // Request - NotifyRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - // Check session - std::lock_guard connection_lock(connection_mutex); - if (!session_) { - LOG_E("No session"); - return -ENOENT; - } - if (!request.has_sid() || (session_->hasTci() && !request.has_tci())) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - // Update TCI - if (session_->hasTci() && session_->updateTci(request.tci())) { - LOG_E("Failed to update TCI"); - return -EINVAL; - } - // Update mapped buffers - if (request.buffers_size() > static_cast(session_->buffers().size())) { - LOG_E("Too many buffers: %d > %zu", request.buffers_size(), - session_->buffers().size()); - return -EINVAL; - } - for (int i = 0; i < request.buffers_size(); i++) { - const NotifyRequest_Buffers& session_buffer = request.buffers(i); - if (!session_buffer.has_sva()) { - LOG_E("Given buffer has no SVA"); - return -EINVAL; - } - if (!session_buffer.has_data()) { - LOG_E("Given buffer has no data"); - return -EINVAL; - } - auto buf = session_->findBuffer(session_buffer.sva()); - if (!buf) { - LOG_E("No buffer record for SVA %jx in session %x", - session_buffer.sva(), request.sid()); - return -EPIPE; - } - buf->update(session_buffer.data()); - } - - // Call - if (driver.notify(request.sid())) { - method_rc = errno; - return 0; - } - - // No response - LOG_D("session %x notification sent", request.sid()); - return 0; -} - -int ServerConnection::waitNotification(std::string& buffer, int& method_rc) { - // Request - WaitNotificationRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_sid() || !request.has_timeout() || - !request.has_partial()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - // Refuse big timeouts (client shall retry so we know it's still around) - if ((request.timeout() < 0) || (request.timeout() > timeout_max)) { - LOG_E("Timeout exceeds 10s"); - return -ENOENT; - } - - // Find session - LOG_D("session %x wait for notification", request.sid()); - // Check session - std::lock_guard connection_lock(connection_mutex); - if (!session_) { - LOG_E("No session"); - return -ENOENT; - } - // Call driver - struct mc_ioctl_wait wait; - wait.sid = request.sid(); - wait.timeout = request.timeout(); - - // Call - if (driver.waitNotification(wait)) { - method_rc = errno; - if ((errno == ETIME) && request.partial()) { - // No point sending buffers on partial timeout - return 0; - } - // Send potentially modified buffers back on failure too - LOG_ERRNO("waitNotification"); - } - - // Response - WaitNotificationResponse response; - // Send updated TCI - if (session_->hasTci()) { - response.set_tci(session_->tci(), session_->tciLen()); - } - // Send updated mapped buffers - auto& buffers = session_->buffers(); - for (auto& buf: buffers) { - if (buf->info().flags & MC_IO_MAP_OUTPUT) { - auto session_buffer = response.add_buffers(); - session_buffer->set_sva(buf->info().sva); - session_buffer->set_data(buf->address(), buf->info().len); - } - } - if (!response.SerializeToString(&buffer)) { - LOG_E("Failed to serialize"); - return -EPIPE; - } - LOG_D("session %x notification received", request.sid()); - return static_cast(buffer.length()); -} - -int ServerConnection::map(std::string& buffer, int& method_rc) { - // Request - MapRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_sid()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - // Check session - std::lock_guard connection_lock(connection_mutex); - if (!session_) { - LOG_E("No session"); - return -ENOENT; - } - if (request.buffers_size() > MC_MAP_MAX) { - LOG_E("Incorrect number of buffers: %d > %d", request.buffers_size(), - MC_MAP_MAX); - return -EINVAL; - } - // Prepare local buffers - struct mc_ioctl_map map; - map.sid = request.sid(); - LOG_D("map %d buffers to session %x", request.buffers_size(), map.sid); - std::vector> buffers; - for (int i = 0; i < request.buffers_size(); i++) { - const MapRequest_Buffers& session_buffer = request.buffers(i); - if (!session_buffer.has_len() || !session_buffer.has_flags()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - if (!(session_buffer.flags() & MC_IO_MAP_INPUT_OUTPUT) || - (session_buffer.flags() & ~MC_IO_MAP_INPUT_OUTPUT)) { - LOG_E("Incorrect flags for buffer: %x", session_buffer.flags()); - return -EINVAL; - } - buffers.emplace_back(new Session::Buffer(session_buffer.len(), - session_buffer.flags())); - map.bufs[i] = buffers.back()->info(); - } - for (int i = request.buffers_size(); i < MC_MAP_MAX; i++) { - map.bufs[i].va = 0; - } - - // Call - if (driver.map(map)) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // Response - MapResponse response; - // Confirm/return buffers - for (int i = 0; i < request.buffers_size(); i++) { - Session::Buffer* buf = buffers[i].release(); - buf->setSva(map.bufs[i].sva); - session_->addBuffer(buf); - auto session_buffer = response.add_buffers(); - session_buffer->set_sva(map.bufs[i].sva); - } - if (!response.SerializeToString(&buffer)) { - LOG_E("Failed to serialize"); - return -EPIPE; - } - LOG_D("session %x %d buffer(s) mapped", map.sid, request.buffers_size()); - return static_cast(buffer.length()); -} - -int ServerConnection::unmap(std::string& buffer, int& method_rc) { - // Request - UnmapRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_sid()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - if (request.buffers_size() > MC_MAP_MAX) { - LOG_E("Incorrect number of buffers: %d", request.buffers_size()); - return -EINVAL; - } - // Check session - std::lock_guard connection_lock(connection_mutex); - if (!session_) { - LOG_E("No session"); - return -ENOENT; - } - // Find local buffers - struct mc_ioctl_map map; - map.sid = request.sid(); - LOG_D("unmap %d buffers from session %x", request.buffers_size(), map.sid); - if (request.buffers_size() > static_cast(session_->buffers().size())) { - LOG_E("More buffers to unmap than we have: %d > %zu", - request.buffers_size(), session_->buffers().size()); - return -EINVAL; - } - std::vector buffers; - for (int i = 0; i < request.buffers_size(); i++) { - // Need to find buffer to get VA/length - const UnmapRequest_Buffers& session_buffer = request.buffers(i); - if (!session_buffer.has_sva()) { - LOG_E("Given buffer has no SVA"); - return -EINVAL; - } - auto buf = session_->findBuffer(session_buffer.sva()); - if (!buf) { - LOG_E("No buffer record for SVA %jx in session %x", - session_buffer.sva(), request.sid()); - method_rc = EINVAL; - return 0; - } - map.bufs[i] = buf->info(); - buffers.push_back(buf); - } - for (int i = request.buffers_size(); i < MC_MAP_MAX; i++) { - map.bufs[i].va = 0; - } - - // Call - if (driver.unmap(map)) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // No response - // Delete buffers - for (size_t i = 0; i < buffers.size(); i++) { - if (session_->removeBuffer(buffers[i]->info().sva)) { - LOG_E("Did not find our buffer anymore!?!"); - return -EPIPE; - } - } - LOG_D("session %x %d buffer(s) unmapped", map.sid, request.buffers_size()); - return 0; -} - -int ServerConnection::getError(std::string& buffer, int& method_rc) { - // Request - GetErrorRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_sid()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - struct mc_ioctl_geterr err; - err.sid = request.sid(); - - // Call - if (driver.getError(err)) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // Response - GetErrorResponse response; - response.set_exit_code(err.value); - if (!response.SerializeToString(&buffer)) { - LOG_E("Failed to serialize"); - return -EPIPE; - } - LOG_D("session %x exit code %d", err.sid, err.value); - return static_cast(buffer.length()); -} - -int ServerConnection::getVersion(std::string& buffer, int& method_rc) { - // Request - GetVersionRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - // No inputs to check - struct mc_version_info version_info; - - // Call - if (driver.getVersion(version_info)) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // Response - GetVersionResponse response; - response.set_product_id(version_info.product_id); - response.set_mci(version_info.version_mci); - response.set_so(version_info.version_so); - response.set_mclf(version_info.version_mclf); - response.set_container(version_info.version_container); - response.set_mc_config(version_info.version_mc_config); - response.set_tl_api(version_info.version_tl_api); - response.set_dr_api(version_info.version_dr_api); - response.set_nwd(version_info.version_nwd); - if (!response.SerializeToString(&buffer)) { - LOG_E("Failed to serialize"); - return -EPIPE; - } - return static_cast(buffer.length()); -} - -int ServerConnection::gpRequestCancellation(std::string& buffer, - int& method_rc) { - // Request - GetErrorRequest request; - if (!request.ParseFromString(buffer)) { - LOG_E("Failed to parse"); - return -EPIPE; - } - if (!request.has_sid()) { - LOG_E("Required parameter missing"); - return -EINVAL; - } - - // Call - if (driver.gpRequestCancellation(request.sid())) { - method_rc = errno; - LOG_D("Error reported %s", strerror(errno)); - return 0; - } - - // No response - return 0; -} diff --git a/mobicore/ClientLib/src/tee_client_api.cpp b/mobicore/ClientLib/src/tee_client_api.cpp deleted file mode 100644 index 5bcf06b..0000000 --- a/mobicore/ClientLib/src/tee_client_api.cpp +++ /dev/null @@ -1,972 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Mci/mcinq.h" /* TA termination codes */ - -#undef LOG_TAG -#define LOG_TAG "TeeGpClient" -#include "log.h" -#include "common_client.h" -#include "tee_client_api.h" -#include "GpTci.h" /* Needs stuff from tee_client_api.h or its includes */ - -//------------------------------------------------------------------------------ -// Macros -#define _TEEC_GET_PARAM_TYPE(t, i) (((t) >> (4*i)) & 0xF) - -//Parameter number -#define _TEEC_PARAMETER_NUMBER 4 - -/** - * These error codes are still to be decided by GP and as we do not wish to - * expose any part of the GP TAF as of yet, for now they will have to live here - * until we decide what to do about them. - */ -#define TEEC_ERROR_TA_LOCKED 0xFFFF0257 -#define TEEC_ERROR_SD_BLOCKED 0xFFFF0258 -#define TEEC_ERROR_TARGET_KILLED 0xFFFF0259 - -static const size_t page_size = static_cast(sysconf(_SC_PAGESIZE)); -static CommonClient& client = CommonClient::getInstance(); - -//------------------------------------------------------------------------------ -// Local functions -static TEEC_Result _TEEC_UnwindOperation( - TEEC_Session_IMP* session, - _TEEC_TCI* tci, - TEEC_Operation* operation, - bool copyValues, - uint32_t* returnOrigin); - -//------------------------------------------------------------------------------ -static void _libUuidToArray( - const TEEC_UUID* uuid, - uint8_t* uuidArr) { - uint8_t* pIdentifierCursor = (uint8_t*)uuid; - /* offsets and syntax constants. See explanations above */ -#ifdef S_BIG_ENDIAN - uint32_t offsets = 0; -#else - uint32_t offsets = 0xF1F1DF13; -#endif - uint32_t i; - - for (i = 0; i < sizeof(TEEC_UUID); i++) { - /* Two-digit hex number */ - uint8_t number; - int32_t offset = ((int32_t)((offsets & 0xF) << 28)) >> 28; - number = pIdentifierCursor[offset]; - offsets >>= 4; - pIdentifierCursor++; - - uuidArr[i] = number; - } -} - -//------------------------------------------------------------------------------ -static TEEC_Result _TEEC_SetupOperation( - TEEC_Session_IMP* session, - _TEEC_TCI* tci, - TEEC_Operation* operation, - uint32_t* returnOrigin) { - uint32_t i; - _TEEC_ParameterInternal* imp; - TEEC_Parameter* ext; - TEEC_Result teecResult = TEEC_SUCCESS; - - LOG_D(" %s()", __func__); - - tci->operation.isCancelled = false; - tci->operation.paramTypes = 0; - - //operation can be NULL - if (operation) { - uint32_t n_buf = 0; - operation->started = 1; - // Buffers to map to SWd - struct mc_ioctl_map map; - map.sid = session->sessionId; - // Operation parameters for the buffers above - _TEEC_ParameterInternal* imps[_TEEC_PARAMETER_NUMBER] = { NULL }; - - //This design allows a non-NULL buffer with a size of 0 bytes to allow trivial integration with any - //implementations of the C library malloc, in which is valid to allocate a zero byte buffer and receive a non- - //NULL pointer which may not be de-referenced in return. - - for (i = 0; i < _TEEC_PARAMETER_NUMBER && teecResult == TEEC_SUCCESS; i++) { - uint8_t paramType = _TEEC_GET_PARAM_TYPE(operation->paramTypes, i); - - imp = &tci->operation.params[i]; - ext = &operation->params[i]; - - switch (paramType) { - case TEEC_VALUE_OUTPUT: - LOG_D(" cycle %d, TEEC_VALUE_OUTPUT", i); - break; - case TEEC_NONE: - LOG_D(" cycle %d, TEEC_NONE", i); - break; - case TEEC_VALUE_INPUT: - case TEEC_VALUE_INOUT: { - LOG_D(" cycle %d, TEEC_VALUE_IN*", i); - imp->value.a = ext->value.a; - imp->value.b = ext->value.b; - break; - } - case TEEC_MEMREF_TEMP_INPUT: - case TEEC_MEMREF_TEMP_OUTPUT: - case TEEC_MEMREF_TEMP_INOUT: { - // A Temporary Memory Reference may be null, which can be used - // to denote a special case for the parameter. Output Memory - // References that are null are typically used to request the - // required output size. - LOG_D(" cycle %d, TEEC_MEMREF_TEMP_*", i); - if ((ext->tmpref.size) && (ext->tmpref.buffer)) { - map.bufs[n_buf].va = (uintptr_t)ext->tmpref.buffer; - map.bufs[n_buf].len = (uint32_t)ext->tmpref.size; - map.bufs[n_buf].flags = paramType & TEEC_MEM_INOUT; - imps[n_buf] = imp; - n_buf++; - } else { - LOG_D(" cycle %d, TEEC_TEMP_IN* - zero pointer or size", i); - } - break; - } - case TEEC_MEMREF_WHOLE: { - LOG_D(" cycle %d, TEEC_MEMREF_WHOLE", i); - if (ext->memref.parent->size) { - map.bufs[n_buf].va = (uintptr_t)ext->memref.parent->buffer; - map.bufs[n_buf].len = (uint32_t)ext->memref.parent->size; - map.bufs[n_buf].flags = ext->memref.parent->flags & TEEC_MEM_INOUT; - imps[n_buf] = imp; - n_buf++; - } - /* We don't transmit that the mem ref is the whole shared mem */ - /* Magic number 4 means that it is a mem ref */ - paramType = (uint8_t)ext->memref.parent->flags | 4; - break; - } - case TEEC_MEMREF_PARTIAL_INPUT: - case TEEC_MEMREF_PARTIAL_OUTPUT: - case TEEC_MEMREF_PARTIAL_INOUT: { - LOG_D(" cycle %d, TEEC_MEMREF_PARTIAL_*", i); - //Check data flow consistency - if ((((ext->memref.parent->flags & TEEC_MEM_INOUT) == TEEC_MEM_INPUT) && - (paramType == TEEC_MEMREF_PARTIAL_OUTPUT)) || - (((ext->memref.parent->flags & TEEC_MEM_INOUT) == TEEC_MEM_OUTPUT) && - (paramType == TEEC_MEMREF_PARTIAL_INPUT))) { - LOG_E("PARTIAL data flow inconsistency"); - *returnOrigin = TEEC_ORIGIN_API; - teecResult = TEEC_ERROR_BAD_PARAMETERS; - break; - } - /* We don't transmit that the mem ref is partial */ - paramType &= TEEC_MEMREF_TEMP_INOUT; - - if (ext->memref.offset + ext->memref.size > ext->memref.parent->size) { - LOG_E("PARTIAL offset/size error"); - *returnOrigin = TEEC_ORIGIN_API; - teecResult = TEEC_ERROR_BAD_PARAMETERS; - break; - } - if (ext->memref.size) { - map.bufs[n_buf].va = (uintptr_t)ext->memref.parent->buffer + ext->memref.offset; - map.bufs[n_buf].len = (uint32_t)ext->memref.size; - map.bufs[n_buf].flags = paramType & TEEC_MEM_INOUT; - imps[n_buf] = imp; - n_buf++; - } - break; - } - default: - LOG_E("cycle %d, default", i); - *returnOrigin = TEEC_ORIGIN_API; - teecResult = TEEC_ERROR_BAD_PARAMETERS; - break; - } - tci->operation.paramTypes |= (uint32_t)(paramType << i * 4); - } - - if (n_buf > MC_MAP_MAX) { - LOG_E("too many buffers: %s", strerror(errno)); - teecResult = TEEC_ERROR_EXCESS_DATA; - } - - if ((teecResult == TEEC_SUCCESS) && (tci->operation.isCancelled)) { - LOG_E("the operation has been cancelled in COMMS"); - *returnOrigin = TEEC_ORIGIN_COMMS; - teecResult = TEEC_ERROR_CANCEL; - } - - // Map buffers - if ((teecResult == TEEC_SUCCESS) && (n_buf > 0)) { - for (i = n_buf; i < MC_MAP_MAX; i++) { - map.bufs[i].va = 0; - } - if (client.map(map) == 0) { - for (i = 0; i < MC_MAP_MAX; i++) { - if (map.bufs[i].va) { - imps[i]->memref.sVirtualAddr = (uint32_t)map.bufs[i].sva; - imps[i]->memref.sVirtualLen = map.bufs[i].len; - } - } - } else { - LOG_E("client map failed: %s", strerror(errno)); - *returnOrigin = TEEC_ORIGIN_COMMS; - teecResult = TEEC_ERROR_GENERIC; - } - } - - if (teecResult != TEEC_SUCCESS) { - uint32_t retOrigIgnored; - _TEEC_UnwindOperation(session, tci, operation, false, &retOrigIgnored); - //Zeroing out tci->operation - ::memset(&tci->operation, 0, sizeof(tci->operation)); - return teecResult; - } - } - - //Copy version indicator field - ::memcpy(tci->header, "TCIGP000", sizeof(tci->header)); - - // Fill in invalid values for secure world to overwrite - tci->returnStatus = TEEC_ERROR_BAD_STATE; - - // Signal completion of request writing - tci->ready = 1; - - return teecResult; -} - -//------------------------------------------------------------------------------ -static TEEC_Result _TEEC_UnwindOperation( - TEEC_Session_IMP* session, - _TEEC_TCI* tci, - TEEC_Operation* operation, - bool copyValues, - uint32_t* returnOrigin) { - uint32_t i; - _TEEC_ParameterInternal* imp; - TEEC_Parameter* ext; - uint32_t n_buf = 0; - - //operation can be NULL - if (operation == NULL) { - return TEEC_SUCCESS; - } - - LOG_D(" %s()", __func__); - - operation->started = 2; - // Buffers to unmap from SWd - struct mc_ioctl_map map; - map.sid = session->sessionId; - // Some sanity checks - if (tci->returnOrigin == 0 || - ((tci->returnOrigin != TEEC_ORIGIN_TRUSTED_APP) && - (tci->returnStatus != TEEC_SUCCESS))) { - *returnOrigin = TEEC_ORIGIN_COMMS; - return TEEC_ERROR_COMMUNICATION; - } - *returnOrigin = tci->returnOrigin; - - //Clear sVirtualLen to unMap further - for (i = 0; i < _TEEC_PARAMETER_NUMBER; i++) { - imp = &tci->operation.params[i]; - ext = &operation->params[i]; - - switch (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i)) { - case TEEC_VALUE_INPUT: - LOG_D(" cycle %d, TEEC_VALUE_INPUT", i); - break; - case TEEC_NONE: - LOG_D(" cycle %d, TEEC_NONE", i); - break; - case TEEC_VALUE_OUTPUT: - case TEEC_VALUE_INOUT: { - LOG_D(" cycle %d, TEEC_VALUE_*OUT", i); - if (copyValues) { - ext->value.a = imp->value.a; - ext->value.b = imp->value.b; - } - break; - } - case TEEC_MEMREF_TEMP_OUTPUT: - case TEEC_MEMREF_TEMP_INPUT: - case TEEC_MEMREF_TEMP_INOUT: { - LOG_D(" cycle %d, TEEC_TEMP*", i); - if ((copyValues) && - (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i) != TEEC_MEMREF_TEMP_INPUT)) { - ext->tmpref.size = imp->memref.outputSize; - } - if (imp->memref.sVirtualLen > 0) { - map.bufs[n_buf].va = (uintptr_t)ext->tmpref.buffer; - map.bufs[n_buf].sva = imp->memref.sVirtualAddr; - map.bufs[n_buf].len = imp->memref.sVirtualLen; - n_buf++; - } - break; - } - case TEEC_MEMREF_WHOLE: { - LOG_D(" cycle %d, TEEC_MEMREF_WHOLE", i); - if ((copyValues) && (ext->memref.parent->flags != TEEC_MEM_INPUT)) { - ext->memref.size = imp->memref.outputSize; - } - if (imp->memref.sVirtualLen > 0) { - map.bufs[n_buf].va = (uintptr_t)ext->memref.parent->buffer; - map.bufs[n_buf].sva = imp->memref.sVirtualAddr; - map.bufs[n_buf].len = imp->memref.sVirtualLen; - n_buf++; - } - break; - } - - case TEEC_MEMREF_PARTIAL_OUTPUT: - case TEEC_MEMREF_PARTIAL_INOUT: - case TEEC_MEMREF_PARTIAL_INPUT: { - LOG_D(" cycle %d, TEEC_MEMREF_PARTIAL*", i); - if ((copyValues) && - (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i) != TEEC_MEMREF_PARTIAL_INPUT)) { - ext->memref.size = imp->memref.outputSize; - } - if (imp->memref.sVirtualLen > 0) { - map.bufs[n_buf].va = (uintptr_t)ext->memref.parent->buffer + ext->memref.offset; - map.bufs[n_buf].sva = imp->memref.sVirtualAddr; - map.bufs[n_buf].len = imp->memref.sVirtualLen; - n_buf++; - } - break; - } - default: - LOG_E("cycle %d, bad parameter", i); - break; - } - } - - if (n_buf > MC_MAP_MAX) { - LOG_E("too many buffers: %s", strerror(errno)); - return TEEC_ERROR_EXCESS_DATA; - } - - for (i = n_buf; i < MC_MAP_MAX; i++) { - map.bufs[i].va = 0; - } - - if (n_buf > 0) { - // This function assumes that we cannot handle errors - if (client.unmap(map) < 0) { - LOG_E("client unmap failed: %s", strerror(errno)); - } - } - - return tci->returnStatus; -} - -//------------------------------------------------------------------------------ -//TEEC_InitializeContext: TEEC_SUCCESS, Another error code from Table 4-2. -TEEC_Result TEEC_InitializeContext( - const char* name, - TEEC_Context* context) { - (void) name; - LOG_D("== %s() ==============", __func__); - - if (context == NULL) { - LOG_E("context is NULL"); - return TEEC_ERROR_BAD_PARAMETERS; - } - - // For test purpose - switch (context->imp.reserved) { - case CommonClient::DRIVER: - client.setOpenMode(CommonClient::DRIVER); - break; - case CommonClient::PROXY: - client.setOpenMode(CommonClient::PROXY); - break; - } - - if (client.open()) { - switch (errno) { - case ENOENT: - return TEEC_ERROR_COMMUNICATION; - case EINVAL: - return TEEC_ERROR_BAD_PARAMETERS; - default: - return TEEC_ERROR_GENERIC; - } - } - - return TEEC_SUCCESS; -} - -//------------------------------------------------------------------------------ -//TEEC_FinalizeContext: void - -// The implementation of this function MUST NOT be able to fail: after this function returns the Client -// Application must be able to consider that the Context has been closed. - -void TEEC_FinalizeContext( - TEEC_Context* context) { - LOG_D("== %s() ==============", __func__); - - // The parameter context MUST point to an initialized TEE Context. - if (context == NULL) { - LOG_E("context is NULL"); - return; - } - - // The implementation of this function MUST NOT be able to fail: after this function returns the Client - // Application must be able to consider that the Context has been closed. - if (client.close()) { - LOG_E("mcCloseDevice failed: %s", strerror(errno)); - /* continue even in case of error */; - } -} - -static void _TEEC_DeleteTci(TEEC_Session_IMP* session_imp) { - if (session_imp->tci) { - ::munmap(session_imp->tci, page_size); - session_imp->tci = NULL; - } -} - -static void _TEEC_CloseSession(TEEC_Session_IMP* session_imp) { - if (client.closeSession(session_imp->sessionId)) { - LOG_E("%s failed: %s", __func__, strerror(errno)); - } - session_imp->active = false; -} - -//------------------------------------------------------------------------------ -static TEEC_Result _TEEC_CallTA( - TEEC_Session_IMP* session, - TEEC_Operation* operation, - uint32_t* returnOrigin) { - TEEC_Result teecRes; - TEEC_Result teecError = TEEC_SUCCESS; - int ret = 0; - - LOG_D(" %s()", __func__); - - // Phase 1: start the operation and wait for the result - _TEEC_TCI* tci = static_cast<_TEEC_TCI*>(session->tci); - teecRes = _TEEC_SetupOperation(session, tci, operation, returnOrigin); - if (teecRes != TEEC_SUCCESS ) { - LOG_E("_TEEC_SetupOperation failed (%08x)", teecRes); - return teecRes; - } - - // Signal the Trusted App - ret = client.notify(session->sessionId); - if (ret) { - LOG_E("Notify failed: %s", strerror(errno)); - teecError = TEEC_ERROR_COMMUNICATION; - } else { - // ------------------------------------------------------------- - // Wait for the Trusted App response - struct mc_ioctl_wait wait; - wait.sid = session->sessionId; - wait.timeout = -1; - ret = client.waitNotification(wait); - if (ret) { - teecError = TEEC_ERROR_COMMUNICATION; - if (errno == ECOMM) { - struct mc_ioctl_geterr err; - err.sid = session->sessionId; - - ret = client.getError(err); - switch (err.value) { - case TA_EXIT_CODE_FINISHED: - // We may get here if the TA_OpenSessionEntryPoint returns an error and TA goes fast through DestroyEntryPoint and exits the TA. - teecError = TEEC_SUCCESS; - break; - case ERR_SESSION_KILLED: - teecError = TEEC_ERROR_TARGET_KILLED; - break; - case ERR_INVALID_SID: - case ERR_SID_NOT_ACTIVE: - LOG_E("mcWaitNotification failed: %s", strerror(errno)); - LOG_E("mcGetSessionErrorCode returned %d", err.value); - break; - default: - LOG_E("Target is DEAD"); - *returnOrigin = TEEC_ORIGIN_TEE; - teecError = TEEC_ERROR_TARGET_DEAD; - break; - } - } - } - } - // Phase 2: Return values and cleanup - // unmap memory and copy values if no error - teecRes = _TEEC_UnwindOperation(session, tci, operation, - (teecError == TEEC_SUCCESS), returnOrigin); - if (teecRes != TEEC_SUCCESS ) { - LOG_E("_TEEC_UnwindOperation (%08x)", teecRes); - /* continue even in case of error */; - } - - // Cleanup - if (teecError != TEEC_SUCCESS) { - if (teecError == TEEC_ERROR_COMMUNICATION) { - *returnOrigin = TEEC_ORIGIN_COMMS; - } - // Previous interactions failed, either TA is dead or communication error - _TEEC_CloseSession(session); - _TEEC_DeleteTci(session); - } - return teecError; -} - -//------------------------------------------------------------------------------ -//TEEC_OpenSession: if the returnOrigin is different from TEEC_ORIGIN_TRUSTED_APP, an error code from Table 4-2 -// If the returnOrigin is equal to TEEC_ORIGIN_TRUSTED_APP, a return code defined by the -//protocol between the Client Application and the Trusted Application. -TEEC_Result TEEC_OpenSession ( - TEEC_Context* context, - TEEC_Session* session, - const TEEC_UUID* destination, - uint32_t connectionMethod, - const void* connectionData, - TEEC_Operation* operation, - uint32_t* returnOrigin) { - TEEC_Result teecRes; - uint32_t returnOrigin_local = TEEC_ORIGIN_API; - struct mc_uuid_t tauuid; - int ret = 0; - - LOG_D("== %s() ==============", __func__); - // ------------------------------------------------------------- - //The parameter context MUST point to an initialized TEE Context. - if (context == NULL) { - LOG_E("context is NULL"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_BAD_PARAMETERS; - } - - if (session == NULL) { - LOG_E("session is NULL"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_BAD_PARAMETERS; - } - - if ((connectionMethod != TEEC_LOGIN_PUBLIC) && - (connectionMethod != TEEC_LOGIN_USER) && - (connectionMethod != TEEC_LOGIN_GROUP) && - (connectionMethod != TEEC_LOGIN_APPLICATION) && - (connectionMethod != TEEC_LOGIN_USER_APPLICATION) && - (connectionMethod != TEEC_LOGIN_GROUP_APPLICATION)) { - LOG_E("connectionMethod not supported"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_NOT_IMPLEMENTED; - } - - if ((TEEC_LOGIN_GROUP == connectionMethod) || - (TEEC_LOGIN_GROUP_APPLICATION == connectionMethod)) { - if (NULL == connectionData) { - LOG_E("connectionData is NULL"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_BAD_PARAMETERS; - } - } - - // ------------------------------------------------------------- - session->imp.active = false; - - _libUuidToArray(destination, tauuid.value); - - if (operation) { - operation->imp.session = &session->imp; - } - - //Allocate a 4kB page with mmap, zero it out, and set session->imp.tci to its address. - session->imp.tci = NULL; - void* bulkBuf = (void*)::mmap(0, page_size, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if (bulkBuf == MAP_FAILED) { - LOG_E("mmap failed on tci buffer allocation"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_OUT_OF_MEMORY; - } - - session->imp.tci = bulkBuf; - ::memset(session->imp.tci, 0, page_size); - - ::pthread_mutex_init(&session->imp.mutex_tci, NULL); - ::pthread_mutex_lock(&session->imp.mutex_tci); - - //Fill the TCI buffer session.tci with the destination UUID. - _TEEC_TCI* tci = static_cast<_TEEC_TCI*>(session->imp.tci); - ::memcpy(&tci->destination, destination, sizeof(tci->destination)); - // ------------------------------------------------------------- - struct mc_ioctl_open_session sess; - sess.sid = 0; - sess.tci = (uintptr_t)tci; - sess.tcilen = sizeof(_TEEC_TCI); - sess.uuid = tauuid; - sess.is_gp_uuid = 1; - sess.identity.login_type = static_cast(connectionMethod); - sess.identity.pid = 0; - if (connectionData) { - ::memcpy(&sess.identity.login_data, connectionData, - sizeof(sess.identity.login_data)); - } - - ret = client.openSession(sess); - if (ret) { - LOG_E("%s failed: %s", __func__, strerror(errno)); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_COMMS; - } - switch (errno) { - case ENOENT: - teecRes = TEEC_ERROR_ITEM_NOT_FOUND; - break; - case EACCES: - teecRes = TEEC_ERROR_ACCESS_DENIED; - break; - case EINVAL: - teecRes = TEEC_ERROR_NOT_IMPLEMENTED; - break; - case ENOSPC: - teecRes = TEEC_ERROR_OUT_OF_MEMORY; - break; - case ECONNREFUSED: - teecRes = TEEC_ERROR_SD_BLOCKED; - break; - case ECONNABORTED: - teecRes = TEEC_ERROR_TA_LOCKED; - break; - case ECONNRESET: - teecRes = TEEC_ERROR_TARGET_KILLED; - break; - case EBUSY: - teecRes = TEEC_ERROR_BUSY; - break; - default: - teecRes = TEEC_ERROR_GENERIC; - } - goto error; - } - - session->imp.context = context->imp; - session->imp.sessionId = sess.sid; - session->imp.active = true; - LOG_I(" created session ID %x", session->imp.sessionId); - - // Let TA go through entry points - LOG_D(" let TA go through entry points"); - tci->operation.type = _TA_OPERATION_OPEN_SESSION; - teecRes = _TEEC_CallTA(&session->imp, operation, &returnOrigin_local); - - // Check for error on communication level - if (teecRes != TEEC_SUCCESS ) { - LOG_E("_TEEC_CallTA failed(%08x)", teecRes); - // Nothing to do here because _TEEC_CallTA closes broken sessions - if (returnOrigin) { - *returnOrigin = returnOrigin_local; - } - goto error; - } - LOG_D(" no errors in com layer"); - - // Check for error from TA - if (returnOrigin) { - *returnOrigin = tci->returnOrigin; - } - teecRes = tci->returnStatus; - if (teecRes != TEEC_SUCCESS ) { - LOG_E("TA OpenSession EP failed(%08x)", teecRes); - goto error; - } - - LOG_D(" %s() = TEEC_SUCCESS ", __func__); - ::pthread_mutex_unlock(&session->imp.mutex_tci); - - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_TRUSTED_APP; - } - return TEEC_SUCCESS; - - // ------------------------------------------------------------- -error: - if (session->imp.active) { - // After notifying us, TA went to Destry EP, so close session now - _TEEC_CloseSession(&session->imp); - } - - ::pthread_mutex_unlock(&session->imp.mutex_tci); - ::pthread_mutex_destroy(&session->imp.mutex_tci); - _TEEC_DeleteTci(&session->imp); - - LOG_D(" %s() = 0x%x", __func__, teecRes); - return teecRes; -} - -//------------------------------------------------------------------------------ -TEEC_Result TEEC_InvokeCommand( - TEEC_Session* session, - uint32_t commandID, - TEEC_Operation* operation, - uint32_t* returnOrigin) { - TEEC_Result teecRes; - uint32_t returnOrigin_local = TEEC_ORIGIN_API; - - LOG_D("== %s() ==============", __func__); - - // ------------------------------------------------------------- - if (session == NULL) { - LOG_E("session is NULL"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_BAD_PARAMETERS; - } - - if (!session->imp.active) { - LOG_E("session is inactive"); - if (returnOrigin) { - *returnOrigin = TEEC_ORIGIN_API; - } - return TEEC_ERROR_BAD_STATE; - } - // ------------------------------------------------------------- - if (operation) { - operation->imp.session = &session->imp; - } - - ::pthread_mutex_lock(&session->imp.mutex_tci); - - // Call TA - _TEEC_TCI* tci = static_cast<_TEEC_TCI*>(session->imp.tci); - tci->operation.commandId = commandID; - tci->operation.type = _TA_OPERATION_INVOKE_COMMAND; - teecRes = _TEEC_CallTA(&session->imp, operation, &returnOrigin_local); - if (teecRes != TEEC_SUCCESS ) { - LOG_E("_TEEC_CallTA failed(%08x)", teecRes); - if (returnOrigin) { - *returnOrigin = returnOrigin_local; - } - } else { - if (returnOrigin) { - *returnOrigin = tci->returnOrigin; - } - teecRes = tci->returnStatus; - } - - ::pthread_mutex_unlock(&session->imp.mutex_tci); - LOG_D(" %s() = 0x%x", __func__, teecRes); - return teecRes; -} - -//------------------------------------------------------------------------------ -void TEEC_CloseSession(TEEC_Session* session) { - TEEC_Result teecRes = TEEC_SUCCESS; - uint32_t returnOrigin; - - LOG_D("== %s() ==============", __func__); - - // ------------------------------------------------------------- - //The Implementation MUST do nothing if the session parameter is NULL. - if (session == NULL) { - LOG_E("session is NULL"); - return; - } - - // ------------------------------------------------------------- - if (session->imp.active) { - // Let TA go through CloseSession and Destroy entry points - LOG_D(" let TA go through close entry points"); - ::pthread_mutex_lock(&session->imp.mutex_tci); - _TEEC_TCI* tci = static_cast<_TEEC_TCI*>(session->imp.tci); - tci->operation.type = _TA_OPERATION_CLOSE_SESSION; - teecRes = _TEEC_CallTA(&session->imp, NULL, &returnOrigin); - if (teecRes != TEEC_SUCCESS ) { - /* continue even in case of error */; - LOG_E("_TEEC_CallTA failed(%08x)", teecRes); - } - - if (session->imp.active) { - _TEEC_CloseSession(&session->imp); - } - ::pthread_mutex_unlock(&session->imp.mutex_tci); - } - - ::pthread_mutex_destroy(&session->imp.mutex_tci); - _TEEC_DeleteTci(&session->imp); - - LOG_D(" %s() = 0x%x", __func__, teecRes); -} - -//------------------------------------------------------------------------------ -TEEC_Result TEEC_RegisterSharedMemory( - TEEC_Context* context, - TEEC_SharedMemory* sharedMem) { - LOG_D("== %s() ==============", __func__); - - //The parameter context MUST point to an initialized TEE Context. - if (context == NULL) { - LOG_E("context is NULL"); - return TEEC_ERROR_BAD_PARAMETERS; - } - //The parameter sharedMem MUST point to the Shared Memory structure defining - //the memory region to register. - if (sharedMem == NULL) { - LOG_E("sharedMem is NULL"); - return TEEC_ERROR_BAD_PARAMETERS; - } - //The buffer field MUST point to the memory region to be shared, and MUST not be NULL. - if (sharedMem->buffer == NULL) { - LOG_E("sharedMem->buffer is NULL"); - return TEEC_ERROR_BAD_PARAMETERS; - } - if ((static_cast(sharedMem->flags) & ~TEEC_MEM_INOUT)) { - LOG_E("sharedMem->flags is incorrect"); - return TEEC_ERROR_BAD_PARAMETERS; - } - if (sharedMem->flags == 0) { - LOG_E("sharedMem->flags is incorrect"); - return TEEC_ERROR_BAD_PARAMETERS; - } - - sharedMem->imp.implementation_allocated = false; - return TEEC_SUCCESS; -} - -//------------------------------------------------------------------------------ -TEEC_Result TEEC_AllocateSharedMemory( - TEEC_Context* context, - TEEC_SharedMemory* sharedMem) { - //No connection to "context"? - LOG_D("== %s() ==============", __func__); - - //The parameter context MUST point to an initialized TEE Context. - if (context == NULL) { - LOG_E("context is NULL"); - return TEEC_ERROR_BAD_PARAMETERS; - } - //The parameter sharedMem MUST point to the Shared Memory structure defining - //the memory region to register. - if (sharedMem == NULL) { - LOG_E("sharedMem is NULL"); - return TEEC_ERROR_BAD_PARAMETERS; - } - if (static_cast(sharedMem->flags) & ~TEEC_MEM_INOUT) { - LOG_E("sharedMem->flags is incorrect"); - return TEEC_ERROR_BAD_PARAMETERS; - } - if (sharedMem->flags == 0) { - LOG_E("sharedMem->flags is incorrect"); - return TEEC_ERROR_BAD_PARAMETERS; - } - - sharedMem->buffer = malloc(sharedMem->size); - if (sharedMem->buffer == NULL) { - LOG_E("malloc failed"); - return TEEC_ERROR_OUT_OF_MEMORY; - } - sharedMem->imp.implementation_allocated = true; - - return TEEC_SUCCESS; -} - -//------------------------------------------------------------------------------ -void TEEC_ReleaseSharedMemory ( - TEEC_SharedMemory* sharedMem) { - //No connection to "context"? - LOG_D("== %s() ==============", __func__); - - //The Implementation MUST do nothing if the sharedMem parameter is NULL - if (sharedMem == NULL) { - LOG_E("sharedMem is NULL"); - return; - } - - //For a memory buffer allocated using TEEC_AllocateSharedMemory the Implementation - //MUST free the underlying memory - if (sharedMem->imp.implementation_allocated) { - if (sharedMem->buffer) { - free(sharedMem->buffer); - sharedMem->buffer = NULL; - sharedMem->size = 0; - } - } -} - -//------------------------------------------------------------------------------ -void TEEC_RequestCancellation( - TEEC_Operation* operation) { - LOG_D("== %s() ==============", __func__); - - while (operation->started == 0); - - LOG_D("while(operation->started ==0) passed"); - - if (operation->started > 1) { - LOG_D("The operation has finished"); - return; - } - - TEEC_Session_IMP* session = operation->imp.session; - operation->started = 2; - - if (!session->active) { - LOG_D("Corresponding session is not active"); - return; - } - - if (client.gpRequestCancellation(session->sessionId)) { - LOG_ERRNO("gpRequestCancellation"); - } -} - -//------------------------------------------------------------------------------ diff --git a/mobicore/Daemon/Android.mk b/mobicore/Daemon/Android.mk deleted file mode 100644 index 7fedf8d..0000000 --- a/mobicore/Daemon/Android.mk +++ /dev/null @@ -1,145 +0,0 @@ -# ============================================================================= -# -# MobiCore Android build components -# -# ============================================================================= - -LOCAL_PATH := $(call my-dir) - -# Registry Shared Library -# ============================================================================= -include $(CLEAR_VARS) - -LOCAL_MODULE := libMcRegistry -LOCAL_MODULE_TAGS := eng - -LOCAL_CFLAGS += -DLOG_TAG=\"McRegistry\" -LOCAL_CFLAGS += -Wall -Wextra -LOCAL_CFLAGS += -DLOG_ANDROID - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/include -LOCAL_SHARED_LIBRARIES := libMcClient -ifeq ($(APP_PROJECT_PATH),) -LOCAL_SHARED_LIBRARIES += liblog -else -# Local build -LOCAL_LDLIBS := -llog -endif - -LOCAL_SRC_FILES := \ - src/Connection.cpp \ - src/Registry.cpp - -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include -LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_EXPORT_C_INCLUDES) - -include $(BUILD_SHARED_LIBRARY) - -# Daemon Application -# ============================================================================= -include $(CLEAR_VARS) - -LOCAL_MODULE := mcDriverDaemon -LOCAL_MODULE_TAGS := eng -LOCAL_CFLAGS += -DLOG_TAG=\"McDaemon\" -LOCAL_CFLAGS += -DTBASE_API_LEVEL=5 -LOCAL_CFLAGS += -Wall -Wextra -LOCAL_CFLAGS += -std=c++11 -LOCAL_CFLAGS += -DLOG_ANDROID -ifdef TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_CFLAGS += -DWITHOUT_PROXY -endif # TRUSTONIC_ANDROID_LEGACY_SUPPORT - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/include -LOCAL_STATIC_LIBRARIES := libMcClient_static -ifeq ($(APP_PROJECT_PATH),) -LOCAL_SHARED_LIBRARIES += \ - liblog - -ifdef TRUSTONIC_ANDROID_LEGACY_SUPPORT -include external/stlport/libstlport.mk - -LOCAL_C_INCLUDES += \ - external/stlport/stlport - -LOCAL_SHARED_LIBRARIES += \ - libstlport -else # TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_STATIC_LIBRARIES += \ - libMcProxy - -LOCAL_SHARED_LIBRARIES += \ - libprotobuf-cpp-lite \ - libcutils - -endif # !TRUSTONIC_ANDROID_LEGACY_SUPPORT -else # !NDK -# Local build -LOCAL_LDLIBS := -llog -ifndef TRUSTONIC_ANDROID_LEGACY_SUPPORT -LOCAL_CFLAGS += -static-libstdc++ - -LOCAL_STATIC_LIBRARIES += \ - libMcProxy \ - libprotobuf-cpp-lite -endif # !TRUSTONIC_ANDROID_LEGACY_SUPPORT -endif # NDK - -LOCAL_SRC_FILES := \ - src/Connection.cpp \ - src/CThread.cpp \ - src/MobiCoreDriverDaemon.cpp \ - src/SecureWorld.cpp \ - src/FSD2.cpp \ - src/Server.cpp \ - src/PrivateRegistry.cpp - -include $(BUILD_EXECUTABLE) - -ifndef TRUSTONIC_ANDROID_LEGACY_SUPPORT - -# Static version of the daemon for recovery - -include $(CLEAR_VARS) - -LOCAL_MODULE := mcDriverDaemon_static -LOCAL_MODULE_TAGS := eng -LOCAL_CFLAGS += -DLOG_TAG=\"McDaemon\" -LOCAL_CFLAGS += -DTBASE_API_LEVEL=5 -LOCAL_CFLAGS += -Wall -Wextra -LOCAL_CFLAGS += -std=c++11 -LOCAL_CFLAGS += -DLOG_ANDROID -LOCAL_CFLAGS += -DWITHOUT_FSD -LOCAL_CFLAGS += -DWITHOUT_PROXY - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/include -LOCAL_STATIC_LIBRARIES := libMcClient_static -ifeq ($(APP_PROJECT_PATH),) -LOCAL_STATIC_LIBRARIES += \ - liblog libc libc++_static libcutils - -else # !NDK -# Local build -LOCAL_LDLIBS := -llog -endif # NDK - -LOCAL_SRC_FILES := \ - src/Connection.cpp \ - src/CThread.cpp \ - src/MobiCoreDriverDaemon.cpp \ - src/SecureWorld.cpp \ - src/Server.cpp \ - src/PrivateRegistry.cpp - -LOCAL_FORCE_STATIC_EXECUTABLE := true - -include $(BUILD_EXECUTABLE) - -endif # !TRUSTONIC_ANDROID_LEGACY_SUPPORT - -# adding the root folder to the search path appears to make absolute paths -# work for import-module - lets see how long this works and what surprises -# future developers get from this. -$(call import-add-path,/) -$(call import-module,$(COMP_PATH_MobiCoreClientLib_module)) -$(call import-module,$(COMP_PATH_AndroidProtoBuf)) diff --git a/mobicore/Daemon/NOTICE b/mobicore/Daemon/NOTICE deleted file mode 100644 index 627167a..0000000 --- a/mobicore/Daemon/NOTICE +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ diff --git a/mobicore/Daemon/src/FSD2.cpp b/mobicore/Daemon/src/FSD2.cpp deleted file mode 100644 index 523851e..0000000 --- a/mobicore/Daemon/src/FSD2.cpp +++ /dev/null @@ -1,691 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -/** - * Filesystem v2 delegate. - * - * Handles incoming storage requests from TA through STH - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#undef LOG_TAG -#define LOG_TAG "TeeFilesystem" -#include -#include "tee_client_api.h" /* TEEC_Result */ -#include "MobiCoreDriverApi.h" /* MC session */ -#include "sth2ProxyApi.h" -#include "sfs_error.h" -#include "FSD2.h" - -#define MAX_SECTOR_SIZE 4096 -#define SECTOR_NUM 8 -#define SFS_L2_CACHE_SLOT_SPACE 12 // Hard coded size, cf. sfs_internal.h -#define DEFAULT_WORKSPACE_SIZE (SECTOR_NUM * (MAX_SECTOR_SIZE + SFS_L2_CACHE_SLOT_SPACE)) - -extern const std::string& getTbStoragePath(); - -/*---------------------------------------------------------------------------- - * Utilities functions - *----------------------------------------------------------------------------*/ -static TEEC_Result errno2serror() { - switch (errno) { - case EINVAL: - return S_ERROR_BAD_PARAMETERS; - case EMFILE: - return S_ERROR_NO_MORE_HANDLES; - case ENOENT: - return S_ERROR_ITEM_NOT_FOUND; - case EEXIST: - return S_ERROR_ITEM_EXISTS; - case ENOSPC: - return S_ERROR_STORAGE_NO_SPACE; - case ENOMEM: - return S_ERROR_OUT_OF_MEMORY; - case EBADF: - case EACCES: - default: - return S_ERROR_STORAGE_UNREACHABLE; - } -} - -class Partition { - std::string name_; - FILE* fd_; - off_t size_; -public: - Partition(std::string name): name_(name), fd_(NULL), size_(0) {} - const char* name() const { - return name_.c_str(); - } - off_t size() { - if (size_ == 0) { - struct stat st; - if (::stat(name(), &st)) { - return -1; - } - size_ = st.st_size; - } - return size_; - } - TEEC_Result create() { - LOG_I("%s: Create storage file \"%s\"", __func__, name()); - fd_ = ::fopen(name(), "w+b"); - if (!fd_) { - LOG_E("%s: %s creating storage file \"%s\"", __func__, - strerror(errno), name()); - return errno2serror(); - } - return S_SUCCESS; - } - TEEC_Result destroy() { - if (!fd_) { - /* The partition is not open */ - return S_ERROR_BAD_STATE; - } - - /* Try to erase the file */ - if (::unlink(name())) { - /* File in use or OS didn't allow the operation */ - return errno2serror(); - } - - return S_SUCCESS; - } - TEEC_Result open() { - /* Open the file */ - LOG_I("%s: Open storage file \"%s\"", __func__, name()); - fd_ = ::fopen(name(), "r+b"); - if (!fd_) { - LOG_E("%s: %s opening storage file \"%s\"", __func__, - strerror(errno), name()); - return errno2serror(); - } - LOG_I("%s: storage file \"%s\" successfully open (size: %ld KB / %ld B))", - __func__, name(), size() / 1024, size()); - return S_SUCCESS; - } - TEEC_Result close() { - if (!fd_) { - /* The partition is not open */ - return S_ERROR_BAD_STATE; - } - - ::fclose(fd_); - fd_ = NULL; - - return S_SUCCESS; - } - TEEC_Result read(uint8_t* buf, uint32_t length, uint32_t offset) { - if (!fd_) { - /* The partition is not open */ - return S_ERROR_BAD_STATE; - } - - if (::fseek(fd_, offset, SEEK_SET)) { - LOG_E("%s: fseek error: %s", __func__, strerror(errno)); - return errno2serror(); - } - - if (::fread(buf, length, 1, fd_) != 1) { - if (feof(fd_)) { - LOG_E("%s: fread error: End-Of-File detected", __func__); - return S_ERROR_ITEM_NOT_FOUND; - } - LOG_E("%s: fread error: %s", __func__, strerror(errno)); - return errno2serror(); - } - - return S_SUCCESS; - } - TEEC_Result write(const uint8_t* buf, uint32_t length, uint32_t offset) { - if (!fd_) { - /* The partition is not open */ - return S_ERROR_BAD_STATE; - } - - if (::fseek(fd_, offset, SEEK_SET)) { - LOG_E("%s: fseek error: %s", __func__, strerror(errno)); - return errno2serror(); - } - - if (::fwrite(buf, length, 1, fd_) != 1) { - LOG_E("%s: fwrite error: %s", __func__, strerror(errno)); - return errno2serror(); - } - return S_SUCCESS; - } - TEEC_Result sync() { - if (!fd_) { - /* The partition is not open */ - return S_ERROR_BAD_STATE; - } - - /* - * First make sure that the data in the stdio buffers is flushed to the - * file descriptor - */ - if (::fflush(fd_)) { - return errno2serror(); - } - - /* Then synchronize the file descriptor with the file-system */ - if (::fdatasync(fileno(fd_))) { - return errno2serror(); - } - - return S_SUCCESS; - } - TEEC_Result resize(off_t new_size) { - if (!fd_) { - /* The partition is not open */ - return S_ERROR_BAD_STATE; - } - - if (new_size == size()) { - return S_SUCCESS; - } - - if (new_size > size()) { - /* - * Enlarge the partition file. Make sure we actually write some - * non-zero data into the new sectors. Otherwise, some file-system - * might not really reserve the storage space but use a sparse - * representation. In this case, a subsequent write instruction - * could fail due to out-of-space, which we want to avoid. - */ - if (::fseek(fd_, 0, SEEK_END)) { - LOG_E("%s: fseek error: %s", __func__, strerror(errno)); - return errno2serror(); - } - - off_t count = new_size - size(); - while (count) { - if (::fputc(0xA5, fd_) != 0xA5) { - LOG_E("%s: fputc error: %s", __func__, strerror(errno)); - return errno2serror(); - } - count--; - } - } else { - /* Truncate the partition file */ - if (::ftruncate(fileno(fd_), new_size)) { - return errno2serror(); - } - } - // Update size - size_ = new_size; - return S_SUCCESS; - } -}; - -struct FileSystem::Impl { - pthread_t thread; - - /* - * Communication buffer, includes the workspace - */ - struct { - STH2_delegation_exchange_buffer_t exchange_buffer; - uint8_t workspace[DEFAULT_WORKSPACE_SIZE]; - } dci; - - /* - * Provided by the SWd - */ - uint32_t sector_size; - - /* - * The 16 possible partitions - */ - Partition* partitions[16]; - - // thread value does not matter, only initialised for code checkers - Impl(): thread(pthread_self()) { - ::memset(&dci, 0, sizeof(dci)); - sector_size = 0; - for (int i = 0; i < 16; i++) { - partitions[i] = NULL; - } - } - void run(); - int executeCommand(); - const char* getCommandtypeString(uint32_t nInstructionID); -}; - -FileSystem::FileSystem(): pimpl_(new Impl) {} - -FileSystem::~FileSystem() { - delete pimpl_; -} - -void* FileSystem::run(void* arg) { - FileSystem::Impl* pimpl = static_cast(arg); - pimpl->run(); - return NULL; -} - -int FileSystem::open() { - const std::string storage_dir_name = getTbStoragePath(); - - // Create Tbase storage directory if necessary, parent is assumed to exist - if (::mkdir(storage_dir_name.c_str(), 0700) && (errno != EEXIST)) { - LOG_ERRNO("creating storage folder"); - // Do not return any error and block deamon boot flow or stop FSD thread. - // Just print a "warning/not critical error message". - // Directory could also be created by platform at initialization time. - // return -1; - } - - // Create partitions with default names - for (int i = 0; i < 16; i++) { - char file_name[16]; - snprintf(file_name, sizeof(file_name), "/Store_%1X.tf", i); - pimpl_->partitions[i] = new Partition(storage_dir_name + file_name); - } - - /* Prepare DCI message buffer */ - pimpl_->dci.exchange_buffer.nWorkspaceLength = DEFAULT_WORKSPACE_SIZE; - - // Create listening thread - int ret = pthread_create(&pimpl_->thread, NULL, run, pimpl_); - if (ret) { - LOG_E("pthread_create failed with error code %d", ret); - return -1; - } - - pthread_setname_np(pimpl_->thread, "McDaemon.FileSystem"); - return 0; -} - -int FileSystem::close() { - // Stop listening thread - pthread_kill(pimpl_->thread, SIGUSR1); - pthread_join(pimpl_->thread, NULL); - - /* Clear DCI message buffer */ - ::memset(&pimpl_->dci, 0, sizeof(pimpl_->dci)); - return 0; -} - -/* - * main - */ -void FileSystem::Impl::run() { - // Only accept USR1, to give up - sigset_t sigmask; - sigemptyset(&sigmask); - sigaddset(&sigmask, SIGUSR1); - pthread_sigmask(SIG_UNBLOCK, &sigmask, (sigset_t*)0); - - mcResult_t mc_ret = mcOpenDevice(MC_DEVICE_ID_DEFAULT); - if (MC_DRV_OK != mc_ret) { - LOG_E("%s: mcOpenDevice returned: 0x%08X\n", __func__, mc_ret); - return; - } - - const mcUuid_t uuid = SERVICE_DELEGATION_UUID; - mcSessionHandle_t session_handle; - session_handle.deviceId = MC_DEVICE_ID_DEFAULT; - mc_ret = mcOpenSession(&session_handle, &uuid, reinterpret_cast(&dci), - sizeof(dci)); - if (MC_DRV_OK != mc_ret) { - LOG_E("%s: mcOpenSession returned: 0x%08X\n", __func__, mc_ret); - mcCloseDevice(MC_DEVICE_ID_DEFAULT); - return; - } - - LOG_I("%s: Start listening for request from STH2", __func__); - while (true) { - /* Wait for notification from SWd */ - LOG_D("%s: Waiting for notification\n", __func__); - mc_ret = mcWaitNotification(&session_handle, MC_INFINITE_TIMEOUT_INTERRUPTIBLE); - if (mc_ret != MC_DRV_OK) { - LOG_E("%s: mcWaitNotification failed, error=0x%08X\n", __func__, mc_ret); - break; - } - - /* Read sector size */ - if (sector_size == 0) { - sector_size = dci.exchange_buffer.nSectorSize; - LOG_D("%s: Sector Size: %d bytes", __func__, sector_size); - - /* Check sector size */ - if (!(sector_size == 512 || sector_size == 1024 || - sector_size == 2048 || sector_size == 4096)) { - LOG_E("%s: Incorrect sector size: terminating...", __func__); - break; - } - } - - LOG_D("%s: Received Command from STH2\n", __func__); - if (executeCommand()) { - break; - } - - /* Set "listening" flag before notifying SPT2 */ - dci.exchange_buffer.nDaemonState = STH2_DAEMON_LISTENING; - mc_ret = mcNotify(&session_handle); - if (mc_ret != MC_DRV_OK) { - LOG_E("%s: mcNotify() returned: 0x%08X\n", __func__, mc_ret); - break; - } - } - - mc_ret = mcCloseSession(&session_handle); - if (MC_DRV_OK != mc_ret) { - LOG_E("%s: mcCloseSession returned: 0x%08X\n", __func__, mc_ret); - } - - mc_ret = mcCloseDevice(MC_DEVICE_ID_DEFAULT); - if (MC_DRV_OK != mc_ret) { - LOG_E("%s: mcCloseDevice returned: 0x%08X\n", __func__, mc_ret); - } - - LOG_W("%s: Exiting Filesystem thread", __func__); -} - -/*---------------------------------------------------------------------------- - * Instructions - *----------------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------------- - * Command dispatcher function - *----------------------------------------------------------------------------*/ -/* Debug function to show the command name */ -const char* FileSystem::Impl::getCommandtypeString(uint32_t nInstructionID) { - switch (nInstructionID) { - case DELEGATION_INSTRUCTION_PARTITION_CREATE: - return "PARTITION_CREATE"; - case DELEGATION_INSTRUCTION_PARTITION_OPEN: - return "PARTITION_OPEN"; - case DELEGATION_INSTRUCTION_PARTITION_READ: - return "PARTITION_READ"; - case DELEGATION_INSTRUCTION_PARTITION_WRITE: - return "PARTITION_WRITE"; - case DELEGATION_INSTRUCTION_PARTITION_SET_SIZE: - return "PARTITION_SET_SIZE"; - case DELEGATION_INSTRUCTION_PARTITION_SYNC: - return "PARTITION_SYNC"; - case DELEGATION_INSTRUCTION_PARTITION_CLOSE: - return "PARTITION_CLOSE"; - case DELEGATION_INSTRUCTION_PARTITION_DESTROY: - return "PARTITION_DESTROY"; - case DELEGATION_INSTRUCTION_SHUTDOWN: - return "SHUTDOWN"; - case DELEGATION_INSTRUCTION_NOTIFY: - return "NOTIFY"; - default: - return "UNKNOWN"; - } -} - -int FileSystem::Impl::executeCommand() { - TEEC_Result nError; - uint32_t nInstructionsIndex; - uint32_t nInstructionsBufferSize = - dci.exchange_buffer.nInstructionsBufferSize; - - - LOG_D("%s: nInstructionsBufferSize=%d", __func__, nInstructionsBufferSize); - - /* Reset the operation results */ - nError = TEEC_SUCCESS; - dci.exchange_buffer.sAdministrativeData.nSyncExecuted = 0; - ::memset(dci.exchange_buffer.sAdministrativeData.nPartitionErrorStates, 0, - sizeof(dci.exchange_buffer.sAdministrativeData.nPartitionErrorStates)); - ::memset(dci.exchange_buffer.sAdministrativeData.nPartitionOpenSizes, 0, - sizeof(dci.exchange_buffer.sAdministrativeData.nPartitionOpenSizes)); - - /* Execute the instructions */ - nInstructionsIndex = 0; - while (true) { - DELEGATION_INSTRUCTION* pInstruction; - uint32_t nInstructionID; - pInstruction = (DELEGATION_INSTRUCTION*)( - &dci.exchange_buffer.sInstructions[nInstructionsIndex/4]); - if (nInstructionsIndex + 4 > nInstructionsBufferSize) { - LOG_D("%s: Instruction buffer end, size = %i", __func__, - nInstructionsBufferSize); - return 0; - } - - nInstructionID = pInstruction->sGeneric.nInstructionID; - nInstructionsIndex += 4; - - LOG_D("%s: nInstructionID=0x%02X [%s], nInstructionsIndex=%d", __func__, - nInstructionID, getCommandtypeString(nInstructionID), nInstructionsIndex); - - if ((nInstructionID & 0x0F) == 0) { - /* Partition-independent instruction */ - switch (nInstructionID) { - case DELEGATION_INSTRUCTION_SHUTDOWN: { - return 1; - } - case DELEGATION_INSTRUCTION_NOTIFY: { - /* Parse the instruction parameters */ - wchar_t pMessage[100]; - uint32_t nMessageType; - uint32_t nMessageSize; - ::memset(pMessage, 0, 100*sizeof(wchar_t)); - - if (nInstructionsIndex + 8 > nInstructionsBufferSize) { - return 0; - } - - nMessageType = pInstruction->sNotify.nMessageType; - nMessageSize = pInstruction->sNotify.nMessageSize; - nInstructionsIndex += 8; - if (nMessageSize > (99)*sizeof(wchar_t)) { - /* How to handle the error correctly in this case ? */ - return 0; - } - - if (nInstructionsIndex + nMessageSize > nInstructionsBufferSize) { - return 0; - } - - ::memcpy(pMessage, &pInstruction->sNotify.nMessage[0], nMessageSize); - nInstructionsIndex += nMessageSize; - /* Align the pInstructionsIndex on 4 bytes */ - nInstructionsIndex = (nInstructionsIndex + 3)&~3; - switch (nMessageType) { - case DELEGATION_NOTIFY_TYPE_ERROR: - LOG_E("%s: %ls", __func__, pMessage); - break; - case DELEGATION_NOTIFY_TYPE_WARNING: - LOG_W("%s: %ls", __func__, pMessage); - break; - case DELEGATION_NOTIFY_TYPE_DEBUG: - LOG_D("%s: DEBUG: %ls", __func__, pMessage); - break; - default: - LOG_D("%s: %ls", __func__, pMessage); - } - break; - } - default: { - LOG_E("%s: Unknown instruction identifier: %02X", __func__, nInstructionID); - nError = S_ERROR_BAD_PARAMETERS; - break; - } - } - } else { - /* Partition-specific instruction */ - uint32_t nPartitionID = (nInstructionID & 0xF0) >> 4; - Partition* partition = partitions[nPartitionID]; - if (dci.exchange_buffer.sAdministrativeData.nPartitionErrorStates[nPartitionID] - == S_SUCCESS) { - /* Execute the instruction only if there is currently no error on the partition */ - switch (nInstructionID & 0x0F) { - case DELEGATION_INSTRUCTION_PARTITION_CREATE: { - nError = partition->create(); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nError); - break; - } - case DELEGATION_INSTRUCTION_PARTITION_OPEN: { - nError = partition->open(); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d pSize=%ld err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, partition->size() / sector_size, - nError); - if (nError == S_SUCCESS) { - dci.exchange_buffer.sAdministrativeData.nPartitionOpenSizes[nPartitionID] = - static_cast(partition->size() / sector_size); - } - break; - } - case DELEGATION_INSTRUCTION_PARTITION_READ: { - /* Parse parameters */ - uint32_t nSectorID; - uint32_t nWorkspaceOffset; - if (nInstructionsIndex + 8 > nInstructionsBufferSize) { - return 0; - } - - nSectorID = pInstruction->sReadWrite.nSectorID; - nWorkspaceOffset = pInstruction->sReadWrite.nWorkspaceOffset; - nInstructionsIndex += 8; - LOG_D("%s: >Partition %1X: read sector 0x%08X into workspace at offset 0x%08X", - __func__, nPartitionID, nSectorID, nWorkspaceOffset); - nError = partition->read(dci.exchange_buffer.sWorkspace + nWorkspaceOffset, - sector_size, nSectorID * sector_size); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d sid=%d woff=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nSectorID, nWorkspaceOffset, nError); - break; - } - case DELEGATION_INSTRUCTION_PARTITION_WRITE: { - /* Parse parameters */ - uint32_t nSectorID; - uint32_t nWorkspaceOffset; - if (nInstructionsIndex + 8 > nInstructionsBufferSize) { - return 0; - } - - nSectorID = pInstruction->sReadWrite.nSectorID; - nWorkspaceOffset = pInstruction->sReadWrite.nWorkspaceOffset; - nInstructionsIndex += 8; - LOG_D("%s: >Partition %1X: write sector 0x%X from workspace at offset 0x%X", - __func__, nPartitionID, nSectorID, nWorkspaceOffset); - nError = partition->write(dci.exchange_buffer.sWorkspace + nWorkspaceOffset, - sector_size, nSectorID * sector_size); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d sid=%d woff=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nSectorID, nWorkspaceOffset, nError); - break; - } - case DELEGATION_INSTRUCTION_PARTITION_SYNC: { - nError = partition->sync(); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nError); - if (nError == S_SUCCESS) { - dci.exchange_buffer.sAdministrativeData.nSyncExecuted++; - } - break; - } - case DELEGATION_INSTRUCTION_PARTITION_SET_SIZE: { - // nNewSize is a number of sectors - uint32_t nNewSize; - if (nInstructionsIndex + 4 > nInstructionsBufferSize) { - return 0; - } - - nNewSize = pInstruction->sSetSize.nNewSize; - nInstructionsIndex += 4; - nError = partition->resize(nNewSize * sector_size); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d nNewSize=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nNewSize, nError); - break; - } - case DELEGATION_INSTRUCTION_PARTITION_CLOSE: { - nError = partition->close(); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nError); - break; - } - case DELEGATION_INSTRUCTION_PARTITION_DESTROY: { - nError = partition->destroy(); - LOG_D("%s: INSTRUCTION: ID=0x%x pid=%d err=0x%08X", __func__, - (nInstructionID & 0x0F), nPartitionID, nError); - break; - } - default: { - LOG_E("%s: Unknown instruction identifier: %02X", __func__, nInstructionID); - nError = S_ERROR_BAD_PARAMETERS; - break; - } - } - dci.exchange_buffer.sAdministrativeData.nPartitionErrorStates[nPartitionID] = - nError; - } else { - /* Skip the instruction if there is currently error on the partition */ - switch (nInstructionID & 0x0F) { - case DELEGATION_INSTRUCTION_PARTITION_CREATE: - case DELEGATION_INSTRUCTION_PARTITION_OPEN: - case DELEGATION_INSTRUCTION_PARTITION_SYNC: - case DELEGATION_INSTRUCTION_PARTITION_CLOSE: - case DELEGATION_INSTRUCTION_PARTITION_DESTROY: - break; - case DELEGATION_INSTRUCTION_PARTITION_READ: - case DELEGATION_INSTRUCTION_PARTITION_WRITE: { - if (nInstructionsIndex + 8 > nInstructionsBufferSize) { - return 0; - } - nInstructionsIndex += 8; - break; - } - case DELEGATION_INSTRUCTION_PARTITION_SET_SIZE: { - if (nInstructionsIndex + 4 > nInstructionsBufferSize) { - return 0; - } - nInstructionsIndex += 4; - break; - } - default: { - LOG_E("%s: Unknown instruction identifier: %02X", __func__, nInstructionID); - /* OMS: update partition error with BAD PARAM ? */ - break; - } - } - } - } - } - return 0; -} diff --git a/mobicore/Daemon/src/FSD2.h b/mobicore/Daemon/src/FSD2.h deleted file mode 100644 index bda4c48..0000000 --- a/mobicore/Daemon/src/FSD2.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 FSD2_H_ -#define FSD2_H_ - -class FileSystem { - struct Impl; - Impl* const pimpl_; - // Until we can use std::thread everywhere - static void* run(void* arg); -public: - /** - * Constructor. - */ - FileSystem(); - /** - * Destructor. - */ - ~FileSystem(); - /** - * Ensure resources are available and start main thread. - */ - int open(); - /** - * Stop main thread and free resources. - */ - int close(); -}; - -#endif /* FSD2_H_ */ - diff --git a/mobicore/Daemon/src/MobiCoreDriverCmd.h b/mobicore/Daemon/src/MobiCoreDriverCmd.h deleted file mode 100644 index 06c6e99..0000000 --- a/mobicore/Daemon/src/MobiCoreDriverCmd.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 MOBICORE_REGISTRY_API_H_ -#define MOBICORE_REGISTRY_API_H_ - -#include "mcUuid.h" -#include "mcSpid.h" - -#define SOCK_PATH "#mcdaemon" - -typedef enum { - // Auth token OPS - MC_DRV_REG_READ_AUTH_TOKEN = 0, - MC_DRV_REG_WRITE_AUTH_TOKEN, - MC_DRV_REG_DELETE_AUTH_TOKEN, - // Root container OPS - MC_DRV_REG_READ_ROOT_CONT, - MC_DRV_REG_WRITE_ROOT_CONT, - MC_DRV_REG_DELETE_ROOT_CONT, - // Service Provider Container OPS - MC_DRV_REG_READ_SP_CONT, - MC_DRV_REG_WRITE_SP_CONT, - MC_DRV_REG_DELETE_SP_CONT, - // Trustlet Container OPS - MC_DRV_REG_READ_TL_CONT, - MC_DRV_REG_WRITE_TL_CONT, - MC_DRV_REG_DELETE_TL_CONT, - // Shared Object Data write - MC_DRV_REG_WRITE_SO_DATA, - // TA Blob store - MC_DRV_REG_STORE_TA_BLOB, - // Delete all TA objects - MC_DRV_REG_DELETE_TA_OBJS, - - MC_DRV_REG_END -} mcDrvCmd_t; - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - /* id - free run counter managed by driver, initialized by - * initial_cmd_counter, incremented for each command. - * If difference between current value and value from previous command - * is greater than 1, it means daemon and driver are out of synch. */ - uint32_t id; - uint32_t cmd; - uint32_t data_size; -} CommandHeader; - -typedef struct { - /* id - must be same value as it was in the corresponding command, - * but managed by daemon */ - uint32_t id; - uint32_t result; - uint32_t data_size; -} ResponseHeader; - -typedef struct { - uint32_t len; - uint32_t tl_start_off; - uint8_t value[]; -} regObject_t; - -typedef struct { - mcUuid_t uuid; - mcSpid_t spid; - uint8_t blob[]; -} TlBlob; - -typedef struct { - mcSpid_t spid; - uint8_t blob[]; -} TaBlob; - -#ifdef __cplusplus -} -#endif - -#endif // MOBICORE_REGISTRY_API_H_ diff --git a/mobicore/Daemon/src/MobiCoreDriverDaemon.cpp b/mobicore/Daemon/src/MobiCoreDriverDaemon.cpp deleted file mode 100644 index 9a822a3..0000000 --- a/mobicore/Daemon/src/MobiCoreDriverDaemon.cpp +++ /dev/null @@ -1,608 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include -#include -#include - -#include - -#include "cutils/properties.h" -#include "mcVersion.h" -#include "PrivateRegistry.h" -#include "MobiCoreDriverDaemon.h" -#include "buildTag.h" - -#define DRIVER_TCI_LEN 4096 - -static SecureWorld* g_secure_world; - -//------------------------------------------------------------------------------ -/** - * Print daemon command line options - */ -static -int printUsage(char *path) -{ - fprintf(stderr, " read() on a FD will now return EINTR - */ -const MobiCoreDriverDaemon::cmd_map_item_t -MobiCoreDriverDaemon::reg_cmd_map[] = { - { - &MobiCoreDriverDaemon::reg_read_auth_token, - 0 - }, - { - &MobiCoreDriverDaemon::reg_store_auth_token, - 0 - }, - { - &MobiCoreDriverDaemon::reg_delete_auth_token, - 0 - }, - { - &MobiCoreDriverDaemon::reg_read_root_cont, - 0 - }, - { - &MobiCoreDriverDaemon::reg_store_root_cont, - 0 - }, - { - &MobiCoreDriverDaemon::reg_delete_root_cont, - 0 - }, - { - &MobiCoreDriverDaemon::reg_read_sp_cont, - sizeof(mcSpid_t) - }, - { - &MobiCoreDriverDaemon::reg_store_sp_cont, - sizeof(TaBlob) - }, - { - &MobiCoreDriverDaemon::reg_delete_sp_cont, - sizeof(mcSpid_t) - }, - { - &MobiCoreDriverDaemon::reg_read_tl_cont, - sizeof(TlBlob) - }, - { - &MobiCoreDriverDaemon::reg_store_tl_cont, - sizeof(TlBlob) - }, - { - &MobiCoreDriverDaemon::reg_delete_tl_cont, - sizeof(TlBlob) - }, - { - &MobiCoreDriverDaemon::reg_store_so_data, - 0 - }, - { - &MobiCoreDriverDaemon::reg_store_ta_blob, - sizeof(TaBlob) - }, - { - &MobiCoreDriverDaemon::reg_delete_ta_objs, - sizeof(mcUuid_t) - }, -}; - -static void terminateDaemon(int signum) -{ - LOG_I("Signal %d received", signum); - if ((signum != SIGUSR1) && g_secure_world) { - g_secure_world->stopListening(); - } -} - -MobiCoreDriverDaemon::MobiCoreDriverDaemon(): - m_reg_server(this, SOCK_PATH) -{ -} - -//------------------------------------------------------------------------------ -int MobiCoreDriverDaemon::init(const std::vector& drivers) -{ - sigset_t sigs_to_block; - - if (!m_reg_server.valid()) - return EXIT_FAILURE; - - LOG_D("Initializing Device"); - - /* Set main thread's signal mask to block SIGUSR1. - * All other threads will inherit mask and have it blocked too */ - sigemptyset(&sigs_to_block); - sigaddset(&sigs_to_block, SIGUSR1); - pthread_sigmask(SIG_BLOCK, &sigs_to_block, NULL); - - // Open Secure World access - if (m_secure_world.open() < 0) { - return EXIT_FAILURE; - } - - // Load SW device driver(s), if requested - for (auto driver = drivers.begin(); driver != drivers.end(); driver++) { - // We don't care will loadDriver failed or not... - m_secure_world.loadDriver(driver->c_str()); - } - - // Look for tokens and send it to (&rx_data[0]); - size_t blobSize = rx_data.size() - sizeof(*blob); - return mcRegistryStoreSp(blob->spid, blob->blob, blobSize); -} - -uint32_t MobiCoreDriverDaemon::reg_store_tl_cont( - const std::string& rx_data, std::string&) -{ - auto blob = reinterpret_cast(&rx_data[0]); - size_t blobSize = rx_data.size() - sizeof(*blob); - return mcRegistryStoreTrustletCon(&blob->uuid, blob->spid, blob->blob, blobSize); -} - -uint32_t MobiCoreDriverDaemon::reg_store_so_data( - const std::string& rx_data, std::string&) -{ - return mcRegistryStoreData(&rx_data[0], rx_data.size()); -} - -uint32_t MobiCoreDriverDaemon::reg_store_ta_blob( - const std::string& rx_data, std::string&) -{ - auto blob = reinterpret_cast(&rx_data[0]); - if (rx_data.size() < sizeof(*blob)) { - return MC_DRV_ERR_INVALID_PARAMETER; - } - size_t blobSize = rx_data.size() - sizeof(*blob); - if (m_secure_world.LoadCheck(blob->spid, blob->blob, - static_cast(blobSize)) < 0) { - return MC_DRV_ERR_TRUSTLET_NOT_FOUND; - } - return mcRegistryStoreTABlob(blob->spid, blob->blob, blobSize); -} - -uint32_t MobiCoreDriverDaemon::reg_read_auth_token( - const std::string&, std::string& tx_data) -{ - // Make buffer big enough - tx_data.resize(sizeof(mcSoAuthTokenCont_t)); - return mcRegistryReadAuthToken(reinterpret_cast(&tx_data[0])); -} - -uint32_t MobiCoreDriverDaemon::reg_read_root_cont( - const std::string&, std::string& tx_data) -{ - // Make buffer big enough - tx_data.resize(MAX_DATA_SIZE); - uint32_t size = MAX_DATA_SIZE; - uint32_t ret = mcRegistryReadRoot(&tx_data[0], &size); - if (ret == MC_DRV_OK) { - tx_data.resize(size); - } - return ret; -} - -uint32_t MobiCoreDriverDaemon::reg_read_sp_cont( - const std::string& rx_data, std::string& tx_data) -{ - const mcSpid_t &spid = *reinterpret_cast(&rx_data[0]); - // Make buffer big enough - tx_data.resize(MAX_DATA_SIZE); - uint32_t size = MAX_DATA_SIZE; - uint32_t ret = mcRegistryReadSp(spid, &tx_data[0], &size); - if (ret == MC_DRV_OK) { - tx_data.resize(size); - } - return ret; -} - -uint32_t MobiCoreDriverDaemon::reg_read_tl_cont( - const std::string& rx_data, std::string& tx_data) -{ - auto blob = reinterpret_cast(&rx_data[0]); - // Make buffer big enough - tx_data.resize(MAX_DATA_SIZE); - uint32_t size = MAX_DATA_SIZE; - uint32_t ret = mcRegistryReadTrustletCon(&blob->uuid, blob->spid, &tx_data[0], &size); - if (ret == MC_DRV_OK) { - tx_data.resize(size); - } - return ret; -} - -uint32_t MobiCoreDriverDaemon::reg_delete_auth_token( - const std::string&, std::string&) -{ - return mcRegistryDeleteAuthToken(); -} - -uint32_t MobiCoreDriverDaemon::reg_delete_root_cont( - const std::string&, std::string&) -{ - mcResult_t mcRet = mcRegistryCleanupRoot(); - - // Look for tokens and send it to (&rx_data[0]); - return mcRegistryCleanupSp(spid); -} - -uint32_t MobiCoreDriverDaemon::reg_delete_tl_cont( - const std::string& rx_data, std::string&) -{ - auto blob = reinterpret_cast(&rx_data[0]); - return mcRegistryCleanupTrustlet(&blob->uuid, blob->spid); -} - -uint32_t MobiCoreDriverDaemon::reg_delete_ta_objs( - const std::string& rx_data, std::string&) -{ - const mcUuid_t *uuid = reinterpret_cast(&rx_data[0]); - return mcRegistryCleanupGPTAStorage(uuid); -} - -bool MobiCoreDriverDaemon::handleConnection(Connection &conn) -{ - LOG_D("handleConnection()==== %p", &conn); - - CommandHeader cmd; - switch (conn.readData(&cmd, sizeof(cmd))) { - case sizeof(cmd): - break; - case 0: - LOG_D(" handleConnection(): Connection closed."); - return false; - case -1: - LOG_E("Socket error."); - return false; - case -2: - LOG_E("Timeout."); - return false; - default: - LOG_E("Insufficient data arrived."); - return false; - } - - ResponseHeader result = { 0, MC_DRV_OK, 0 }; - std::string rx_data; - std::string tx_data; - - if (MC_DRV_REG_END > cmd.cmd) { - if (cmd.data_size) { - if (cmd.data_size >= reg_cmd_map[cmd.cmd].min_rx_size) { - rx_data.resize(cmd.data_size); - size_t total = 0; - while (total < rx_data.size()) { - ssize_t sz = conn.readData(&rx_data[total], cmd.data_size - total); - if (sz <= 0) { - LOG_E("Payload reading failed for command %d expected=%zu received=%zd", cmd.cmd, cmd.data_size - total, sz); - result.result = MC_DRV_ERR_UNKNOWN; - break; - } - total += sz; - } - } else { - LOG_E("Invalid payload size for command %d", cmd.cmd); - } - } - - if (result.result == MC_DRV_OK) { - result.result = (this->*(reg_cmd_map[cmd.cmd].handler))(rx_data, tx_data); - } - } else { - LOG_E("Unknown command %d", cmd.cmd); - result.result = MC_DRV_ERR_INVALID_OPERATION; - } - - struct iovec iov[2]; - iov[0].iov_len = sizeof(result); - iov[0].iov_base = const_cast(&result); - int count = 1; - ssize_t write_sz = sizeof(result); - - if ((result.result == MC_DRV_OK) && !tx_data.empty()) { - iov[1].iov_len = tx_data.size(); - iov[1].iov_base = &tx_data[0]; - count++; - write_sz += tx_data.size(); - } - - LOG_D("handleConnection()<-------"); - return conn.writeMsg(iov, count) == write_sz; -} - -int MobiCoreDriverDaemon::run() -{ - LOG_D("run()===="); - - // Start File Storage Daemon and registry server -#ifndef WITHOUT_FSD - m_filesystem.open(); -#endif - m_reg_server.start(); - - /* Exy SP: To let the other daemon which calls TA know - if secureOS daemon is loaded or not */ - LOG_I("McDaemon.Server was loaded"); - property_set("secure_os.init", "done"); - -#ifndef WITHOUT_PROXY - m_proxy_server.open(); -#endif - - g_secure_world = &m_secure_world; - // This call blocks - int ret = m_secure_world.listen(); - -#ifndef WITHOUT_PROXY - m_proxy_server.close(); -#endif - m_reg_server.terminate(); - m_reg_server.kill(SIGUSR1); - m_reg_server.stop(); - m_reg_server.join(); - -#ifndef WITHOUT_FSD - m_filesystem.close(); -#endif - LOG_I("run()<-------"); - - return ret; -} - -//------------------------------------------------------------------------------ -/** - * Main entry of the drivers; - std::vector registry_paths; - - // By default don't fork - bool is_daemon = false; - - while ((c = getopt(argc, args, "r:bhp:")) != -1) { - switch (c) { - case 'h': /* Help */ - errFlag++; - break; - case 'b': /* Fork to background */ - is_daemon = true; - break; - case 'p': /* Search paths for registry */ - registry_paths.push_back(optarg); - LOG_D("registry search path %s added", optarg); - break; - case 'r': /* Load c_str()); - } - - // Open the device before becoming a daemon - MobiCoreDriverDaemon mobiCoreDriverDaemon; - if (mobiCoreDriverDaemon.init(drivers)) { - return EXIT_FAILURE; - } - - // We should fork the daemon to background - if (is_daemon) { - /* ignore "terminal has been closed" signal */ - signal(SIGHUP, SIG_IGN); - - if (daemon(0, 0) < 0) { - fprintf(stderr, "Fork failed, exiting...\n"); - return 1; - } - LOG_D("Daemon's fork was done"); - - /* ignore tty signals */ - signal(SIGTSTP, SIG_IGN); - signal(SIGTTOU, SIG_IGN); - signal(SIGTTIN, SIG_IGN); - } - - // Process signal action - struct sigaction action; - - // Set up the structure to specify the new action. - action.sa_handler = terminateDaemon; - sigemptyset(&action.sa_mask); - - action.sa_flags = 0; - sigaction(SIGINT, &action, NULL); - sigaction(SIGTERM, &action, NULL); - sigaction(SIGUSR1, &action, NULL); - - signal(SIGPIPE, SIG_IGN); - - LOG_I("Daemon starting up..."); - LOG_I("Interface version is %u.%u", DAEMON_VERSION_MAJOR, - DAEMON_VERSION_MINOR); - - LOG_I("%s", MOBICORE_COMPONENT_BUILD_TAG); - LOG_I("Build timestamp is %s %s", __DATE__, __TIME__); - - ret = mobiCoreDriverDaemon.run(); - - LOG_D("Daemon exit with code %d...", ret); - return ret; -} - -void MobiCoreDriverDaemon::installEndorsementToken(void) -{ - /* Look for tokens in the registry and pass them to -#include - -#include "ConnectionHandler.h" -#include "Server.h" -#ifndef WITHOUT_FSD -#include "FSD2.h" -#endif -#include "SecureWorld.h" -#ifndef WITHOUT_PROXY -#include "proxy_server.h" -#endif - -class MobiCoreDriverDaemon: public ConnectionHandler -{ - struct cmd_map_item_t { - uint32_t (MobiCoreDriverDaemon:: *handler)( - const std::string& rx_data, - std::string& tx_data); - uint32_t min_rx_size; - }; - - /** - * installEndorsementToken - * Look for tokens in the registry and pass them to & drivers); - int run (void); -}; - -#endif /* MOBICOREDRIVER_H_ */ diff --git a/mobicore/Daemon/src/Registry.cpp b/mobicore/Daemon/src/Registry.cpp deleted file mode 100644 index ae7b772..0000000 --- a/mobicore/Daemon/src/Registry.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -/** Mobicore Driver Registry Interface - * - * Implements the MobiCore registry interface for the ROOT-PA - * - * @file - * @ingroup MCD_MCDIMPL_DAEMON_REG - */ - -#include -#include -#include -#include -#include "log.h" - -#include "mcSpid.h" -#include "MobiCoreRegistry.h" -#include "MobiCoreDriverCmd.h" -#include "Connection.h" -#include "buildTag.h" - -static const __attribute__((used)) char* buildtag = MOBICORE_COMPONENT_BUILD_TAG; - -#define DAEMON_TIMEOUT 30000 -#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) - -struct cmd_t: public CommandHeader -{ - cmd_t(const uint32_t c) - { - id = 0; - cmd = c; - data_size = 0; - } -}; - -static -mcResult_t check_iov(const struct iovec *iov, size_t iovcnt, size_t *pay_size) -{ - size_t sz = 0; - if(iov == NULL || iov[0].iov_len != sizeof(cmd_t)) - return MC_DRV_ERR_INVALID_PARAMETER; - - for(size_t i = 0; i < iovcnt; i++) { - if(iov[i].iov_base == NULL || iov[i].iov_len == 0) - return MC_DRV_ERR_INVALID_PARAMETER; - sz += iov[i].iov_len; - } - *pay_size = sz - iov[0].iov_len; - return MC_DRV_OK; -} - - -static mcResult_t send_cmd_recv_data(struct iovec *out_iov, - size_t out_iovcnt, void *rbuff = NULL, uint32_t *rlen = NULL) -{ - uint32_t nsegs; - ResponseHeader rsp; - size_t payload_sz; - ssize_t length; - - if( (rbuff == NULL && rlen != NULL) || - (rbuff != NULL && rlen == NULL) || - out_iov == NULL || out_iovcnt == 0) { - LOG_E("Invalid buffer length!"); - return MC_DRV_ERR_INVALID_PARAMETER; - } - - memset(&rsp, 0, sizeof(rsp)); - rsp.result = check_iov(out_iov, out_iovcnt, &payload_sz); - if(rsp.result != MC_DRV_OK) - return rsp.result; - - struct iovec in_iov[2] = { - { &rsp, sizeof(rsp) } - }; - - if(rbuff != NULL) { - nsegs = 2; - in_iov[1].iov_base = rbuff; - in_iov[1].iov_len = *rlen; - } else { - nsegs = 1; - } - - cmd_t &cmd = *static_cast(out_iov[0].iov_base); - cmd.data_size = static_cast(payload_sz); - LOG_D("Sending command %d", cmd.cmd); - - Connection con; - - if (!con.connect(SOCK_PATH)) { - LOG_E("Failed to connect to daemon!"); - return MC_DRV_ERR_DAEMON_SOCKET; - } - - if (con.writeMsg(out_iov, static_cast(out_iovcnt)) <= 0) { - LOG_E("Failed to send data to daemon"); - return MC_DRV_ERR_DAEMON_SOCKET; - } - - length = con.readMsg(in_iov, nsegs, DAEMON_TIMEOUT); - if (length <= 0) { - LOG_E("Failed to get answer from daemon!"); - return MC_DRV_ERR_DAEMON_SOCKET; - } - if (length < (ssize_t)sizeof(ResponseHeader)) { - LOG_E("Invalid length received from daemon!"); - return MC_DRV_ERR_DAEMON_SOCKET; - } - length -= sizeof(ResponseHeader); - - LOG_D("result is %x", rsp.result); - - // Return also the read size - if(rsp.result == MC_DRV_OK && rlen != NULL) - *rlen = length; - - return rsp.result; -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreAuthToken(void *so, uint32_t size) -{ - cmd_t cmd(MC_DRV_REG_WRITE_AUTH_TOKEN); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {so, size} - }; - LOG_D("execute MC_DRV_REG_WRITE_AUTH_TOKEN"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryReadAuthToken(void *so, uint32_t *size) -{ - cmd_t cmd(MC_DRV_REG_READ_AUTH_TOKEN); - struct iovec iov[] = { - {&cmd, sizeof(cmd)} - }; - //__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "%s", MOBICORE_COMPONENT_BUILD_TAG); - LOG_D("execute MC_DRV_REG_READ_AUTH_TOKEN"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov), so, size); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryDeleteAuthToken(void) -{ - cmd_t cmd(MC_DRV_REG_DELETE_AUTH_TOKEN); - struct iovec iov[] = { - {&cmd, sizeof(cmd)} - }; - LOG_D("execute MC_DRV_REG_DELETE_AUTH_TOKEN"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreRoot(void *so, uint32_t size) -{ - cmd_t cmd(MC_DRV_REG_WRITE_ROOT_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {so, size} - }; - LOG_D("execute MC_DRV_REG_WRITE_ROOT_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryReadRoot(void *so, uint32_t *size) -{ - cmd_t cmd(MC_DRV_REG_READ_ROOT_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)} - }; - LOG_D("execute MC_DRV_REG_READ_ROOT_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov), so, size); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryCleanupRoot(void) -{ - cmd_t cmd(MC_DRV_REG_DELETE_ROOT_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)} - }; - LOG_D("execute MC_DRV_REG_DELETE_ROOT_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreSp(mcSpid_t spid, void *so, uint32_t size) -{ - cmd_t cmd(MC_DRV_REG_WRITE_SP_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {&spid, sizeof(spid)}, - {so, size} - }; - LOG_D("execute MC_DRV_REG_WRITE_SP_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryReadSp(mcSpid_t spid, void *so, uint32_t *size) -{ - cmd_t cmd(MC_DRV_REG_READ_SP_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {&spid, sizeof(spid)} - }; - LOG_D("execute MC_DRV_REG_READ_SP_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov), so, size); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryCleanupSp(mcSpid_t spid) -{ - cmd_t cmd(MC_DRV_REG_DELETE_SP_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {&spid, sizeof(spid)}, - }; - LOG_D("execute MC_DRV_REG_DELETE_SP_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, - mcSpid_t spid, void *so, uint32_t size) -{ - cmd_t cmd(MC_DRV_REG_WRITE_TL_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {const_cast(uuid), sizeof(*uuid)}, - {&spid, sizeof(spid)}, - {so, size} - }; - LOG_D("execute MC_DRV_REG_WRITE_TL_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, void *blob, uint32_t size) -{ - cmd_t cmd(MC_DRV_REG_STORE_TA_BLOB); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {&spid, sizeof(spid)}, - {blob, size} - }; - LOG_D("execute MC_DRV_REG_STORE_TA_BLOB"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryReadTrustletCon(const mcUuid_t *uuid, mcSpid_t spid, - void *so, uint32_t *size) -{ - cmd_t cmd(MC_DRV_REG_READ_TL_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {const_cast(uuid), sizeof(*uuid)}, - {&spid, sizeof(spid)} - }; - LOG_D("execute MC_DRV_REG_READ_TL_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov), so, size); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryCleanupTrustlet(const mcUuid_t *uuid, const mcSpid_t spid) -{ - cmd_t cmd(MC_DRV_REG_DELETE_TL_CONT); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {const_cast(uuid), sizeof(*uuid)}, - {const_cast(&spid), sizeof(spid)}, - }; - LOG_D("execute MC_DRV_REG_DELETE_TL_CONT"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryCleanupTA(const mcUuid_t *uuid) -{ - cmd_t cmd(MC_DRV_REG_DELETE_TA_OBJS); - struct iovec iov[] = { - {&cmd, sizeof(cmd)}, - {const_cast(uuid), sizeof(*uuid)}, - }; - LOG_D("execute MC_DRV_REG_DELETE_TA_OBJS"); - return send_cmd_recv_data(iov, ARRAY_SIZE(iov)); -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreData(void *, uint32_t) -{ - return MC_DRV_ERR_INVALID_PARAMETER; -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryReadData(uint32_t, const mcCid_t *, mcPid_t, - mcSoDataCont_t *, uint32_t) -{ - return MC_DRV_ERR_INVALID_PARAMETER; -} diff --git a/mobicore/Daemon/src/SecureWorld.cpp b/mobicore/Daemon/src/SecureWorld.cpp deleted file mode 100644 index de558e7..0000000 --- a/mobicore/Daemon/src/SecureWorld.cpp +++ /dev/null @@ -1,452 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -// Standard -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -// -// Driver -#include "mc_user.h" -#include "mc_admin.h" -// Registry -#include "PrivateRegistry.h" -// Self -#include "SecureWorld.h" - -MC_CHECK_VERSION(MCDRVMODULEAPI, 2, 1); -#define MAX_SO_CONT_SIZE 512 -#define CRASHDUMP_PATH "/sys/kernel/debug/trustonic_tee/crashdump" - -#define MY_LOG_ERRNO(fmt, ...) \ - LOG_E("%s: %s " fmt, __func__, strerror(errno), ##__VA_ARGS__) - -struct SecureWorld::Impl { - int device_fd; - uint32_t command_id; - bool keep_running; - Impl(): device_fd(-1), command_id(0), keep_running(true) {} -}; - -SecureWorld::SecureWorld(): pimpl_(new Impl) {} - -SecureWorld::~SecureWorld() { - delete pimpl_; -} - -static void* getRootContainer(const struct mc_admin_request*, - struct mc_admin_response* response, - bool*) { - void* data = ::malloc(MAX_SO_CONT_SIZE); - uint32_t length = MAX_SO_CONT_SIZE; - - switch (mcRegistryReadRoot(data, &length)) { - case MC_DRV_OK: - response->length = length; - response->error_no = 0; - break; - case MC_DRV_ERR_INVALID_PARAMETER: - response->error_no = EINVAL; - break; - case MC_DRV_ERR_INVALID_DEVICE_FILE: - response->error_no = ENOENT; - break; - default: - // Some kind of default - response->error_no = EPERM; - } - - if (response->error_no) { - ::free(data); - return NULL; - } - - LOG_D("Read root container, size: %u", response->length); - return data; -} - -static void* getSpContainer(const struct mc_admin_request* request, - struct mc_admin_response* response, - bool*) { - void* data = ::malloc(MAX_SO_CONT_SIZE); - uint32_t length = MAX_SO_CONT_SIZE; - - switch (mcRegistryReadSp(request->spid, data, &length)) { - case MC_DRV_OK: - response->length = length; - response->error_no = 0; - break; - case MC_DRV_ERR_INVALID_PARAMETER: - response->error_no = EINVAL; - break; - case MC_DRV_ERR_INVALID_DEVICE_FILE: - response->error_no = ENOENT; - break; - default: - // Some kind of default - response->error_no = EPERM; - } - - if (response->error_no) { - ::free(data); - return NULL; - } - - LOG_D("Read SP container for %u, size: %u", request->spid, response->length); - return data; -} - -static void* getTrustletContainer(const struct mc_admin_request* request, - struct mc_admin_response* response, - bool*) { - void* data = ::malloc(MAX_SO_CONT_SIZE); - uint32_t length = MAX_SO_CONT_SIZE; - - const mcUuid_t* uuid = reinterpret_cast(&request->uuid); - switch (mcRegistryReadTrustletCon(uuid, request->spid, data, &length)) { - case MC_DRV_OK: - response->length = length; - response->error_no = 0; - break; - case MC_DRV_ERR_INVALID_PARAMETER: - response->error_no = EINVAL; - break; - case MC_DRV_ERR_INVALID_DEVICE_FILE: - response->error_no = ENOENT; - break; - case MC_DRV_ERR_OUT_OF_RESOURCES: - response->error_no = ENOMEM; - break; - default: - // Some kind of default - response->error_no = EPERM; - } - - if (response->error_no) { - ::free(data); - return NULL; - } - - LOG_D("Read trustlet container for %u, size: %u", response->spid, response->length); - return data; -} - -static void* mapTrustlet(const char* path, uint32_t* length, - uint32_t* service_type) { - int fd = ::open(path, O_RDONLY); - if (fd < 0) { - LOG_W("Cannot open trustlet %s (%d)", path, errno); - return NULL; - } - - void* data = NULL; - *service_type = SERVICE_TYPE_ILLEGAL; - do { - struct stat stat; - if (::fstat(fd, &stat) < 0) { - MY_LOG_ERRNO("getting size for trustlet %s", path); - break; - } - - data = ::mmap(NULL, stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0); - if (data == MAP_FAILED) { - data = NULL; - MY_LOG_ERRNO("mapping file to memory"); - break; - } - - /* Give service type to driver so it knows how to allocate and copy */ - mclfHeaderV2_t* header = static_cast(data); - *service_type = header->serviceType; - *length = static_cast(stat.st_size); - } while (false); - - ::close(fd); - - return data; -} - -static void* getTrustlet(const struct mc_admin_request* request, - struct mc_admin_response* response, - bool* is_mmapped) { - *is_mmapped = true; - const mcUuid_t* uuid = reinterpret_cast(&request->uuid); - std::string path; - - mcResult_t res = mcRegistryGetTrustletInfo(uuid, request->is_gp, &response->spid, path); - switch (res) { - case MC_DRV_OK: - response->error_no = 0; - break; - case MC_DRV_ERR_INVALID_PARAMETER: - response->error_no = EINVAL; - break; - case MC_DRV_ERR_TRUSTLET_NOT_FOUND: - response->error_no = ENOENT; - break; - default: - // Some kind of default - response->error_no = EPERM; - } - - if (response->error_no) { - return NULL; - } - - void* data = mapTrustlet(path.c_str(), &response->length, - &response->service_type); - if (!data) { - response->error_no = errno; - } else { - LOG_D("Read spid %u and mmap'd trustlet from %s, total size: %u", response->spid, path.c_str(), response->length); - } - return data; -} - -static void* logCrashDump(const struct mc_admin_request*, - struct mc_admin_response* response, - bool*) { - std::ifstream crashdump(CRASHDUMP_PATH); - if (!crashdump.is_open()) { - MY_LOG_ERRNO("opening crash dump"); - response->error_no = errno; - return NULL; - } - - LOG_E("device_fd = ::open("/dev/" MC_ADMIN_DEVNODE, O_RDWR); - if (pimpl_->device_fd < 0) { - MY_LOG_ERRNO("opening admin device"); - return -1; - } - - LOG_D("Check version of device_fd, MC_ADMIN_IO_GET_INFO, &info) != 0) { - LOG_ERRNO("ioctl MC_ADMIN_IO_GET_INFO"); - ::close(pimpl_->device_fd); - return -1; - } - - char *errmsg; - if (!checkVersionOkMCDRVMODULEAPI(info.drv_version, &errmsg)) { - LOG_E("%s", errmsg); - ::close(pimpl_->device_fd); - return -1; - } - - LOG_D("%s", errmsg); - pimpl_->command_id = info.initial_cmd_id; - - // We wait 10 times 100ms for the device file to appear - int counter = 10; - do { - struct stat st; - - int ret = ::stat("/dev/" MC_USER_DEVNODE, &st); - if (!ret) { - break; - } - - if (errno != ENOENT) { - MY_LOG_ERRNO("stat'ing user device"); - return -1; - } - - /* Device driver didn't appear yet: give some time */ - usleep(100000); - } while (counter--); - - if (counter == 0) { - LOG_E("timed out while waiting for user device to appear"); - return -1; - } - - LOG_D("TEE is ready"); - return 0; -} - -void SecureWorld::close() { - ::close(pimpl_->device_fd); -} - -int SecureWorld::loadDriver(const char* path) { - struct mc_admin_load_info info; - uint32_t service_type; - - void* data = mapTrustlet(path, &info.length, &service_type); - if (!data) { - return -1; - } - - LOG_D("Load secure driver %s of size %d", path, info.length); - info.address = reinterpret_cast(data); - info.spid = 0; - - int ret = ioctl(pimpl_->device_fd, MC_ADMIN_IO_LOAD_DRIVER, &info); - if (ret != 0) { - LOG_ERRNO("ioctl MC_ADMIN_IO_LOAD_DRIVER"); - } - - // Free memory occupied by Trustlet data - ::munmap(data, info.length); - return ret == 0; -} - -int SecureWorld::loadToken(const void *data, uint32_t length) { - struct mc_admin_load_info token; - - LOG_D("Load authentication token %p of size %u", data, length); - token.address = reinterpret_cast(data); - token.length = length; - - int rc = ioctl(pimpl_->device_fd, MC_ADMIN_IO_LOAD_TOKEN, &token); - if (rc != 0) { - LOG_ERRNO("ioctl MC_ADMIN_IO_LOAD_TOKEN"); - return -1; - } - - return 0; -} - -int SecureWorld::LoadCheck(mcSpid_t spid, const void *data, uint32_t length) { - struct mc_admin_load_info info; - - LOG_D("Load secure object %p, length %u, spid %x", data, length, spid); - info.spid = spid; - info.address = reinterpret_cast(data); - info.length = length; - - int rc = ioctl(pimpl_->device_fd, MC_ADMIN_IO_LOAD_CHECK, &info); - if (rc != 0) { - LOG_ERRNO("ioctl MC_ADMIN_IO_LOAD_CHECK"); - return -1; - } - - return 0; -} - -int SecureWorld::listen() -{ - int rc = 0; - - while (pimpl_->keep_running) { - struct mc_admin_request request; - - rc = ioctl(pimpl_->device_fd, MC_ADMIN_IO_GET_DRIVER_REQUEST, &request); - if (rc) { - if (errno == EINTR) { - LOG_D("Giving up on signal"); - } else { - LOG_ERRNO("Getting request from driver"); - } - break; - } - - LOG_D("Request %d received (ID %u)", request.command, request.request_id); - if (pimpl_->command_id != request.request_id) { - LOG_E("Request ID counters are not synchronised (expected %u, got %u)", pimpl_->command_id, request.request_id); - break; - } - - struct mc_admin_response response; - memset(&response, 0, sizeof(response)); - response.request_id = pimpl_->command_id++; - void* response_data = NULL; - bool is_mmapped = false; // Response data needs freeing - switch (request.command) { - case MC_DRV_GET_ROOT_CONTAINER: - response_data = getRootContainer(&request, &response, &is_mmapped); - break; - case MC_DRV_GET_SP_CONTAINER: - response_data = getSpContainer(&request, &response, &is_mmapped); - break; - case MC_DRV_GET_TRUSTLET_CONTAINER: - response_data = getTrustletContainer(&request, &response, &is_mmapped); - break; - case MC_DRV_GET_TRUSTLET: - response_data = getTrustlet(&request, &response, &is_mmapped); - break; - case MC_DRV_SIGNAL_CRASH: - logCrashDump(&request, &response, &is_mmapped); - break; - default: - LOG_E("Unknown command"); - response.error_no = EBADRQC; - } - - ssize_t ret = ::write(pimpl_->device_fd, &response, sizeof(response)); - if (ret != sizeof(response)) { - LOG_ERRNO("Sending response to driver"); - ret = -1; - } else if (response.length > 0) { - ssize_t expected_length = response.length; - ret = ::write(pimpl_->device_fd, response_data, response.length); - if (ret != expected_length) { - LOG_ERRNO("Sending response data to driver"); - ret = -1; - } - } - - if (response_data && is_mmapped) { - ::munmap(response_data, response.length); - } else { - ::free(response_data); - } - } - - return rc; -} - -void SecureWorld::stopListening() { - pimpl_->keep_running = false; -} diff --git a/mobicore/Daemon/src/SecureWorld.h b/mobicore/Daemon/src/SecureWorld.h deleted file mode 100644 index b42f521..0000000 --- a/mobicore/Daemon/src/SecureWorld.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 MOBICORE_SECURE_WORLD_H_ -#define MOBICORE_SECURE_WORLD_H_ - -#include - -#include - -class SecureWorld { - struct Impl; - Impl* const pimpl_; -public: - SecureWorld(); - ~SecureWorld(); - int open(); - void close(); - int loadDriver( - const char* path); - int loadToken( - const void* data, - uint32_t length); - int LoadCheck( - mcSpid_t spid, - const void *data, - uint32_t length); - // Does not exit until stopListening() is called - int listen(); - void stopListening(); -}; - -#endif // MOBICORE_SECURE_WORLD_H_ - diff --git a/mobicore/Daemon/src/Server.cpp b/mobicore/Daemon/src/Server.cpp deleted file mode 100644 index c6e8391..0000000 --- a/mobicore/Daemon/src/Server.cpp +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -/** - * Connection server. - * - * Handles incoming socket connections from registry library clients. - */ -#include -#include -#include -#include - -#include "Server.h" - -const char * const Server::m_server_name = "McDaemon.Server"; - -class LockGuard { - pthread_mutex_t* mutex_; -public: - LockGuard(pthread_mutex_t* mutex): mutex_(mutex) { - pthread_mutex_lock(mutex_); - } - ~LockGuard() { - pthread_mutex_unlock(mutex_); - } -}; - -//------------------------------------------------------------------------------ -Server::Server(ConnectionHandler *handler, const char *localAddr, - const int listen_queue_sz) : - m_serverSock(-1), - m_connectionHandler(handler) -{ - // Fill in address structure and bind to socket - struct sockaddr_un serverAddr; - int sock; - - pthread_mutex_init(&m_close_lock, NULL); - if(localAddr == NULL || strlen(localAddr) == 0 || listen_queue_sz <= 0) - return; - - LOG_D("Server: start listening on socket %s", localAddr); - - // Open a socket (a UNIX domain stream socket) - sock = socket(AF_UNIX, SOCK_STREAM, 0); - if (sock < 0) { - LOG_ERRNO("Can't open stream socket, because socket"); - return; - } - - serverAddr.sun_family = AF_UNIX; - strncpy(serverAddr.sun_path, localAddr, sizeof(serverAddr.sun_path) - 1); - - socklen_t len = static_cast(strlen(serverAddr.sun_path) + - sizeof(serverAddr.sun_family)); - // Make the socket in the Abstract Domain(no path but everyone can connect) - serverAddr.sun_path[0] = 0; - - if (bind(sock, reinterpret_cast(&serverAddr), len) == 0) { - if (listen(sock, listen_queue_sz) == 0) { - m_serverSock = sock; - return; - } - else - LOG_ERRNO("listen"); - } else - LOG_ERRNO("Binding to server socket failed, because bind"); - - close(sock); -} - -//------------------------------------------------------------------------------ -void Server::run() -{ - sigset_t sigmask; - sigemptyset(&sigmask); - sigaddset(&sigmask, SIGUSR1); - pthread_sigmask(SIG_UNBLOCK, &sigmask, NULL); - - LOG_D("Server::run()===="); - - while ( valid() && !shouldTerminate() ) { - fd_set fdReadSockets; - - // Clear FD for select() - FD_ZERO(&fdReadSockets); - - LockGuard lock(&m_close_lock); - - // Select server socket descriptor - FD_SET(m_serverSock, &fdReadSockets); - int maxSocketDescriptor = m_serverSock; - - // Select socket descriptor of all connections - for (auto it = m_peerConnections.begin(); it != m_peerConnections.end(); it++) { - auto& conn = *it; - int peerSocket = conn->socket(); - FD_SET(peerSocket, &fdReadSockets); - if (peerSocket > maxSocketDescriptor) - maxSocketDescriptor = peerSocket; - } - - // Wait for activities, select() returns the number of sockets - // which require processing - LOG_D(" Server: waiting on sockets"); - int numSockets = select(maxSocketDescriptor + 1, - &fdReadSockets, NULL, NULL, NULL); - // Check if select failed - if (numSockets < 0) { - int err = errno; - if (err == EINTR) { - LOG_D("Giving up on signal"); - } else { - LOG_ERRNO("select failed"); - } - continue; - } - - // actually, this should not happen. - if (0 == numSockets) { - LOG_W(" Server: select() returned 0, spurious event?."); - continue; - } - - LOG_D(" Server: events on %d socket(s).", numSockets); - - // Check if a new client connected to the server socket - if (FD_ISSET(m_serverSock, &fdReadSockets)) { - LOG_D(" Server: new connection attempt."); - numSockets--; - - int clientSock = ::accept(m_serverSock, NULL, NULL); - if (clientSock > 0) { - Connection *connection = new Connection(clientSock); - m_peerConnections.push_back(connection); - LOG_D(" Server: new socket connection established and start listening."); - } else - LOG_ERRNO("accept"); - - // we can ignore any errors from accepting a new connection. - // If this fail, the client has to deal with it, we are done - // and nothing has changed. - } - - // Handle traffic on existing client connections - auto it = m_peerConnections.begin(); - while ((it != m_peerConnections.end()) && (numSockets > 0)) { - Connection *connection = *it; - - if (!FD_ISSET(connection->socket(), &fdReadSockets)) { - ++it; - continue; - } - - numSockets--; - - // the connection will be terminated if command processing - // fails - if (!m_connectionHandler->handleConnection(*connection)) { - LOG_D(" Server: dropping connection."); - - //Inform the driver - m_connectionHandler->dropConnection(*connection); - - // Remove connection from list - it = m_peerConnections.erase(it); - delete connection; - } else - it++; - } - } - - stop(); - - LOG_D("Exiting Server"); -} - -//------------------------------------------------------------------------------ -Server::~Server() -{ - LOG_D("Destroying Server object"); - stop(); -} - -void Server::stop() -{ - LockGuard lock(&m_close_lock); - - // Destroy all client connections - while(!m_peerConnections.empty()) { - Connection *c = m_peerConnections.front(); - m_peerConnections.pop_front(); - delete c; - } - - // Shut down the server socket - if(m_serverSock != -1) { - close(m_serverSock); - m_serverSock = -1; - } -} diff --git a/mobicore/Daemon/src/buildTag.h b/mobicore/Daemon/src/buildTag.h deleted file mode 100644 index d8a4859..0000000 --- a/mobicore/Daemon/src/buildTag.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 MOBICORE_COMPONENT_BUILD_TAG -#define MOBICORE_COMPONENT_BUILD_TAG \ - "t-base-EXYNOS64-Android-310B-V006-20160331_140301_7136" -#endif diff --git a/mobicore/Daemon/src/drSecureFS_Api.h b/mobicore/Daemon/src/drSecureFS_Api.h deleted file mode 100644 index 4541b36..0000000 --- a/mobicore/Daemon/src/drSecureFS_Api.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -/** - * @file drSecureFS_Api.h - * @brief Contains TCI definitions shared with FSD2 daemon and SPT2 TA - * - */ - -#ifndef __DRSFSAPI_H__ -#define __DRSFSAPI_H__ - -#include "service_delegation_protocol.h" - - -/* - * Driver ID. This is managed by Trustonic - */ -#define DRV_STH2_ID 0x0104 - -/** - * Driver UUID. Update accordingly after reserving UUID - */ -#define DRV_SFS_UUID { { 0x07, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20 } } - -/* - * TCI definitions, relayed by SPT2 TA from FSD2 daemon - */ -#define EXCHANGE_BUFFER_INSTRUCTIONS_NB 1000 - -/** - * This type indicates the state of the daemon - */ -typedef enum { - STH2_DAEMON_LISTENING = 0, - STH2_DAEMON_PROCESSING = 1, -} STH2_daemon_state; - -/** - * TCI message data. - */ -typedef struct { - /* indicates that the secure driver has sent instructions to the normal world daemon. - * This variable is updated in the following ways: - * - Initially set to LISTENING by the daemon before it connects to the secure driver. - * - The secure driver switches the state from LISTENING to PROCESSING when it wants the daemon to process instructions. - * - The daemon switches the state from PROCESSING to LISTENING when it has finished processing the instructions. - */ - STH2_daemon_state nDaemonState; - /* sector size - * set initially by the secure world. - * In TF: `g_nSectorSize`. - */ - uint32_t nSectorSize; - - /* workspace length - * set initially by the daemon. - * In TF: calculated from the exchange buffer size. - */ - uint32_t nWorkspaceLength; - /* administrative data - * written by the normal world. - * In TF: `g_pExchangeBuffer->sAdministrativeData`. - */ - DELEGATION_ADMINISTRATIVE_DATA sAdministrativeData; - /* number of instructions to be executed by the daemon. - * Set by the secure world for each command. - * In TF: the output `size` of `params[1]` - */ - uint32_t nInstructionsBufferSize; - /* instruction list - * set by the secure world. - * In TF: `g_pExchangeBuffer->sInstructions`. - */ - uint32_t sInstructions[EXCHANGE_BUFFER_INSTRUCTIONS_NB]; - /* sectors content, set by either side depending on the instruction. - * The workspace size is hard-coded based on the maximum sector size (4096). - * In TF: `g_pExchangeBuffer->sWorkspace' - */ - uint8_t sWorkspace[]; -} STH2_delegation_exchange_buffer_t; - - -#endif // __DRSFSAPI_H__ diff --git a/mobicore/Daemon/src/mc_admin.h b/mobicore/Daemon/src/mc_admin.h deleted file mode 100644 index 5c9bf1d..0000000 --- a/mobicore/Daemon/src/mc_admin.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_ADMIN_IOCTL_H__ -#define __MC_ADMIN_IOCTL_H__ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MC_ADMIN_DEVNODE "mobicore" - -/* Driver/daemon commands */ -enum { - /* Command 0 is reserved */ - MC_DRV_GET_ROOT_CONTAINER = 1, - MC_DRV_GET_SP_CONTAINER = 2, - MC_DRV_GET_TRUSTLET_CONTAINER = 3, - MC_DRV_GET_TRUSTLET = 4, - MC_DRV_SIGNAL_CRASH = 5, -}; - -/* MobiCore IOCTL magic number */ -#define MC_IOC_MAGIC 'M' - -struct mc_admin_request { - __u32 request_id; /* Unique request identifier */ - __u32 command; /* Command to daemon */ - struct mc_uuid_t uuid; /* UUID of trustlet, if relevant */ - __u32 is_gp; /* Whether trustlet is GP */ - __u32 spid; /* SPID of trustlet, if relevant */ -}; - -struct mc_admin_response { - __u32 request_id; /* Unique request identifier */ - __u32 error_no; /* Errno from daemon */ - __u32 spid; /* SPID of trustlet, if relevant */ - __u32 service_type; /* Type of trustlet being returned */ - __u32 length; /* Length of data to get */ - /* Any data follows */ -}; - -struct mc_admin_driver_info { - /* Version, and something else..*/ - __u32 drv_version; - __u32 initial_cmd_id; -}; - -struct mc_admin_load_info { - __u32 spid; /* SPID of trustlet, if relevant */ - __u64 address; /* Address of the data */ - __u32 length; /* Length of data to get */ -}; - -#define MC_ADMIN_IO_GET_DRIVER_REQUEST \ - _IOR(MC_IOC_MAGIC, 0, struct mc_admin_request) -#define MC_ADMIN_IO_GET_INFO \ - _IOR(MC_IOC_MAGIC, 1, struct mc_admin_driver_info) -#define MC_ADMIN_IO_LOAD_DRIVER \ - _IOW(MC_IOC_MAGIC, 2, struct mc_admin_load_info) -#define MC_ADMIN_IO_LOAD_TOKEN \ - _IOW(MC_IOC_MAGIC, 3, struct mc_admin_load_info) -#define MC_ADMIN_IO_LOAD_CHECK \ - _IOW(MC_IOC_MAGIC, 4, struct mc_admin_load_info) - -#ifdef __cplusplus -} -#endif -#endif /* __MC_ADMIN_IOCTL_H__ */ diff --git a/mobicore/Daemon/src/mc_user.h b/mobicore/Daemon/src/mc_user.h deleted file mode 100644 index e8ac3d6..0000000 --- a/mobicore/Daemon/src/mc_user.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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_USER_H_ -#define _MC_USER_H_ - -#define MCDRVMODULEAPI_VERSION_MAJOR 2 -#define MCDRVMODULEAPI_VERSION_MINOR 10 - -#include - -#define MC_USER_DEVNODE "mobicore-user" - -/** Maximum length of MobiCore product ID string. */ -#define MC_PRODUCT_ID_LEN 64 - -/** Number of buffers that can be mapped at once */ -#define MC_MAP_MAX 4 - -/** Max length for buffers */ -#define BUFFER_LENGTH_MAX 0x100000 - -/** Flags for buffers to map (aligned on GP) */ -#define MC_IO_MAP_INPUT 0x1 -#define MC_IO_MAP_OUTPUT 0x2 -#define MC_IO_MAP_INPUT_OUTPUT (MC_IO_MAP_INPUT | MC_IO_MAP_OUTPUT) - -/* - * Universally Unique Identifier (UUID) according to ISO/IEC 11578. - */ -struct mc_uuid_t { - __u8 value[16]; /* Value of the UUID. */ -}; - -/* - * GP TA login types. - */ -enum mc_login_type { - LOGIN_PUBLIC = 0, - LOGIN_USER, - LOGIN_GROUP, - LOGIN_APPLICATION = 4, - LOGIN_USER_APPLICATION, - LOGIN_GROUP_APPLICATION, -}; - -/* - * GP TA identity structure. - */ -struct mc_identity { - enum mc_login_type login_type; - union { - __u8 login_data[16]; - gid_t gid; /* Requested group id */ - struct { - uid_t euid; - uid_t ruid; - } uid; - }; - pid_t pid; /* Client, when using proxy */ -}; - -/* - * Data exchange structure of the MC_IO_OPEN_SESSION ioctl command. - */ -struct mc_ioctl_open_session { - struct mc_uuid_t uuid; /* trustlet uuid */ - __u32 is_gp_uuid; /* uuid is for GP TA */ - __u32 sid; /* session id (out) */ - __u64 tci; /* tci buffer pointer */ - __u32 tcilen; /* tci length */ - struct mc_identity identity; /* GP TA identity */ -}; - -/* - * Data exchange structure of the MC_IO_OPEN_TRUSTLET ioctl command. - */ -struct mc_ioctl_open_trustlet { - __u32 sid; /* session id (out) */ - __u32 spid; /* trustlet spid */ - __u64 buffer; /* trustlet binary pointer */ - __u32 tlen; /* binary length */ - __u64 tci; /* tci buffer pointer */ - __u32 tcilen; /* tci length */ -}; - -/* - * Data exchange structure of the MC_IO_WAIT ioctl command. - */ -struct mc_ioctl_wait { - __u32 sid; /* session id (in) */ - __s32 timeout; /* notification timeout */ - __u32 partial; /* for proxy server to retry silently */ -}; - -/* - * Data exchange structure of the MC_IO_ALLOC ioctl command. - */ -struct mc_ioctl_alloc { - __u32 len; /* buffer length */ - __u32 handle; /* user handle for the buffer (out) */ -}; - -/* - * Buffer mapping incoming and outgoing information. - */ -struct mc_ioctl_buffer { - __u64 va; /* user space address of buffer */ - __u32 len; /* buffer length */ - __u64 sva; /* SWd virt address of buffer (out) */ - __u32 flags; /* buffer flags */ -}; - -/* - * Data exchange structure of the MC_IO_MAP and MC_IO_UNMAP ioctl commands. - */ -struct mc_ioctl_map { - __u32 sid; /* session id */ - struct mc_ioctl_buffer bufs[MC_MAP_MAX]; /* buffers info */ -}; - -/* - * Data exchange structure of the MC_IO_ERR ioctl command. - */ -struct mc_ioctl_geterr { - __u32 sid; /* session id */ - __s32 value; /* error value (out) */ -}; - -/* - * Global MobiCore Version Information. - */ -struct mc_version_info { - char product_id[MC_PRODUCT_ID_LEN]; /** Product ID string */ - __u32 version_mci; /** Mobicore Control Interface */ - __u32 version_so; /** Secure Objects */ - __u32 version_mclf; /** MobiCore Load Format */ - __u32 version_container; /** MobiCore Container Format */ - __u32 version_mc_config; /** MobiCore Config. Block Format */ - __u32 version_tl_api; /** MobiCore Trustlet API */ - __u32 version_dr_api; /** MobiCore Driver API */ - __u32 version_nwd; /** This Driver */ -}; - -/* - * defines for the ioctl mobicore driver module function call from user space. - */ -/* MobiCore IOCTL magic number */ -#define MC_IOC_MAGIC 'M' - -/* - * Implement corresponding functions from user api - */ -#define MC_IO_OPEN_SESSION \ - _IOWR(MC_IOC_MAGIC, 0, struct mc_ioctl_open_session) -#define MC_IO_OPEN_TRUSTLET \ - _IOWR(MC_IOC_MAGIC, 1, struct mc_ioctl_open_trustlet) -#define MC_IO_CLOSE_SESSION _IO(MC_IOC_MAGIC, 2) -#define MC_IO_NOTIFY _IO(MC_IOC_MAGIC, 3) -#define MC_IO_WAIT _IOW(MC_IOC_MAGIC, 4, struct mc_ioctl_wait) -#define MC_IO_MAP _IOWR(MC_IOC_MAGIC, 5, struct mc_ioctl_map) -#define MC_IO_UNMAP _IOW(MC_IOC_MAGIC, 6, struct mc_ioctl_map) -#define MC_IO_ERR _IOWR(MC_IOC_MAGIC, 7, struct mc_ioctl_geterr) -#define MC_IO_HAS_SESSIONS _IO(MC_IOC_MAGIC, 8) -#define MC_IO_VERSION _IOR(MC_IOC_MAGIC, 9, struct mc_version_info) - -#endif /* _MC_USER_H_ */ diff --git a/mobicore/Daemon/src/service_delegation_protocol.h b/mobicore/Daemon/src/service_delegation_protocol.h deleted file mode 100644 index 123662e..0000000 --- a/mobicore/Daemon/src/service_delegation_protocol.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -/** - * @file service_delegation_protocol.h - * @brief Delegation protocol definitions - * - */ - -#ifndef __SERVICE_DELEGATION_PROTOCOL_H__ -#define __SERVICE_DELEGATION_PROTOCOL_H__ - - - -/* Instruction codes */ -#define DELEGATION_INSTRUCTION_SHUTDOWN 0xF0 -#define DELEGATION_INSTRUCTION_NOTIFY 0xE0 - -/* Partition-specific instruction codes (high-nibble encodes the partition identifier) */ -#define DELEGATION_INSTRUCTION_PARTITION_CREATE 0x01 -#define DELEGATION_INSTRUCTION_PARTITION_OPEN 0x02 -#define DELEGATION_INSTRUCTION_PARTITION_READ 0x03 -#define DELEGATION_INSTRUCTION_PARTITION_WRITE 0x04 -#define DELEGATION_INSTRUCTION_PARTITION_SET_SIZE 0x05 -#define DELEGATION_INSTRUCTION_PARTITION_SYNC 0x06 -#define DELEGATION_INSTRUCTION_PARTITION_CLOSE 0x07 -#define DELEGATION_INSTRUCTION_PARTITION_DESTROY 0x08 - -#define DELEGATION_NOTIFY_TYPE_ERROR 0x000000E1 -#define DELEGATION_NOTIFY_TYPE_WARNING 0x000000E2 -#define DELEGATION_NOTIFY_TYPE_INFO 0x000000E3 -#define DELEGATION_NOTIFY_TYPE_DEBUG 0x000000E4 - -typedef struct -{ - uint32_t nInstructionID; -} DELEGATION_GENERIC_INSTRUCTION; - -typedef struct -{ - uint32_t nInstructionID; - uint32_t nMessageType; - uint32_t nMessageSize; - char nMessage[4]; -} DELEGATION_NOTIFY_INSTRUCTION; - -typedef struct -{ - uint32_t nInstructionID; - uint32_t nSectorID; - uint32_t nWorkspaceOffset; -} DELEGATION_RW_INSTRUCTION; - -typedef struct -{ - uint32_t nInstructionID; - uint32_t nNewSize; -} DELEGATION_SET_SIZE_INSTRUCTION; - -typedef union -{ - DELEGATION_GENERIC_INSTRUCTION sGeneric; - DELEGATION_NOTIFY_INSTRUCTION sNotify; - DELEGATION_RW_INSTRUCTION sReadWrite; - DELEGATION_SET_SIZE_INSTRUCTION sSetSize; -} DELEGATION_INSTRUCTION; - -typedef struct -{ - uint32_t nSyncExecuted; - uint32_t nPartitionErrorStates[16]; - uint32_t nPartitionOpenSizes[16]; -} DELEGATION_ADMINISTRATIVE_DATA; - -#endif /* __SERVICE_DELEGATION_PROTOCOL_H__ */ diff --git a/mobicore/Daemon/src/sfs_error.h b/mobicore/Daemon/src/sfs_error.h deleted file mode 100644 index 090a7ed..0000000 --- a/mobicore/Daemon/src/sfs_error.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -/** - * @file sfs_error.h - * @brief error codes used for levels 0-2 - * - */ - -#ifndef __SFS_ERROR_H__ -#define __SFS_ERROR_H__ - -#include "sfs_type.h" - -#if defined (DRIVER) - -#include "tee_error.h" - -/* Existing TEE codes */ -#define S_SUCCESS TEE_SUCCESS -#define S_ERROR_GENERIC TEE_ERROR_GENERIC -#define S_ERROR_CANCEL TEE_ERROR_CANCEL -#define S_ERROR_ACCESS_CONFLICT TEE_ERROR_ACCESS_CONFLICT -#define S_ERROR_BAD_PARAMETERS TEE_ERROR_BAD_PARAMETERS -#define S_ERROR_BAD_STATE TEE_ERROR_BAD_STATE -#define S_ERROR_ITEM_NOT_FOUND TEE_ERROR_ITEM_NOT_FOUND -#define S_ERROR_NOT_SUPPORTED TEE_ERROR_NOT_SUPPORTED -#define S_ERROR_OUT_OF_MEMORY TEE_ERROR_OUT_OF_MEMORY -#define S_ERROR_COMMUNICATION TEE_ERROR_COMMUNICATION -#define S_ERROR_SHORT_BUFFER TEE_ERROR_SHORT_BUFFER -#define S_ERROR_STORAGE_NO_SPACE TEE_ERROR_STORAGE_NO_SPACE - -/* Implementation-specific errors */ -#define S_ERROR_STORAGE_ITEM_EXISTS ((S_RESULT)TEE_TBASE_ERROR_STORAGE_ITEM_EXISTS) -#define S_ERROR_STORAGE_CORRUPTED ((S_RESULT)TEE_TBASE_ERROR_STORAGE_CORRUPTED) -#define S_ERROR_STORAGE_UNREACHABLE ((S_RESULT)TEE_TBASE_ERROR_STORAGE_UNREACHABLE) -#define S_ERROR_NO_MORE_HANDLES ((S_RESULT)TEE_TBASE_ERROR_NO_MORE_HANDLES) -#define S_ERROR_ITEM_EXISTS ((S_RESULT)TEE_TBASE_ERROR_ITEM_EXISTS) - -#else - -#include "tee_client_error.h" - -/* Existing TEEC codes */ -#define S_SUCCESS TEEC_SUCCESS -#define S_ERROR_GENERIC TEEC_ERROR_GENERIC -#define S_ERROR_CANCEL TEEC_ERROR_CANCEL -#define S_ERROR_ACCESS_CONFLICT TEEC_ERROR_ACCESS_CONFLICT -#define S_ERROR_BAD_PARAMETERS TEEC_ERROR_BAD_PARAMETERS -#define S_ERROR_BAD_STATE TEEC_ERROR_BAD_STATE -#define S_ERROR_ITEM_NOT_FOUND TEEC_ERROR_ITEM_NOT_FOUND -#define S_ERROR_NOT_SUPPORTED TEEC_ERROR_NOT_SUPPORTED -#define S_ERROR_OUT_OF_MEMORY TEEC_ERROR_OUT_OF_MEMORY -#define S_ERROR_COMMUNICATION TEEC_ERROR_COMMUNICATION -#define S_ERROR_SHORT_BUFFER TEEC_ERROR_SHORT_BUFFER -#define S_ERROR_STORAGE_NO_SPACE TEEC_ERROR_STORAGE_NO_SPACE - -/* Implementation-specific errors */ -#define S_ERROR_STORAGE_ITEM_EXISTS ((S_RESULT)TEEC_TBASE_ERROR_STORAGE_ITEM_EXISTS) -#define S_ERROR_STORAGE_CORRUPTED ((S_RESULT)TEEC_TBASE_ERROR_STORAGE_CORRUPTED) -#define S_ERROR_STORAGE_UNREACHABLE ((S_RESULT)TEEC_TBASE_ERROR_STORAGE_UNREACHABLE) -#define S_ERROR_NO_MORE_HANDLES ((S_RESULT)TEEC_TBASE_ERROR_NO_MORE_HANDLES) -#define S_ERROR_ITEM_EXISTS ((S_RESULT)TEEC_TBASE_ERROR_ITEM_EXISTS) - -#endif /* #if defined (DRIVER) */ - - -#endif //__SFS_ERROR_H__ diff --git a/mobicore/Daemon/src/sfs_type.h b/mobicore/Daemon/src/sfs_type.h deleted file mode 100644 index 6bfbfa2..0000000 --- a/mobicore/Daemon/src/sfs_type.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __SFS_TYPES_H__ -#define __SFS_TYPES_H__ - -#if defined (DRIVER) -#include "tee_type.h" -#endif - -/* These definitions are for common port */ -typedef uint32_t S_RESULT; -typedef uint32_t S_HANDLE; -typedef S_HANDLE SM_HANDLE; -#define S_HANDLE_NULL ((S_HANDLE)0) -#define SM_HANDLE_INVALID S_HANDLE_NULL - -/** Definition of an UUID (from RFC 4122 http://www.ietf.org/rfc/rfc4122.txt) */ -typedef struct S_UUID -{ - uint32_t timeLow; - uint16_t timeMid; - uint16_t timeHiAndVersion; - uint8_t clockSeqAndNode[8]; -} S_UUID; - -/* Static SFS configuration */ -typedef struct -{ - - uint32_t nFileSystemCacheSize; /* filesystem.cache.size */ - uint32_t nFileSystemSectorSize; /* filesystem.sector.size */ - uint32_t nFileSystemSizeMax; /* filesystem.size.max in KB */ -} -SYSTEM_STATIC_CFG; - - -extern SYSTEM_STATIC_CFG g_sSystemStaticCfg; - -/** - * Return the difference {p1}-{p2} in bytes - **/ -#define SPointerDiff(p1, p2) ((int32_t)(((uint32_t)p1) - ((uint32_t)p2))) - -/** - * Add an offset of {n} bytes to the pointer {p} - **/ -#define SPointerAdd(p, n) ((void*)(((uint8_t*)(p)) + (int32_t)(n))) - - -#if defined (DRIVER) - #include "DrApi/DrApi.h" - -/* These definitions are for TDriver port */ - #define _SLogTrace(...) drDbgPrintLnf(__VA_ARGS__) - #define SLogTrace(...) drDbgPrintLnf(__VA_ARGS__) - #define SLogError(...) drDbgPrintLnf(__VA_ARGS__) - //#define SLogError(...) drApiPrintLnf(__VA_ARGS__) - #define SLogWarning(...) drDbgPrintLnf(__VA_ARGS__) - #define __INCLUDE_DEBUG - _EXTERN_C _NORETURN void _doAssert( - const char *expr, - const char *file, - const uint32_t line - ); - #define SAssert(cond) \ - do{if (!(cond)){_doAssert(NULL,__FILE__, __LINE__);}} while(FALSE) - - _DRAPI_EXTERN_C _DRAPI_NORETURN void drApiExit(uint32_t exitCode); - #define SPanic(exitCode) drApiExit(exitCode) - - #define SMemAllocEx(param,size) drApiMalloc(size,0) - #define SMemAlloc(size) drApiMalloc(size,0) - #define SMemFree(ptr) drApiFree(ptr) - #define SMemMove(a,b,c) memmove(a,b,c) - #define SMemCompare(a,b,c) memcmp(a,b,c) - #define SMemFill(a,b,c) memset(a,b,c) - #define SMemRealloc(a, b) drApiRealloc(a, b) - - #define setError(...) drDbgPrintLnf(__VA_ARGS__) - #define exosTraceError(...) drDbgPrintLnf(__VA_ARGS__) - - #define Trace(...) drDbgPrintLnf(__VA_ARGS__) - - #define Error(...) drDbgPrintLnf(__VA_ARGS__) - -#elif defined (TEST_SUITE_NAME) -/* These definitions are for Test Suite port */ -/* Olivier, this is your part to update */ - #include - #include -// #include "ssdi.h" - - #ifndef LOG_TAG - #define LOG_TAG "sfs" - #endif - - #include -// #undef LOG_I -// #define LOG_I(fmt, args...) DUMMY_FUNCTION() - - #ifdef NDEBUG - #define LOG(fmt, args...) DUMMY_FUNCTION() - #else - #define LOG(...) \ - (void) fprintf(stdout, __VA_ARGS__); (void) fflush(stdout) - #endif - - #define setError(...) LOG(__VA_ARGS__) - #define Trace(...) LOG(__VA_ARGS__) - -#endif /* #if defined (DRIVER) */ - -#endif //__SFS_TYPES_H__ diff --git a/mobicore/Daemon/src/sth2ProxyApi.h b/mobicore/Daemon/src/sth2ProxyApi.h deleted file mode 100644 index e01240f..0000000 --- a/mobicore/Daemon/src/sth2ProxyApi.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 STH2_PROXY_API_H_ -#define STH2_PROXY_API_H_ - - -#include "drSecureFS_Api.h" - - -/** - * Termination codes - */ -#define EXIT_ERROR ((uint32_t)(-1)) - -/** - * TA UUID. - */ -#define SERVICE_DELEGATION_UUID { { 0x07, 0x05, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20 } } - -#endif // STH2_PROXY_API_H_ diff --git a/mobicore/ClientLib/MODULE_LICENSE_BSD b/mobicore/MODULE_LICENSE_BSD similarity index 100% rename from mobicore/ClientLib/MODULE_LICENSE_BSD rename to mobicore/MODULE_LICENSE_BSD diff --git a/mobicore/NOTICE b/mobicore/NOTICE new file mode 100644 index 0000000..d742e22 --- /dev/null +++ b/mobicore/NOTICE @@ -0,0 +1,25 @@ + 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: + 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. \ No newline at end of file diff --git a/mobicore/README.android b/mobicore/README.android new file mode 100644 index 0000000..29edee1 --- /dev/null +++ b/mobicore/README.android @@ -0,0 +1,64 @@ +MobiCore Daemon in Android +--- +Command line +-- +The MobiCore Daemon supports 4 command line options. It also displays them with the help option: + +# ./mcDriverDaemon -h +usage: ./mcDriverDaemon [-mdsbh] +Start MobiCore Daemon + +-h show this help +-b fork to background +-m IMAGE load mobicore from IMAGE to DDR +-s disable daemon scheduler(default enabled) +-r DRIVER load dyamic driver + +-b Forks the daemon to background + +# ./mcDriverDaemon -b + +Makes the daemon run in background and returns immediate control to the shell. No need to use shell forking with & + +-m Loads a mobicore image to DDR + +# ./mcDriverDaemon -m /data/app/mobicore.img + +Loads the mobicore.img to DDR and starts executing it. + +-s Disables NQ IRQ scheduler + +# ./mcDriverDaemon -s + +-r Loads dynamic driver at startup. The full path of the driver binary must be given, eg. /data/app/driver.drbin + +# ./mcDriverDaemon -r /data/app/driver.drbin + +Custom registry locations +-- +Registry fallback + +In case of a Device wipe in Android the /data/app/mcRegistry folder will be deleted with all it's contents. To overcome +this the daemon supports a fallback location(eg /system/app/mcRegistry): it first tries to load the trustlet +from /data/app/mcRegistry/[uuid].tlbin and if it fails then it tries to read the trustlet from /system/app/mcRegistry/[uuid].tlb + +Both paths are completely configurable for the Daemon using 2 environment variables:MC_REGISTRY_PATH and MC_REGISTRY_FALLBACK_PATH + +For example if you want to use /data/app/mcRegistry as the default path and /system/app/mcRegistry as the fallback path: + +$ export MC_REGISTRY_PATH=/data/app/mcRegistry +$ export MC_REGISTRY_FALLBACK_PATH=/system/app/mcRegistry +$ /data/app/mcDriverDaemon + +Custom authtoken path +-- + +The authtoken file is created at provisioning and is by default located in /data/app/mcRegistry/00000.authtoken + +Because a device wipe could delete this file and make MobiCore unusable a new environment variable has been added to change the +default behaviour: MC_AUTH_TOKEN_PATH + +$ export MC_AUTH_TOKEN_PATH=/efs +$ /data/app/mcDriverDaemon + +This would change the location of the authtoken file to /efs diff --git a/mobicore/TuiService/Android.mk b/mobicore/TuiService/Android.mk deleted file mode 100644 index d1b62b1..0000000 --- a/mobicore/TuiService/Android.mk +++ /dev/null @@ -1,55 +0,0 @@ -# -# build TuiService -# - -# ExySp: Choice TUI availability -#_SUPPORT_TUI := true -ifdef _SUPPORT_TUI -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -# Module name (sets name of output binary / library) -LOCAL_MODULE := libTui - -# Add your source files here (relative paths) -LOCAL_SRC_FILES += \ - jni/tlcTui.cpp \ - jni/tlcTuiJni.cpp - -# Enable logging to logcat per default -LOCAL_CFLAGS += -DLOG_ANDROID -LOCAL_LDLIBS += -llog - -# Undefine NDEBUG to enable LOG_D in log -LOCAL_CFLAGS += -UNDEBUG - -# Needed to use Trustonic logging macros -LOCAL_SHARED_LIBRARIES := libMcClient -LOCAL_ALLOW_UNDEFINED_SYMBOLS := true - -include $(BUILD_SHARED_LIBRARY) - - -include $(CLEAR_VARS) - -LOCAL_SRC_FILES := $(call all-java-files-under, src) -LOCAL_JNI_SHARED_LIBRARIES := libTui - -LOCAL_PACKAGE_NAME := TuiService -LOCAL_MODULE_TAGS := debug eng optional -LOCAL_CERTIFICATE := platform -LOCAL_DEX_PREOPT := false - -LOCAL_PROGUARD_FLAGS := -include $(LOCAL_PATH)/proguard-project.txt - -include $(BUILD_PACKAGE) - -# ============================================================================= - -# adding the root folder to the search path appears to make absolute paths -# work for import-module - lets see how long this works and what surprises -# future developers get from this. -$(call import-add-path,/) -$(call import-module,$(COMP_PATH_MobiCoreClientLib_module)) -endif diff --git a/mobicore/TuiService/AndroidManifest.xml b/mobicore/TuiService/AndroidManifest.xml deleted file mode 100644 index f7de043..0000000 --- a/mobicore/TuiService/AndroidManifest.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mobicore/TuiService/NOTICE b/mobicore/TuiService/NOTICE deleted file mode 100644 index 627167a..0000000 --- a/mobicore/TuiService/NOTICE +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ diff --git a/mobicore/TuiService/ant.properties b/mobicore/TuiService/ant.properties deleted file mode 100644 index 1ac0097..0000000 --- a/mobicore/TuiService/ant.properties +++ /dev/null @@ -1,12 +0,0 @@ -out.dir=out -java.compilerargs="-Xlint:unchecked" - -debug.key.store=google_certificate.keystore -debug.key.alias=platform -debug.key.store.password=android -debug.key.alias.password=android - -key.store=google_certificate.keystore -key.alias=platform -key.store.password=android -key.alias.password=android diff --git a/mobicore/TuiService/build.xml b/mobicore/TuiService/build.xml deleted file mode 100644 index 38cdd9f..0000000 --- a/mobicore/TuiService/build.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/mobicore/TuiService/google_certificate.keystore b/mobicore/TuiService/google_certificate.keystore deleted file mode 100644 index 759f6d2cf6738e0e7e051d9bd4fb76689ded7848..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2549 zcmd6o`9IYA9>-_3Hlndqjv9=y^Rk>yZ~?6S*pjD4qT8*}Uwp&Z7(mL=IjLiQAf zj#T3ykt91=NA7g)x%c*X-1`TdAKs78t~>2tp6=pTXqk zfDRrsvr;?1dw1ffQ^AgoB<32i$OTRU^oayf-ULRwHjBrTqmSVS5`vn zjMs-8Gr4xT9%4oM+KL6tXGDjbSl8sSZj<&S=rJJ(g_1=5HoD|x+vRtmd30tD4ivV@ zb0-0Zce?SmM9Gnzr4ii5+QVt*WU`i>vVz!j;PX4USaj1;)X3q5gY2vb86RNq(!R=3 zD&m4=zNXV9CYF;r3p)cP$i`7**99w`?XvoN!LQSm>B;`tzU~*`3sTOM(QW5@YZ2N{<2czm(2w0HqB@&qdC%!Zfa~xyC+YH zSxGFaYI5S*=kvA@#P!2q>2~xR; z9KzLwiv~uSS%^bbPtzdgk${e^}a2-D4pz$d}P>~UoPEmHS~P{B=bDb*pUra4J3D}t4GZeKzm z;On^lzA#Ao!Nq9IQ>y#t8I7Ih$-26mewy z*JgH_mN4MZ;GyqR{?QmJ;VEDi#Wzc0JHC-9Yw|1$e$v&5i%x&Zr4u?+;M`KA3pp$D zsNE_H?44t~C7jB(B2c!K{xlPao>!7AXj*cbbm}X--nwnO+`E)Fo^NGkP_?}>7-{cy z1?LP6t7<>Rk!SHL%OgMNUV3jU)Oma&A;%l^5KnZf|t%e_AwQFV)0HvMlGLg}8MLs<+lN*9Y(} z3!IVdYK8IM4eSn2V+T^Bf1z5Q7h+FsnbK4e#%OjX5-Sv<3T5uTu6R&Q4$r7l!*?s3 zSFO@#qXGtmb*$obm*gQ4T9^*&+lO)#BX~-%*_B~l*T+#jBC~=Wf!ZCf7i9esD8nf& z6=~YNe%2D!4gyv7qv!pxYcgr(m=e%jKuPGyG5O4}qxodc>w=2qQz~%-Ouyr;_lnjLDK=1(+G2<}d~% z#N1Q{32=N*n2;=5PF@7M$@&nSWViv&?~oCRF!T-f334L%pezWkp)%}r!=-Z;B%`K} zOMoxI<==$$e+cxyL;yhjrv_#)H`3`}cX5BMQqI2Kzy%%zpajUvD9Fmn0}6mO4?>RK z7$Eak`gbjx1V;V%!1NIWC4mw2*#u^SkicM2UKl*124Sc4(@d4?%JT}4kD}fw?*PVn z6i4T^c$Ml8&32&NS%2NhEtCLpaKtct3WHWnCVF8SuOfp5%QD;r^kIL1^)(_`DCgnN zgLcW#a7Q3NJ?PbC;+$u#Sc1IbIpgI$F+EA<23UQ9{h6BIx~oFf-9c^3#~;0|I^Ql) zxerPmne(vs85NH$$vwK?<#Yw{h7S&s6@}*Cz4Zh0xR}1@-Rm&61 zYEPNcIOnExUSAM2YX7W8E?YeqHNzmUt(aOcb`eTWt`tQ!?=7Pc%oW{D1^hVaq*ade zB$aCGJH$(@^m}IY7+N_kBTFOg9kIN<OieqxiVzU3HN+A94<4%2V1qp)#P%!x9M|sfy zA6*_`kfo4u>pPW;fitJQbqnLElYX2aQMJUPk%%{8E$Vf{=c21a7Wt(tx(A&oebR5_ zW=#57-Y0U7(pXfj&ui(z4M~N3q$Y8cURPrCxW4Fm+%DVnnKzQ=u2BN>OLnm5GLy*h z9HsUo5<0q+U&ymqlFuV8W0|kMH&7Vn4Z{d#k` z)uYcz9UgkqS5Z>btbyuVuUnNfpwx#_6S{&@MxQ(GA+rVmHe;oE%B#4=g@s>DQ(NmB aEgKxzFO$zmx@9}>UPas$mlJjjPW>m5U^%w{ diff --git a/mobicore/TuiService/jni/tlcTui.cpp b/mobicore/TuiService/jni/tlcTui.cpp deleted file mode 100644 index 966201e..0000000 --- a/mobicore/TuiService/jni/tlcTui.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -#include -#include -#include -#include -#include /* For SYS_xxx definitions */ -#include -#include -#include -#include -#include - -#include "tui_ioctl.h" - -#include "tlcTui.h" -#include "tlcTuiJni.h" - -#define LOG_TAG "TlcTui" -#include "log.h" - -/* ------------------------------------------------------------- */ -/* Globals */ -bool testGetEvent = false; -/* ------------------------------------------------------------- */ -/* Static */ -static pthread_t threadId; -static int32_t drvFd = -1; - -/* ------------------------------------------------------------- */ -/* Static functions */ -static void *mainThread(void *); - -/* Functions */ -/* ------------------------------------------------------------- */ -/** - * TODO. - */ -static void *mainThread(void *) { -// int32_t fd; -// struct stat st; -// uint32_t size; -// void *address; - uint32_t cmdId; - - LOG_D("mainThread: TlcTui start!"); - -/* Android APP has no right to load a .ko. It must be loaded prior to starting the app. - // Load the k-TLC - fd = open("/data/app/tlckTuiPlay.ko", O_RDONLY); - if (fd < 0) { - LOG_E("mainThread: Could not find k-tlc file!"); - exit(1); - } - else { - fstat(fd, &st); - size = st.st_size; - address = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0); - if (syscall(__NR_init_module, address, size, NULL)) { - int32_t errsv = errno; - LOG_E("mainThread: Load k-tlc failed with errno %s!", strerror(errsv)); - exit(1); - } - close(fd); - } -*/ - drvFd = open("/dev/" TUI_DEV_NAME, O_NONBLOCK); - if (drvFd < 0) { - LOG_E("mainThread: open k-tlc device failed with errno %s.", strerror(errno)); - exit(1); - } - - /* TlcTui main thread loop */ - for (;;) { - /* Wait for a command from the k-TLC*/ - if (false == tlcWaitCmdFromDriver(&cmdId)) { - break; - } - /* Something has been received, process it. */ - if (false == tlcProcessCmd(cmdId)) { - break; - } - } - - // Close - close(drvFd); - - // close_module() ? - return NULL; -} -/* ------------------------------------------------------------- */ -bool tlcLaunch(void) { - - bool ret = false; - /* Create the TlcTui Main thread */ - if (pthread_create(&threadId, NULL, &mainThread, NULL) != 0) { - LOG_E("tlcLaunch: pthread_create failed!"); - ret = false; - } else { - ret = true; - } - - return ret; -} - -/* ------------------------------------------------------------- */ -bool tlcWaitCmdFromDriver(uint32_t *pCmdId) { - uint32_t cmdId = 0; - int ioctlRet = 0; - - /* Wait for ioctl to return from k-tlc with a command ID */ - /* Loop if ioctl has been interrupted. */ - do { - ioctlRet = ioctl(drvFd, TUI_IO_WAITCMD, &cmdId); - } while((EINTR == errno) && (-1 == ioctlRet)); - - if (-1 == ioctlRet) { - LOG_E("TUI_IO_WAITCMD ioctl failed with errno %s.", strerror(errno)); - return false; - } - *pCmdId = cmdId; - return true; -} - -/* ------------------------------------------------------------- */ -bool tlcNotifyEvent(uint32_t eventType) { - - if (-1 == ioctl(drvFd, TUI_IO_NOTIFY, eventType)) { - LOG_E("TUI_IO_NOTIFY ioctl failed with errno %s.", strerror(errno)); - return false; - } - - return true; -} - -/* ------------------------------------------------------------- */ -bool tlcProcessCmd(uint32_t commandId) { - uint32_t ret = TLC_TUI_ERROR; - struct tlc_tui_response_t response; - - bool acknowledge = true; - - switch (commandId) { - case TLC_TUI_CMD_NONE: - LOG_I("tlcProcessCmd: TLC_TUI_CMD_NONE."); - acknowledge = false; - break; - - case TLC_TUI_CMD_START_ACTIVITY: - LOG_D("tlcProcessCmd: TLC_TUI_CMD_START_ACTIVITY."); - ret = tlcStartTuiSession(); - LOG_D("tlcStartTuiSession returned %d", ret); - if (ret == TUI_JNI_OK) { - ret = TLC_TUI_OK; - } else { - ret = TLC_TUI_ERROR; - acknowledge = false; - } - break; - - case TLC_TUI_CMD_STOP_ACTIVITY: - LOG_D("tlcProcessCmd: TLC_TUI_CMD_STOP_ACTIVITY."); - ret = tlcFinishTuiSession(); - LOG_D("tlcFinishTuiSession returned %d", ret); - if (ret == TUI_JNI_OK) { - ret = TLC_TUI_OK; - } else { - ret = TLC_TUI_ERROR; - } - break; - - default: - LOG_E("tlcProcessCmd: Unknown command %d", commandId); - acknowledge = false; - ret = TLC_TUI_ERR_UNKNOWN_CMD; - break; - } - - // Send command return code to the k-tlc - response.id = commandId; - response.return_code = ret; - if (acknowledge) { - if (-1 == ioctl(drvFd, TUI_IO_ACK, &response)) { - LOG_E("TUI_IO_ACK ioctl failed with errno %s.", strerror(errno)); - return false; - } - } - - LOG_D("tlcProcessCmd: ret = %d", ret); - return true; -} - diff --git a/mobicore/TuiService/jni/tlcTui.h b/mobicore/TuiService/jni/tlcTui.h deleted file mode 100644 index 9089ccb..0000000 --- a/mobicore/TuiService/jni/tlcTui.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __TLCTUI_H__ -#define __TLCTUI_H__ - -bool tlcLaunch(void); -bool tlcOpen(void); -bool tlcProcessCmd(uint32_t); -bool tlcWaitCmdFromDriver(uint32_t *); -bool tlcNotifyEvent(uint32_t eventType); -void tlcClose(void); - -#endif /* __TLCTUI_H__ */ - diff --git a/mobicore/TuiService/jni/tlcTuiJni.cpp b/mobicore/TuiService/jni/tlcTuiJni.cpp deleted file mode 100644 index 9cfc81e..0000000 --- a/mobicore/TuiService/jni/tlcTuiJni.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -#include -#include -#include -#include - -#include "tui_ioctl.h" - -#include "tlcTui.h" -#include "tlcTuiJni.h" - -#define LOG_TAG "TlcTuiJni" -#include "log.h" - -/* See for more help about JNI: - * http://java.sun.com/docs/books/jni/html/jniTOC.html - * http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html - * http://developer.android.com/training/articles/perf-jni.html - */ - -#ifdef __cplusplus -#define EXTERN_C extern "C" -#else -#define EXTERN_C -#endif - -JNIEnv *gEnv = NULL; -JavaVM *gVm = NULL; -jclass gTuiTlcWrapperClass = NULL; - -static uint32_t setByteArrayField(const char * field, const void *ptr, - uint32_t length, jclass cls, - jobject instance) { - jfieldID fid = NULL; /* store the field ID */ - jbyteArray bytearray = NULL; - - LOG_D("setByteArrayField: {%s}, length=%u", field, length); - /* Look for the static field in class */ - fid = gEnv->GetFieldID(cls, field, "[B"); - if (fid == NULL) { - LOG_E("setByteArrayField: cannot find field [%s]", field); - return TUI_JNI_ERROR; /* field not found */ - } - bytearray = gEnv->NewByteArray(length); /* TODO : free */ - if (bytearray == NULL) { - LOG_E("setByteArrayField: not enough memory"); - return TUI_JNI_ERROR; /* out of memory */ - } - gEnv->SetByteArrayRegion(bytearray, (jint)0, (jint)length, (jbyte*)ptr); - gEnv->SetObjectField(instance, fid, bytearray); - gEnv->DeleteLocalRef(bytearray); - - return TUI_JNI_OK; -} - -uint32_t tlcStartTuiSession(void) { - - uint32_t nResult = TUI_JNI_ERROR; - jmethodID midStartTuiSession = NULL; - - if (gTuiTlcWrapperClass == NULL) { - LOG_E("tlcStartTuiSession: Missing parameter gTuiTlcWrapperClass"); - nResult = TUI_JNI_ERROR; - goto exit; - } - - /* Attach the thread to the VM */ - if (gVm->AttachCurrentThread(&gEnv, 0) != JNI_OK) { - LOG_E("tlcStartTuiSession: AttachCurrentThread failed"); - return 1; - } - - if (gEnv != NULL) { - /* ------------------------------------------------------------- */ - /* Get the method ID for startTuiSession */ - midStartTuiSession = gEnv->GetStaticMethodID(gTuiTlcWrapperClass, - "startTuiSession", - "()Z"); - if (midStartTuiSession == NULL) { - LOG_E("tlcStartTuiSession: Method startTuiSession not found"); - nResult = TUI_JNI_ERROR; - goto exit; - } - /* Call startTuiSession */ - jboolean success = gEnv->CallStaticBooleanMethod(gTuiTlcWrapperClass, - midStartTuiSession); - /* ------------------------------------------------------------- */ - if (!success) { - LOG_E("tlcStartTuiSession: timeout in activity creation"); - nResult = TUI_JNI_ERROR; - goto exit; - } - nResult = TUI_JNI_OK; - } else { - LOG_E("tlcStartTuiSession: gEnv is null!"); - nResult = TUI_JNI_ERROR; - goto exit; - } - - exit: if (gEnv != NULL) { - if (gEnv->ExceptionCheck()) { - LOG_E("tlcStartTuiSession: Java exception"); - gEnv->ExceptionClear(); - } - } else { - LOG_E("tlcStartTuiSession: exit gEnv is NULL"); - } - - if (gVm->DetachCurrentThread() != 0) { - LOG_E("tlcStartTuiSession: DetachCurrentThread failed"); - } - return nResult; -} - -uint32_t tlcFinishTuiSession(void) { - - uint32_t nResult = TUI_JNI_ERROR; - jmethodID midFinishTuiSession = NULL; - - if (gTuiTlcWrapperClass == NULL) { - LOG_E("tlcFinishTuiSession: Missing parameter gTuiTlcWrapperClass"); - nResult = TUI_JNI_ERROR; - goto exit; - } - - /* Attach the thread to the VM */ - if (gVm->AttachCurrentThread(&gEnv, 0) != JNI_OK) { - LOG_E("tlcFinishTuiSession: AttachCurrentThread failed"); - return 1; - } - - if (gEnv != NULL) { - /* ------------------------------------------------------------- */ - /* Get the method ID for finishTuiSession */ - midFinishTuiSession = gEnv->GetStaticMethodID(gTuiTlcWrapperClass, - "finishTuiSession", - "()V"); - if (midFinishTuiSession == NULL) { - LOG_E("tlcFinishTuiSession: Method finishTuiSession not found"); - nResult = TUI_JNI_ERROR; - goto exit; - } - /* Call finishTuiSession */ - gEnv->CallStaticVoidMethod(gTuiTlcWrapperClass, midFinishTuiSession); - /* ------------------------------------------------------------- */ - nResult = TUI_JNI_OK; - } else { - LOG_E("tlcFinishTuiSession: gEnv is null!"); - nResult = TUI_JNI_ERROR; - goto exit; - } - - exit: if (gEnv != NULL) { - if (gEnv->ExceptionCheck()) { - LOG_E("tlcFinishTuiSession: Java exception"); - gEnv->ExceptionClear(); - } - } else { - LOG_E("tlcFinishTuiSession: exit gEnv is NULL"); - } - - if (gVm->DetachCurrentThread() != 0) { - LOG_E("tlcFinishTuiSession: DetachCurrentThread failed"); - } - - return nResult; -} - - -EXTERN_C JNIEXPORT bool JNICALL -Java_com_trustonic_tuiservice_TuiTlcWrapper_startTlcTui(JNIEnv *env, - jobject obj) { - (void) env; - (void) obj; - bool ret = false; - - LOG_D("calling tlcLaunch()"); - ret = tlcLaunch(); - if(!ret) { - LOG_E("tlcLaunch: failed to start TlcTui!"); - } - - return ret; -} - -EXTERN_C JNIEXPORT bool JNICALL -Java_com_trustonic_tuiservice_TuiTlcWrapper_notifyEvent(JNIEnv *env, - jobject obj, jint eventType) { - (void) env; - (void) obj; - bool ret = false; - - LOG_D("calling tlcNotifyEvent()"); - ret = tlcNotifyEvent(eventType); - if (!ret) { - LOG_E("tlcNotifyEvent: failed to notify an event!"); - } - - return ret; -} - -jint JNI_OnLoad(JavaVM *vm, void *reserved) { - (void) reserved; - JNIEnv *env = NULL; - jclass TuiTlcWrapperClass = NULL; - - LOG_D("JNI_OnLoad"); - - if (vm->GetEnv((void **)&env, JNI_VERSION_1_6) != JNI_OK) { - LOG_E("JNI_OnLoad: GetEnv failed!"); - return -1; - } - - TuiTlcWrapperClass = env->FindClass( - "com/trustonic/tuiservice/TuiTlcWrapper"); - if (TuiTlcWrapperClass == NULL) { - LOG_E("JNI_OnLoad: FindClass on class TuiTlcWrapperClass failed!"); - return -1; - } - - LOG_D("JNI_OnLoad: TuiTlcWrapperClass = %p", TuiTlcWrapperClass); - - /* Cache the TlcTuiWrapper class in a global reference */ - /* Use the cached gTuiTlcWrapperClass. - * As we called the AttachCurrentThread to get the java environnement from - * a native thread, the FindClass will always fail. This is a ClassLoader issue. - * This call (AttachCurrentThread) changes the call stack, so when the FindClass - * try to start the class search in the class loader associated with this method, - * FindClass find the ClassLoader associated with the a wrong class, so FindClass fails.*/ - gTuiTlcWrapperClass = (jclass)env->NewGlobalRef(TuiTlcWrapperClass); - - /* Cache the javaVM to get back a JNIEnv reference from native code*/ - gVm = vm; - LOG_D("JNI_OnLoad: gVm = %p vm = %p", gVm, vm); - - return JNI_VERSION_1_6; -} - diff --git a/mobicore/TuiService/jni/tlcTuiJni.h b/mobicore/TuiService/jni/tlcTuiJni.h deleted file mode 100644 index 40d2e4a..0000000 --- a/mobicore/TuiService/jni/tlcTuiJni.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 __TLCTUIJNI_H__ -#define __TLCTUIJNI_H__ - -#define TUI_JNI_OK 0 -#define TUI_JNI_ERROR 1 -#define TUI_JNI_ERROR_IN_JAVA 2 - -uint32_t tlcStartTuiSession(void); -uint32_t tlcFinishTuiSession(void); - -#endif /* __TLCTUIJNI_H__ */ diff --git a/mobicore/TuiService/jni/tui_ioctl.h b/mobicore/TuiService/jni/tui_ioctl.h deleted file mode 100644 index 3643541..0000000 --- a/mobicore/TuiService/jni/tui_ioctl.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 TUI_IOCTL_H_ -#define TUI_IOCTL_H_ - - - -/* Response header */ -struct tlc_tui_response_t { - uint32_t id; - uint32_t return_code; -}; - -/* Command IDs */ -#define TLC_TUI_CMD_NONE 0 -#define TLC_TUI_CMD_START_ACTIVITY 1 -#define TLC_TUI_CMD_STOP_ACTIVITY 2 - -/* Return codes */ -#define TLC_TUI_OK 0 -#define TLC_TUI_ERROR 1 -#define TLC_TUI_ERR_UNKNOWN_CMD 2 - - -/* - * defines for the ioctl TUI driver module function call from user space. - */ -#define TUI_DEV_NAME "t-base-tui" - -#define TUI_IO_MAGIC 't' - -#define TUI_IO_NOTIFY _IOW(TUI_IO_MAGIC, 1, uint32_t) -#define TUI_IO_WAITCMD _IOR(TUI_IO_MAGIC, 2, uint32_t) -#define TUI_IO_ACK _IOW(TUI_IO_MAGIC, 3, struct tlc_tui_response_t) - -#ifdef INIT_COMPLETION -#define reinit_completion(x) INIT_COMPLETION(*(x)) -#endif - -#endif /* TUI_IOCTL_H_ */ diff --git a/mobicore/TuiService/proguard-project.txt b/mobicore/TuiService/proguard-project.txt deleted file mode 100644 index f2fe155..0000000 --- a/mobicore/TuiService/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/mobicore/TuiService/project.properties b/mobicore/TuiService/project.properties deleted file mode 100644 index 4ab1256..0000000 --- a/mobicore/TuiService/project.properties +++ /dev/null @@ -1,14 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-19 diff --git a/mobicore/TuiService/res/drawable-hdpi/sym_def_app_icon.png b/mobicore/TuiService/res/drawable-hdpi/sym_def_app_icon.png deleted file mode 100644 index 96a442e5b8e9394ccf50bab9988cb2316026245d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9397 zcmV;mBud+fP)L`9r|n3#ts(U@pVoQ)(ZPc(6i z8k}N`MvWQ78F(rhG(?6FnFXYo>28{yZ}%O}TvdDT_5P?j=iW=V`8=UNc_}`JbG!ST zs@lK(TWkH+P**sB$A`cEY%Y53cQ}1&6`x-M$Cz&{o9bLU^M-%^mY?+vedlvt$RT-^ zu|w7}IaWaljBq#|I%Mpo!Wc2bbZF3KF9|D%wZe{YFM=hJAv$>j>nhx`=Wis#KG!cJA5x!4)f) zezMz1?Vn$GnZNjbFXH(pK83nn!^3=+^*kTTs5rV9Dq^XS(IKO!mKt5!dSmb3IVCxZ z8TTk5IE)F1V29$G7v#j9d-hy&_pdg8?kT4)zqr>?`}I%W>(?GO%*C&}?Fp|bI*~2&KZ$%^B6R&1~2kA{`CWy+>F-x=z-f{_&vyu_3yp{jtw(*syi% zu3t2|4{c~LJXRt2m>rMg2V_kLltCZ<`m>qcI?BPP?6hf``|e!rZEFszeYQ3f-*nAS zZ+h1$mFwy+7156lkB(k6)!1fUbJCxgIBK38$jj5cC$r&YXN)nr#PY=tJaLc?C_o?j+8H3Q>891JJ9&$l-r+-SG#q)*;r52% z@nlKflb65o%s*Jt)!pw1k{vIoQIvoJ0Y&Msiw0X!qJ)_47G*?aJ6bJFLh_4b$5&1k5wN>du*>6#i7R9T8; z7>EHOV=ue7mo77SJPwER4(A+s?n0JjYK)b}Om6n>ke?0JR=jTI+RFBg_iwb7k%n*2 zR_M0DJ9x+0zxba4(B1y^JQ_Nj6dlP5PGXvSq8fF#mxrFYj3d9(V#jJwt+IqU9+8+D z6C6Us1OI$d8OF!3+Hm1 zW5in zXV^%U35HooOpSmeqlG6e0kUMYNonKp1vr|My9}4-WO+uOxe_c-o&}%voNYHkqtle% z5yQ_^oozSUUNu30EQSAl!Q%(%3G1NXENSMjCL*Vx-Td2~rk(}d z8pT!HZe>1r5EGuz`pgsg@^yQEi=BIa#meLq0!?{TZ}q#}=7UC9_l=w|wv+pP!g4#! zRys6EN$Jv}#U47$k&)pDzvks}LGfPku6P9p!56Py)~1)W(11n7n}`Wx!=;_JTiu#d zpCqx=hEk@t4sp?!j{W}wP@V-=Pd=T^>6IKBy;#mLA7hCe{V7B3@I7Ipa}L`MbF|YQ z)$BNWsiEnoNHrtJli|n8cOnn4NyF=8MbVxgof0>Uv%wM_j94a;8(LMjlL~E(99gJ*2%JtNtAkD@j;^ za~Y~&j6uY{=Rv5S4joH*RW_m9N{ZSN0HhAwFyJNok zS9kx$>wMf%tUi&Eb`6u0lWJ|k?A-42(lp2UmS(PrAc(24wexRiHUieMwf$o%m6$xs zp#-SdBUu2D5`v;(9-sm&kN2M74c&AvKe_v@tQ|dzJ2qSgQHpnUP(iQ?J%Il;Jdyp# z7}cpq6Kdm+FS~zS4Eo;fuO=DFP*UlpO|_CNt5&NUqBvQWxmg7#ARvMf=%#H@p%RZ` zjK$hMbNb+vVP3UlkfIt&ptJ<00Ic{Ka+lF+&w;OEs1O2#V8~O|R*Gq9TIgM&UqM&bZOXBwnbC? zDr))NR&g>lwVgcmnx`K1$)PTTw3m}-T11^ZkY{}jQ@lGD$XzJIcVFkYBBW=o_}TUU zt@yd{Jz;@~72x#!RG(#ira6}v-*J#<{@@^OI-Q2T^}=IKLubsa&V-%WwlF1s7fz~u zMdQTV7SnRet#^`VO0V7H(?59X{uy+S`(sorO@2-+qioUdo9+6r4#|jb=?t50oh42R z{}I>Krut|YKkOc|O|M>y#(3YA;I(i+MiHSfwbJA$jIUr$Y2i|u)*>@2eUYk`j4C5r z>61dKu!AqM_E7#DoDzbd-bfT%AYXUUB{SS|{b{`5^?wz1{PVQgTlvyqOX8(#GTz(U zNPhnj>$lC`xaD56`TjW&uW8p~qikP*F8kHFM0frzdk%UNGjb1O$%uLK`0-)2UsZ3L z#+j+CI_8k4VslL%$aVR@joX>M-@odbX!os$xY$HDIOCokY?{Q0v2kQErf|ZlN>D9w zC+2}E&?rDdi#%))$p%P4C_xGXu=@U~_<|V4L|{>TP$XBp$5pCPXLzK3!;gP>7=QNi zkNOur`>xY=@VSpB#LsN9JKpOz({ANcdv>?K+D_*_HZ<;9>kplj^Ph5!e&&a#?(3vK z_Q@}D_M5kGcx^AuaI~qKYUnb1Mj-n;MURXa)+x7~e2gbMW|gw?5Rg zTOMlo>6zIJ$VNVgn(@kTSL0eP)nR35IHpoHM2W#h6cNmTm@-9`dFJ$;k(S`7Lg@RY zp!hNmb9un!O4Wt05ANDGirv(B14gW| zwjP}C9bK{J`qZ_S2o)b`RonR-b8~y8)$H0`+gg6>#^wu8eCp9xA9B>>8(KRizI?+^ zAJ#i>*({qM-c4gBB~5dzg(wj!HA`hkh!aDl5>u&J;>2K#Ax2)2wt|L!9X;(=*jy!`r4_FhCBoRxNjXNv(~jGQ|%<}%K6RimaBJcP0v}oCgRN3B;oiM)opj? zXm;;tv3q-yy}NqMOr^~3&1lW$w3}UK_IT2sCrkYx5$&6e2A%g;QZUX~A&L!2rFd0p z5%men@^zN_Xw2|v%*c2|wQfkN4r6u&k;LxYY+w3{KY#cie)!iz>(yAgt=&-+Sy2V& z9BJxI+VMKQ%dvY~x>gmEijj3ss_*NAT(8d1@DQ6e&#Ln&6Qk>wHrh>;V2nvomC`8& z(w?`?*_^3u-TJrMzv2~7dH(XLJvUOXk4U8oW6Ol)YsawhIB{GdvIzu1hzMTrE)cvB z%2GxMpaF89<9uF(?cfN(BNR?wwWvCZ6e62+G_{$+;`yjgLj{(^z*zzwd;K3RElb*%=??P zm+lLY0@Y}^kVdMYX5M)YJ~8h=i(S{q#NfU0xPTao4WPDQL=Y_;vg=p%iay1_`<0Ga zMG&<(pOU+bI2u9_g8IJBTqGX*3@G$Zc`pj0f@)vd2?Aj`ms>DHg>;w~p}HXV(*VJX zphd;fht9qL3E)D8h$$A;SGl22Ygv>`iU=A)z=1ZYN$|2`*$`R)?KD>$tw_e9h_x~eX_udS~Q%yz?48i*aIa+_wx|j{B zsG7mwZ)6M3dmvgMC3K-66;ML(9o2xU!F8+qF)>v{1;ip)6v_I)6law|rd_Dx2oV|n z(Qm_PUnTTuKFG)w%s|)lS!w~Lm$k|Al=0djocyHU;>1H=!N}0E0lSV^b2^6~^lUco zyoH+|_!li3#euHd4TJS8=CLaHG9H8g&h3Xm z#>BkpUBAmae(#)qO3)ZMG3irM=5IzA^s+)w86=tIMT{&?Awux<(k2>U#n`c&@Z?u= z%=#BoO-9Nc^?)hz*YW~~tU8rLR-MZBJsY_7fp2r~mY>q-O;L%5Fp?}V6CK=F(18U3 znxB8ZR0TT{)T64RDt!+yFgp!JXGP0|It0Hz2Em#YfRv>O>8A?J=Sz!nq<|{&mW=?~ zDQT{S6PH0|jwy37t+0Ob6izz)JdRlNEUbyk>-K?}FOT=Dj9SuS_0nTFd+A^D?Bo83 zTkicXcW=IuZoZd(Dl;&#`LI;_s?e;OH9quf?*XuV0O$Qh0j~HWKpA|PXV4&b2zs z@W5<)dtovIRZ@gvsi$^s;v05(XwF3$lJ;wzYfE`46fnT7>!qt|hWHRE>yQP)i8= zVbC|O{Ud6%kwGcch>>|pE-=?cW;TDR0lE5Nw7l66lr-zIYT3bj^ujCn$b0{ZO;gwK z#}}W(*T3~in$6ZCpbB98pftPTo;!K>U;H*7_}t4m;;4i9#^2t`pS<=jsnx198);d3 z-M6Mx{7-c0A-jhJQ`5mBy8TBnfbr2~sER5E5oz}=so34cg)GYarRWi8w#W$%G{?Z*4xDb#LX1B1 zg!4G{m~*)H_J8J^SNt`XU-fxjea`>p_$Qyn*Dn18*WdPCp8oWw^XU)%kfRQHMgfQh z1j_ua@O4G%QK;&YH3Y9(q!hkgOUCkcVH5N0Ug(EPX%H6qCfPqg))qrd#ec^47dBu- z=sRkmjGS>3K(tfRTo;zCXO-74hV;y1!vCN}v|w?AWR$YpYXs@Dr?iNLKD9s|2)0aHY!TKTYhwMI z7b#54h!H6rUU9+xnL$g6h?t?Li5guXPY1g)$bI$~rHWP%QkYJ6Y-U^0C(@*$ruN2*zn0QRBOeVpgMFbT%k!Dn1*u#%J^y)enX1K;0~ z%3Q zP(b%}P!Loj6M{v96(Qa~K!bq-V-P89U_K)0zHC_F#L==3IPh2hHG6&?rxvQ%|EljR zfGIDyu=rIrl1dyjuMfwuh?pXZmARwNZ?GbW;5BH5D#nN|WbGm+UGAh7_AcG>4&|{0 zrg?k@h8zm!0A|5Zo%X%g|2tBPKHHB6`~4h?I@bepDe6?^f8w zBnzfOf|j{kR5m6BLRr0$!RZ$PHSk*)tyjkws*DpyHIiiL*8o(Smx(OKT7@D&Y3OI^ zEUMtKa2*SLjt(eJsZsLsrgV`A+xL(~JN#JU6+L)gCe%VuSNbCzTr09w>eZ#779SKV z)m)@#TNVy|q3Tz_U`^7MY`l}`GU~OlQi|*cprX?tm@tIV+8kOGkaa=9Y<{N|RZ)ns zHlgnz2S%qwK9wXjest~Ux$YNNA{0?6Xpv{_mqYt8D`g&7Yb~>lX+HP&AK<=+Zl_kO z6a2g`^4=9W92GQ3e9Mk6?DlzlkIM`iOzwk*5L81TcuyYkI-<3^@49_+^XC7&N}SL1 zh$kIBxb`9+v}acfV?FQ zN#04eHe0*j{pz=zOj3#EHLrT3e)O;3xqpCWrl$e)PcD9jQ4P-8_zyZg^M7i|*kOuj znsvlwNUsy5+01^P_sqMOjXjxKwHn4)$87t-MWZZ*5Dbit4|D9vL+spsJ0JPd?{Ms) zFW^<@yqjZ=IvG%$ck_Cu9|b8CvoV%5P5IZWzs>i4`~`N+-p`7a6RbLHJ;nxtSB#Mb z`1I552=9DrYWFNZ{-=Mt;SVo5@3cmv`IZT@@>#~zCe-=qENxsn+uHfL`e?SbT3IQ_ zt~e)Lcirs_S5^X#?hDYmgV%8QQDe+?>*1&0e^BnaeZz(&D~3<)#QuUL8h*NlXgtr| z&a{_Z)o9FK_U5<0!E3N|yY1P2g%J9s*?!zF78+NSb%!ix)tbQ09oO&|U$~Bwk35^- zec9VN^xz{043e^xD}WEmzh8d^-~Pd8**bEfd+I?HuO~n4SksoN8LRPUy={E<@BjRMUh?X71Xaey>t^$&Eq2B7)u_r$ z|IQwpG52G!F$J5fRo1LqLB7iKz_!bI@27skX~+Eze|Y}IBuRp?hR7z|eA~7B<99#7 zrX4r2a_tCDUb_}Cg)g!OEVeJ5AEVRyb!9~f4OL68qhZZRP0l*>MdkxvxXeGWx$T>+ zI^X!wnYQDnwK9?i)j)eLXJU2Cw>~>R?72@MecvT7;h~2gATow_cbc)$Ws+xNSB{++ zo^tTp^y*(-Y-XF=$XyoBJnMN9+p!Qrep1)%ym_v7zZH{;u~L>T=4XP!f^?uC4ULUR zdl`>x+DVkHVd;|9#N*oubBFQEyRT#UK^0c7T}l)eEEFS)qvZl%f>#I;iCwAWb=kW0 z(e#lm51o?d>D|kgtTscVQCNDAXMAjxSX&{_Qf)T((wMHWWLbz6WpPXP0(3_SBWwI19Vx?$i6WUqP$4O|wjNbYzst$z{58`cBhm z&F(N-KeXFzo#aC|6BbC($As#B8X=}ggpDyQUp|Q>9cG$47#>TQn%T(eHA`5se7KnZ zF_dj_6NN0xS-oZ%Nj%PTpK=MC zw*4IMGls_v)mokI)Dph*pD<)7prEF|j6I$2=XF=Ua3z;BN^yt&H@G%7& zWnL7*e0S9svjSP>kuc;VCbZXUN3G7D8`G@!Qnjt=p=7yC?QH0tsa@RsuPMLj@wf-c z|LV)H$Auga+MTAU#>)eeuh_L`!qC=Ls|{m}Cy)|w6#aP}w6_-ya~9LF z{dQAPa-|&ME858gIK=}lVK7MLT~Oye&UM9y?0X=8Qmvb*)=X}iv%Me)Gqav+FWdGT zuk&#ak~?2Kzf}w)xZuKGx%+`1?Ecoq?*H@EjFm%C6OT577vWKoJB z$A^sIasm!5TGOFFGmHkKNTE7KW3nveUq1bt4Uj)!1_6BJ zU6=EoPrjVdk+pQX+j-GTpQS&&^43tT43kuRlvE8fGdYc!1|m)3WCuwlqB>NeQc0** zYE&wTj*QpuPLfJ)j2$(`sI@k@oR!^9d(3&Kd6r3*<)pooPNzq=)1%#NQ;nAsF*5VR zOYXQC;B^4*Sik--jy?J`uDj-! zSep}9YT4*SOrT2I6MF4H+EZFRPh+}^b4@i8OYk9Y&86o*Y4(`Ax1W4#tX^5m6LjZPb61LF2?qBy?B_?1YE!nej)R5c8qG`2s_uF`Cu+ z`X_$#2Ur#!Pw0WVd60fYG8A#y55LDyJ!Yt$5G6Efb<6Nr%-BTC_|llMB?%*A5%rOX z`fyBbD5g@4Ns^)P;F7zjv{t6u?k1J0kR*v#Dhair3iXjH^^qz=!xd`vm`W`oN-Wj_ zNML7~t!rRbc|9I0mUjpEgOJ9XGg2;vjDZ;b~V638P!uVuejytg~ci-I(n9#M6AR=mQG0YjoLKGPgFp(jS4Pn7UJR)Et z-8ZsqWsRLXri#f_BSeWIat3P+Q3Td1#ws={2CLGpDdvrgP#KD7 z&SnaR^#_Bsq;Xt;kyI^}iX~1WYzdHamc$tH1#Mz6f<2(WuH^s%^yXK78Gyg}{;LNA zoW%$)#R!a0wv&q%qj%+~i3^k&1jY!ljfi82Vr$~W5G6u&$Wp0VqR3*bDIWLE4Y64K ze08)CmeFrq2>QGFSDAk%Rhs}$r*rJVNuoO(~AJ!PG{T~d_i(dQ;OsQc+q&twwlJV|`Bv$N}R$K=uxCPyc!RBBXfRjRcZi5yAQk|YKj*>d`|Xw~ckP!!SW%^gsH z4oDR1AJt?S?}B;<&e0TPFsNAMQwxCt69o{uA>=K^qd1+MST3tptj8GHnN(upgb*ji zq`i%b+{{=o7ByB78@8!x_Gs&uqLOKv_6{gO2b4jbc8YT@EEzqBp!v_c?XXFx9Dq zb{!I|Nu<;4kZbyl3*LDg#$f7`nKwT9p9|2|t&fmAe64Of^c3TKI%Q?_^+uxaj|?xL zw5U4G#YlpQDngbfM)q85qt=DJt|y5nG){VqE;V8I&WBCAH+|pe@QT+};^BWB8(lGB zqe!DD7GqI`0pj%h;hm z;n?F&(5YS1X4{T?Hf24&;~ic?rDC*Zgk;*ga9b~Je`?R%gBQy3U5$!cEi-#s>T+d# zWH}Mbv|6p1R<`wiiPB32Gn*u}EQxC^LGJIR?H}~g*|#s5IQY`pJzcYP=0El5RWIen z8*k;5(^qldFJ}(enhxl1pnB_vPi5uu!@1|-9|Owd=%J>WPwQ>dkLW|!5WV<$<73Xb z{0CRJT1OpP567)vYea*J7*!3_M-nC`C)l*@dKzsw^5El5v)K$c-nf?sZ)?i>Gc=yt zg{xL=urnv{!j}h=hh{KFAjIS@=h9C=(D^ozd21A$hejl>H=2t^clK$wD1s7RC`0@*-uY!cgvy;-l#dVN1;P9MBB zYkNOz%Se6b|LRCrbLYun+wD$<^Xz){8_*NVZ|aq8WBvan@ai$w%LFcRUY*i!w)pp{dzT`7$Mtk@-el!A%L;uatUOji?H zoEsX5hh<5K)reIjbUSx!{sks7^CkxTpv2vM&mcx&B7-%8i7ZhVa&y;VwDnNdWB=Bt zh@ud&s>(EBSrR~eF$b5WaH7yU)>y2y?C89gq`QHXyOI5UPZD=q>Hqpq9N6|tlCgHW zTlaEH&m(*``YOA+9^}HET*PIK$#p92o*#Af_xlFrmFES5~N z7p+_(>$7j`qZG;)NjU46j;?V_&tb~p1P|QwBC1LZr9ger&nx_HiSL?(vMt-`&D@E# z7JwbugY(Z4Ze}*}fJW2Na@}_?3an3T2Ot^i0D+|2PH+0a!mwyfwq>Z6>)M1w1ZyoK z!uNqjW7j1#N9y~4)_UcH{-+eGCbb$Ur5b*W*7cXhHCIT)QuGJOB>EcksXy+T=a7iu z^5kjK@jgVBzOR%bpU>lY-bR)?4_RyHZTV0*I))WP5KZHUB|IlJJDx=IWCjKX@O_{0 z@o__qZOs~lOwh{XO6gNR9X-z2^ym1d$f@BMX>m8OBYTjWx(?&&1W^=HEEY*7lZeQi zI?WYoMkul~SP6+cX#n2;=J#C4pFk_GGPu>PHyZ3hju47Wz@jL8>k*mj17Qi?Ja_LXvJfd%GWF zu<#*%%jcvvU1Q|iGuN2qzu>D^okK!MZtMhcXFW-GJrn*AYC$?UC~?@+^#}^h$CsYR zh|k^Ip5dJPI*F8HnB8M9Poe5ct7V1q0FyJrWD`62LG~wD6CoDFf-xa|>3i6>>2baq zf16X6|B5joSjCt5ci5RZgovF}N175^PS~dWQ3SX=`3WCidI6SQcd~!$(@ckX zJ{)?Mso+XgNMT^2pYFEX@SL`q@~>JUjfWTk(O?yxUdQd5o*nUTpeD2dIh zHfLI5oE<&R-tMC{g=jcaH_D-Od@G6=BCu=2L&V)Qr-%PWXr@t0(`W`OOb?P9`TN=u ziaQzhY&=3TmgU^os}#$FXyu~N&}=?cigH+38KGuXmM@=Y$NEFO_Qk_cnF^M>7&rRs zT(Lr0xx9DrH(V;7q$71bd%BKrYWO9za#;!LabIzjSuu>4zC^1yc59k2Are2m00Rmtg_&0F2 zav#)F$O0uG2jqda3Zb<`!0d^~c*WNOmFk@j#ernyUf1cn8g=GAIt0pq&!Y38{{qBs zqz^R1j>!N303~!qSaf7zbY(hYa%Ew3WdJfTF)%GLF)c7MR539+Ff=+dH7zhVIxsMi z7pmI;001R)MObuXVRU6WZEs|0W_bWIFflMKF)=MLGE^}!IxsXkGc_$RH##sd;7Sr_ z0000SbVXQnQ*UN;cVTj606}DLVr3vkX>w(EZ*psMAVX6$2C~zj00000NkvXXu0mjf D^r03) diff --git a/mobicore/TuiService/res/drawable-mdpi/sym_def_app_icon.png b/mobicore/TuiService/res/drawable-mdpi/sym_def_app_icon.png deleted file mode 100644 index 359047dfa4ed206e41e2354f9c6b307e713efe32..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5237 zcmV-*6pHJKP)!xJWW@nmR0Ns^Wrk)72_X;&VM@qLNZyn;-h1m-)j4PH{!#b7fObo=TF+Xw z)_t{JRqgNW{e9m)=MZ*rJl6A%IHK!gcqM)U)>TjF8ytMTRLpN39jns9J?@oOe47l4 z1dw7d06;*nuu_+V$6Qs4K>#PCRHVFExV^duw#+4>?(j) z*AHP%*L5@qEpM#j?*@5nOq@HlBR^5M@^_J9)U!&MV7N?QAAfFbdJaGWPgRws)6~+R z-NrZmx0V*7Od$!{dkY1w*wll3j_1b``)C%NHS6N>yBU998+?y%)4SU2YA} zA%$NKSGVi)4!sVH=l1lla~XcBLKrfnO2~CXCa>$GlX_p?dYsM`3%)hidhs()bzlDL zr7zEG>kK#SwpW`1YyR;!pa1&-`0t?)V)3FnK7V~pCo%hYIQUj+f?7Oh#@-(|a?XKA zr;?n->{Mx?{fOYn3n4;UD5a5kBx9Z>DQ1SETOzUjjZ`HF0&e`i-6T<17qM|ec7?fBc z;0k&%hz+o?+KMG>1)PSqUSqTR@!luCa_YiGo3TkPUp^w8T}r$YFf$gPyy|ZYU`={9 z3c4MNG|FgE6ETxVuw_~St-lefEMgF+NTdzZD8wWJ0s<69@frs3IxH*_A4`(dIZhJT z)TwApTxD36oOSS>-?;UKV^n{)k!mFpfWRL3*Rxl@V_bS?f`4@I!*C2lX%(H}L=`CT z0BxGtLQ@`yX#0U)3`bO@9NHBjM^*Gw64K=(1QdKEK*p+u<&qTSoUzKhfO`4Wz>@z)uK^Aw6m!k{QPq@f~bd?t)6?} z1bJ=k7!E&fDxUmP-(QVQ?F@i8a-dv4%Gg64haX`yNv^E%Ea<=YJ4SdqH4e{1~Sk?qbu|M;*f zbqpYh(szvQ9ev=Amrj8q0@9+|SbxTQw)=Lr&Hm@e_hY2mXXchai5dBmusvCYf%>!X zK>#8PKtTjx&+y*EIR|SkT*`=|2>VPq0kb=fM~F#u|GG<9sj?zc-#-8BqmC*-%N5t% z3v1um65bJjO9}`JV*qzjs9O-*vCma1qq%z0=Thg*sPtm8u4CiyU5H^JCTU0mH2?_M zGn{jci{Y)p`kvomV&MR6*th{{opqpyh3Ux4m)!GykUSWKMk@t>>SyNTwj2L%XZ{Nn z>Xv_j0zm+HA-wSFCJ4n;tqux{Z<*M!+ghP`mh}};q{({$d;y{&M#518E{~{H2e(KJ+~I! z(QA0${wLzt8F#!r1DoX%bYVIIT!6Y1 zJctN_2;>9AahjEz5Cm@p&;a2*ykj`$0UrSH$QJ^n3By@S!UCJh5jS2|HIuruyXF34 zRDv0v?9yEOYVFWR0jftU~yzAQIFKu_~N!vxLSpD zIxEmBpAwnRC3gEyg%Yon(xeEA2t*11fhfB~8i^HvMIcQOp5dF9V>l7DZ+tS31TC`?6B2!P-{Ai`NS%8sfWFCh_# z2!sJ<26G0;dxnUBNT3Wrj-j+52u(2zc*4ieoxAxfi_hFMD8$Dt*t4hHU+Z6a>y4`) z-dgRJ&wT2GICjQeJ24|X4P=?_kA+q7QY|L{F) z>E#!CslTU!sFuPzhBSJAZ4?NAGFdr600O~tQ;`JDd9Vkv#1X>KptUV8Q)hHgp)4=n zf7k1aF8a|v_e`5zKCDz~Nuz3ARYohScS~Kpws!0=fL0XBO0`T-YycqYn}yY@ZV?g2 zlnDnM86|@t(hM=mC6W&G)j}8N_Fwtr#>s`2R4qD9xuZ_o&BU=o5&`up5LX5DnnxN7 z(!|510_PdtJ9u$`Fq8(A0!#>KLogu_1c1^6@0sdRitRngzWe^er2PiAMIqpkE7Xj4 zqSD0i@PNn2cHaUJ;)tnGEM^?Y2OX%5fOPNhi#0IY;la!zy_Gm@B#Lw#(Mo_^%= znu44{7-|HeMy{k$Y%?&%Kq&>KG_*4CK85oRio&-@sE4y2Y3h;2*%j9ragC&24JaC` z`!uzlS%RjYWaMg=C2{s!Ax`QU03w3c0Yn(2{;azYNJdU3mn!CrxI&4*JCC^T#}y}2 zA`QzFa=EsmQ0RGvftbU zQ>{c90A|-98)Xj4nT0b0yyJf8t%xIraRd)QQ&z*I6o?d@PmrXe$eT_q-0f@}wCCAq zEl$Ss8*j&&jkjWZGSHg|Kx;aNPWFa9~0$jGSbWOU>XjH6xDc0w(iTEtcE6dO3#5TC{ScvW=I(b=Nv*)M5VtC-7j0@OiMO};u|K_aA+ua&Wy|G z0O?p6>sL7#>4bE^@$`cedW&;pHYGbq)cE=gVUygN~?!_hF|0teV`9}~ml+s!M!x_o7(s*;* zCVc-VU&If8em*{M)JJgGyiZ}QGSUDFC<*}~u!v@1)yzPXBMKoDa!^zNBmjHLN~pCo z86Fi-BjwE?n=_NmIA?K7liV3M;v_;xTNl23?ow=ga}EA*-%{NFA9)Ej6(HYiJs85m`CL9ANNz_7Wfw>}W{H&o zhy)^>0cdZXg2B-WvL1};5P}FJQvqpeDFK{}*W_F4Q?l}yJ$-+C<-Fxs|HfnZ?SC!9 z1CQT|j+S@fx%Cg={YRgO&z2Z>i~diz*O?*BnAkIbU{QcAP}Z33z=$xNR5+KgfMs35xDG&i*Vb0Kg44zZ^zZ& zc>uXE4-p1))`B-&1MC}R(r5-n0MAaC)!S!3D{E#4D+*c5&ME_7bO-`vnhuJ0%rG^y z*MSI{U{o_J!WqGvFVAW?BdzlmMhBQRZ2?B+Z$U21!?_gN1W=^F4PGQ^jHW1{`Cb9o zLx~8DXBkZ|AhymqMH-oHxQxU~>&7f9WD8o#QYOvxW(yKUdVH3~XXbxdwyFjxt+lAv zZaWSag=@ z=8P$&K}1lbY?iX@ee4?s0wKUBJ964=H$0STaA3T?n~R$9CTTo$W*+}*eEXdRL>ghx z0ulvhz0Z>9A)>e;5?WE{3wn~(Mxl@k5Z8vY60)g)Z7AM`NMj7L0~nqG?*MV$0cj#* zg?t%+Zb&IZs~iSLH{&P2T8vGbH$W*3fW~XQxiirODk4xy!&-;m-f<)T^zbbx6J$2bI!+g&Q(Tb>mTpfw(MhPbbX*24YD+xC~pjzlg4B?I0>ZG1eo;$GZ-@3q)Ayc(TT%9uB8CcO9K>t$rJ4+!Ga!{2blb3*{mJ?rAx;e_@g zW=}sb8SURhsg02gkr06Qo;))H{@ois2J0*E-a_ku;$#FwS}J2z^z{y5!Tf{u-m?$! zW7XmPw~xK}Y|U*DV-zVxM2Z?xn6(ROnxdy?JIXW%Qzy=WHv^~-wPRiPJ(xPPjP?m_ zU@!3AH)Mt2y@NuFGk%)cvT4gxH~;vV!~gKarE2vv&(f8P@Ag++xft8kE4o&xvN3^V zhgKTPzIFc&iMV*lvDmVC6ReMr3kzh>qKs;xT2uwI^KCQwiCuxGcI>;nX1mYH6|D_I zV?e$kJ`M5;L7M=zY84}cF$$#|Dx-Bwp4xT+U;&*D<@0j8tMo%x5%Tg?~5R?T=3cv%@lt|5rbf!U~$$KWHR3?Xk zu&I|c5%P}XIIb@4XrJ=aC`y!W*}^Y88R7A}hVa+MJ05U+?`P+M8rvjM6j3edroqA2 zxm4Kuj7oLnm$`fxbar$}K3^bGfWT*$Wd5R*hEfJ52%w-LATTp*YNZ}ksTNg7J=bnd z-Pkqa!RO=D(kYB&|Wjqg0rvF8kum{NfucTYqrP z`5U%u**G!G6{S=zQMp`3K3_yWUyzoz^2Q(tmC>3+s5Oq`4(BY=)S@2MFgiNo;u?&k zg`0}`37-~9P0%vHiA@+H2!cEy8o#>wuOImB)G_Pj7yce!TXGVt#ORn z(=jFB*q2Zp6$}lGp?}+$um^#4QjKaSEI75c$z6AAYL348>#uKEccl>fFbuUZ0R$d} zZ~}6sT!$|qC`YPurgrtQ76=RC$YS~T-}$t1r_YJ6x+vSq`|xwOl@gGLU>BhcFBv~FMie-ahi$Rz-LINpu0Hu~Za`}LYEdk2y0hQVU6k7}mB|~9e!x(}I6ii4k;VvE0 z?|KG+Oj%0Bi3m(dlp;$c5Cu`1CM@ypLV(%bX9 zr_WVSKiJ10x1!vdPr`gLXF?@f1r%~#N8UkH?XgO1p%e>?-DLnfb z=86?7j~f~sKElT8lSw^&-{|PJ_Z)D@o-cw6^yvN1aY@hS38meM!r|M7s_XW%93Aak za$IUh=gpcu=jzR`4$^18^F8_11#h4-#Jd^}{s&{CB`(>qac=+s03~!qSaf7zbY(hY za%Ew3WdJfTF)=MLIW00WR4_R@Gcr0eGA%GSIxsM(l48sN001R)MObuXVRU6WZEs|0 vW_bWIFflPLFgYzTHdHV-Ix;spGd3+SH##sdcWUue00000NkvXXu0mjfB?gph diff --git a/mobicore/TuiService/res/drawable-xhdpi/sym_def_app_icon.png b/mobicore/TuiService/res/drawable-xhdpi/sym_def_app_icon.png deleted file mode 100644 index 71c6d760f05183ef8a47c614d8d13380c8528499..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14383 zcmV+~IMBz5P)>IR{Zx9EA~4K?jU8DyU!%BVu|c#=(H1 zIAFva(2=Yn8AKWhO=@Vm>As!A%_mpwu-+fLs?Ir051^0kZ=Q9(`cB=t=bYMm<@H-@ z?@QQC#}7(lHuiOKOg-hI-&yJQ@X z>38Dx`mgcs{{O@!m2+^EdNUPDF+a6!8!8*d@!BI^jeED=gH;btqEI5d{e*jVDP7bq z{q~MSBE(fsoQg6}7k95+Ji!s3$poDp-qlOkXAwnM{3JB1P1P!!MLkm@C24>Si7~v(J@mNzG-t<6(_#~IP~Z}QN`;~#%u^^ zBv=E1KsZ>EXwWhEA%MjWSj+&p1YiKMScFGKjPH_0g9QS9!hVpahud$BNHq6km8f&$y)VmTQ`qJPd+?0zVd*nDN_N;fDC>PCKgkkd- zF&a`~zS4LCy*S)Om}M0r157c%Vz&|}g=6?|;XWKwAQT*MxQ#H?lrYWC!I5q;pTUZZ zoF|S^mMxt;_qPCIXf(txX5a0Ww;uk~=vd{jwJXPI%UbvK`FqRT9{O`bUiO)BJM_2% z(XOY!tbcIB+EHv;)4J*BV9|&y5&#Sa0{{$SB&foHK?p!lAcP=9mJn^Q zEdF4f`u+CiwmYVjr%WuN^Du#n`yU&B^3IJzBL_Zu-$?zTyBfz|`{R*^-t)z|a`kd+ z3q1~f(k6y5Nm3x1Yb_kKdg+KYV*sjIe!V z{5>Bz^<6`n@li*u;}T2+4lyJ`2oxNk906cBFdVfoiU|zCpa} z1i&zeF@X)3#Clk0*p&E|Ev$2}*1}l_W2{Z$7(q~!&ar*`feE?ciQuhsm(q`Gl}fN+ z@eJbtu1z-J9Kjlg^G?2Vm(yjpIN`_LzXAXv^r3($xF(p5y?b9P1*F-Cr~YXsj=g)| zS$n>$x7f>y=ZgXCM@>wqVLVI>hXL%1sn{O{%!kA@0KEW80E%#MFwm*p_a{B zD)9ll)VtgP1B?cSF@g0+Q1@mB1{Ma^85pZ!tc5iO#u!-ZV6}xY4oPBJCzg_?K&wta zn%L5Rj?vAeG*Bm!j&+Mc0?>)WhhMvFm(gdJCt~yENoevA*5h{EDh@*#(_{(r%m&=? zu|e$lr34M$iU-{w?Joo(Y{qhgD4~QIkSM}}!O$?MLZbI-s18e=OF&ai&7-M0rh0zYyI+(=47^@pK8?@?t)yRhO zzs%pSswcJ+l9+kcqH%0n*9V;dpM3NE&pVBFsSjxAt=MWGLVz-sxL2ty_6bwL*y%l( z^9>+yo3UI7lth3j7{MAa0$2!WSj1?ejxkiQ4K<7-K?@ef2cKYAaNFUg(T{h&499@8 zfO7ildBY909A~mi5d(n62vetXrh7` z4HzV;U3Zyv?>JqX@EIcrL17PGz;pl_gtaW`qV2(}?K z7!zhaTCssiN~pzE)ZG|bt^v&&Iw!VCuMKp5YG@e$;~cE9-qBhIYucx?3~Lx{30fye zS{fl{!|4FcxRUz?fTWbfM0}x+#ep9=eVP@JqE)w;wWx(pTzXQP1!_hCDgS-E@^?9S!F42HJ_S_#uc_5Su zs5YV8=8;EdD(d~XBf)i7k@eOjOu}f!6L8G}mPQ{ykK7Z1=*K{C7^dQQG~*hqW*BXt zwShMNOtkjDYl9@w(22=Uqtnw^7;U{qm`pPmt+!FL;E8XQ{Y&G*#ZExj-eADv1EkRiA9p=HbW9mXn&pE zx6s<=(T*{$-anb}*Q^f2@NW}!Ypi#4-44eZ5;wFGR z2l-#ffa_PC34p;4_~V9Ch1H=Mop@k2T=ZsZ95ER2~w$V2Qwf@K~R83 zvJIQ6w*fXxCEOy(CETXcuAvj1GDN3@H|;ZhZ>JU*V<1q%=E-}pVf-!#5kQI%P6I0* zTLpFk*7~tCJ3&MYqC=<6ZM^c6Z@7>dv20Zp<}9uM?_~fH0U)$$1VND)+d76o^q=A^ zEr^rEHJg*7*_`x*)CPi!7_L8n$2VUEYYnzlmg6rQKZCm73TFhg)~N(r7^9)J_GT#Y z=E!J+L>qrUGe4>H>r4xD=7=p^O5i)6{5&4r@Eg=yoNE;R%JeoxjiXN3-XX0XM8Z3x+2kseod+K#}a>@yV^%M}^*#iQp1F zAst%zV+r1|H5(QIra@x@LRv&YFN9=BDFGr7sAH&E#DX-22b|;do=c^e;n;zlgR|aA zyY$*QZ{k|5CRq1iVqyY?LIkChclb`g8G$6Wu3oE&%0x0;uh6maSl?4UGb=(U=b9CT zAAD)W^Fp)dRRgSbAYouM5g5E}`|w<2-3dk;YPD)2(M=f5sbl0cDunQcOk3Ku&N5x^1FSJ=M3mZon=-*VILENo0tgU=eUPES)PX*zAoL7o z=^+bdICcU=mYo}9XOEjc^IkZoMNjft0EE-uvH$-*2E<7n^$EZlD+Y?kfE~ZUXxp14 zEf*&Z@EgTT(Y7k=$iK(SA|BR=ybI5Z(;@VwCMZ!$sa_=8wT7h@fN5QG4U zvlvfCab)odtTZ3MLn~IoCYzzuBK6l5SDPdEd-X-eRX!@EFbu5#2NG>lLPR;HL-}yh z`_wi&MC5}HqLgS1BLC{41#goav%lv!HA~s6mwsoR&nay7yEk7xf5)QejjzT(&AaOVO#?>xa{z!6%4qPn@N-<8|7}ThG@fYqze_s}1$89iq|O`10Jds> zYaEiem4=mV>361M;_0g=f=i>8)OmJ>lG;J1CPwF4k%DWP#OL>1TN^ShV9rgEXOi~~ zo@v>AmuiBAwT9R;XvwTawOIhrs)H{7(gpbBM@FC!BA{L{Kms92D$+oBAOK+VhGBg7 zc3)5U{+-ADeGFL39|7~7nBW-O`9f^QpHak8ybYhG0{W>$Q)!!B3u9_nx2~CC?^LgC zw{LpU1qHTp&{+jz9CbniodoVWt?PyotcB^iXFaoWV!JN0<83{suyab>OdC2+=C-z^ z*N%~DOvW?==a`rY)^SNHJ^KfD&w!Ai3aa?hC9_FWO<7cBACBb`&gR+lG2YO;P7w)N z$40Dvd?O~u8W0k=P_IuBrh5qCR6NJtRo;Uu{YcZwM}hWjy#XVYoCUvLpd zn?q7ah~9Dw)-ffue$<-Vr!$MGYy)F7V6=nL-sT&_xx^dO37}>6x)aZ_usS8a%cMPf zzwKh0F>OY;)b6|VyE8_(G-_&JBaQvN3G>W?H+4=hAT(PCWA*%fj=K_LBQ@Gqt;@M| z0ZT|@FlvE~(|`wNGT+_rM8!xctgZCX?71^U5PB0x1YCU0kH~j9c;9A zYgg6?07kd90N`nW-cG@|S^K;O3l@!{FPe@H@;ShX>*$mw_$j6^H?+9E=;4JzVe!A@_?7{ll9hUq1mbgaVweTVAJ>>5RxDy zfyg`1+@W^8a!MHF63fmz-L`Zicf>A}NqK&zoP2oG6*0z51&Nt7Xq#*6oY5hmlvF>Uo>Ti(<_Xtp)F~;ksPsCeiHJgq7 zn$5=R4m)V>q0WihPCt1@ef7GAsEk=IlmzNki#xB|p40kiCCT4D^jduClFfL-Sv@e^ zq6;hk={{Bbz?2dOzty0|8!a3{^g%#iL_dXUZG5(F%43_g;A~0i{de7X?|+~1_Lqu} z|7ndFoN~|&f4=+SEz(T;R$MDCC9*6F4U%CCGKx{`Arwmi!h%2$3aF4ga|D3|00Km= zqm;J_I=921Ib{Opzk;3UNYv8Prgq*kOu|TFhq%dTH7uHSz{U}59Kkd~#0`PT>R4;r z*3qB6=(O->fBDloG%$^<-m+w9!-M}_oKl}V(7!?8r*DX#7%u# zqiRa;J8#t~r@W!xW`h%=JMerO17z636 z>Mb-fJc&3q&`AQ4jHsXxMuey+Q78!%N`#<5P)Z>xNCcroSP&p$2q6&!5-MaMt^Vc| zPeWE~7&-y0wP4542_uOu;-<%xlGq|?IJ|60S##{G0sLlSv?cqe2e#FWpP2z*0cQeKM=O$hoZYsudfZqvbY?RiHsquN31R{S z0>CNg*igOhM72^+CdV655EMRErtjZ%@l}86Iq1lP-m}kvi!p0H>ql3u3HDgW*t#yn z)(sXTTY<6dEliBY7#@kytXt?9ND{yq_^zwxbnKYQFtUpAP7eV{38;XeLZDCx5EUhQ z`T~@D6^gwAJ^dOzQ=dY)M{-|ZKNTkJ85`G@zCy6ewr-p}R9j}CAtu5EK^OvzHZ~P& zv|0v9lWAf^^R`XRg8}?z+r}m>+`HE&c+bRu=EMLn8`!d8f@lwkiS6ouM!Z2XVnZZ} zg!InY5u5{zwn$nAjYgtc4ab!+w-}&k-kf6x*RNUKSE+8n)c*Nu!QvU%V{eOMG!^U^ z^=1XFra|0vXw`w*q(;4(pjowO)HLd~1dUpPxMh*F99k`pjQY$u%^949O_Q+9JP83v zMUYBBDFGFD^A;5(!h-Z#6%nF>M4==R6@+I-Kv03VcSd^?Rj)d7Y^-%mlES^`(fP~X z`^AHcjk>1VWK1eFkTUTo1_RDGXzjddYd9n=qGp}>?Ju|ouQ_`GKKQD?;zM6O@R=Fl zbO;b5X+)SoAHa`qeOsYf6CCRVQYe6QZgVrcYP3V#vZz-yRmNighLdVfZ>5UU7AU}H@0rcd5CEg?Gc!Pt!ZA}W!(}(TI#qBn!3=VaL7hz@xpV7?oe3bJ zdJa5tR(}-sRpORy7`8oOBALjM3)zi_o|!!u`^Dj6v?Eq9p-V)oXiw-F^3s( zGX_Y(8W2ebDg9`PDDC6-s_6;lnFH5NW$#Km9BhYhfe8eO#59oT7@;ad$pDTmIw`?u z19cu|KzBaC$g^SR+Cs(-IW&>YlaNb@;PybeXpvLjKQB`Nk&PJuv}<(Jc}K$MQ>Gn| z$j(4JpIye)lw2u7sf`AlXgf>mCCs`G>9a1yW_B=TopzMlh^Axq!)1v$X<=+~8x#*> z-jo->B!r2|b{Jy-R_(+sBeLrzen!~LbaDsrokMPDIlX2NOL%&ue{6q$N8;E;CZA#w zaXtGW05mJzGXFnoKn@VMO;}oV$|Z`snBY<(k#9wosn*!G84wn5zQ5Mn^z?hY4@jTm z+FIb!=Tn-Mwc{J2UW1DA?tu3mx$H*`L^tI?Z91X>{FLJiu_yR&#Cwa5{Qs25|buw&r+a zojE^m|EX=`vJ8(D3BP!vJblLWa-a&W_FxFPjn3@1OY0pXv$fncA!a}d1?L=MU4hmH z1LeJN+<~vh{tHh=Pia~%2s5VciBpgLERGs~6PB<3Z#=sGT1+;!BMM6hgJMd2(`B1G zCAU+_^WY|py4pS^P4t{`%*u!2sbEo;eeC!O-<3yz@6H1}2KFo(&|%a3@0C;vsQnCX zzb};*4=WJ>mMS1Aq-4&K#Y{ajtx0_W5yE!VDZ{PF;$ZANesHv+rAR|EeqT*t+X5T3LfYMTmlO%4pjaGG=pN&O+S| zMsyICJZwfp6nV*ZkR4H2Zk*HWP9M^FIM;pe=}?3SQi=9Bog~@tlSH0yWISNUd4!S) z2{Tyhn4Pu649X_!Z6KweNkh-{b0j3?N1!?Da?|o37v?^|T#kh>!=~ zUj1WZoFtOH{yC1AWgdBTa-i*yI|7N!S>st4(B@EHIuvcKXb&N-H!g^JRGvOpLO^F|o(F{~cf1z(-Y(%2 zIFgPtZS5lWj)P}*sTax1NZK z6_m6>1a0l;kd}PHOh`-<{iOw1IQT+b^!>Ns%y%A!>;Lc@z)46U(~gGc42^aj)>#k{ zq*SO^8~DLbzkyTE+zXfe_>0(Q?kSKc!dQdOfFf;8L=g0#RG6NVh#>LU(5>X0>7I92 zMvR=HnWJ{8>B(MgHx#t9k|bmL)J0xB0T3t#$Z?KMba1{SBkYj6Ac$1ZzS*5McNWBv zI^7xl2jC4SeG?a5a4qI7nTpSU`*k?yBQM2Wci-$WAt6#mSUlU20dUL=DJ1Ik27YtZ z6?oHm$KaAHK7gZ+J_J50^Tlr|C9HAy{Y_Wm zSJz&Qr#9b%Lk>I!A9>$ZIPS1hA%wtWWgPXYfeYFhaCd@5I}DR}-Npw)A_}u`)@SBf zCeUFOoC6R*$*?2(Nyp3G<9-?g-uR-+ap6y2;E_lGBs!em4){nH@zV)p4N&L`gR?9& zjhHe%r0_yBo&*3`XAr0eFFxu`IO@QE#!bt9u>+An5<56z-;4V+ z3C)tn6uTmcdOXoX5arHbvK_{DV2IPJub;JAZdhnw&H4z9oLyZGouSK;XW z-+;HA@nI}kvZw#7wZ4fLz+aZ#fh&IXpLlfbAF#(>3-G~rei<)1;*A*SpOrI>h;pE@ zv$&r})|o>S?SV3bo#j|c(FO&&61G&xkY&~kcs+I6#Ib+2;SSn7GXwg2r)496ps>M= zI)J{6xw$lVG9pt{-(^4mEC8FosUyiD+3mnOQBNO9wHYxubs^4t`4@4*p>M)X_kIW0 z-E;-s@$sMIWk;WbH=KSh7A{w#>;o zN+}=20uVx2fUFPAkcVM;5u`%}DXmsXNdiCuxOz6X9A4QWjN3`Jz5^qCb~|^*zIf{^ zFUE<7zZKWtekrcH;hVT^*_Bv4=TQ9h;Tth9vw#nr_bI&mgnz}%X^XogUW)&DJ$jCa zb_hSa)S|$*!XWiIl;xzkx8|JaT|&mlg{a+%p9M9~;sg94+Tj$7E=07WD$^DFrbJ@^ zLQ$!dt3y|I$UePy+>!P0(_-UpMx@zo%7}%t55c)-eiyGe;a&LNl^?^hzg~;ePk$rM zKI@AZoH{QhssWMABf0`z++;^%uafT zm}kV@W7=tFoDd?X4~aCx$`Gbbsofz=aE_UX5EY^V5rI2805Ubrq^%3YdJcIOrP;7! z3u85w%sm`0I^th2cX0`?dBr&xoH`H2Bw%(BLOm_xeERpbr8PgSc0 zr0O1Mra4`5n1OlOrSlwXW4=3LzdM_x5RhpK9)&%1BGf4j>pN?qS?2+zgUudntxx-; z2)ca*x79vpBA$~1>~JuMgl~&63@NEyxqA+u1%Otofkva|%@lX~HqL!nXVFPW!Oo>E z8qYB9_MAM(Xmr*vmc4e9e5VZPTpWQk3T~I&IOlYyA8l6$JpKQBskgK1zm0pelY8Fa2xLiE_7`ioC6%Bo zLCq`xfE~cb6q;iJfOQh3~E(;W$QhLqV%s3Q#Pd=|I0WrxYP z{m9>^18IQ$_kEnuZjVWCWOEWE(V?pVV488gW)ddnI+4hoJf5?%E5TXT8qyPXR6fXP4Cm>~aQT~4j z8T^cv|JtYelpFKR-nQA^q8;*?1Gx4Y8y>s7AOR5*)4CvSmvGFs)m^mjC_2 z(^0QKOGy#{nstk!801$Rf4EeYqKzB0-dRD;S!bQi2;DJ5z%e_c8F7>AI;QmiP>6aM zP{Dw2}f>-}+^|?~^CtC%^tW>h&t5^x5olDZ)IH8OjJRrNZ`+E%^H7pTOB4 zd>L-N`!^^Si@t^+(BX_TEXQM8k?IE=u~JgC^q7X}`E;Wy!Dc{(G*b)iw{X1QFST{U2Bp$xAj>lInhY-&J4ZZj7hcNxrSt!yX_njL)g!;Jp z>g0s@X9!sigGg)J63+QGw8juyExB0>s5)t7qvpPS)G;$3zWJ(ED3zw#vY7_s>hL=q zrZ@@OOS8egIcv$%`Pj5>3_rg56ZqrpKfxLQ{9e5L#s7k0v6xoT9Au8|WKMYJqMt1{ zl~O`Vh0(F?xcc`$!f&ttE+*@nF=N&M=Jw7(5F$lqvj*f8OUN-Sh7vun7E~w%4Anr= zto=$BsaTuTUo3}n=9Ef)Pq`#XP}3FY=A^WVS=WpwKODw;-F)t+PY{>?$6a=^au67d zD0&VWaLq68#@+YbjHm~0*#mbHK=(E)!CB+m-L~3jIdJv)GM*R|wb6c2AMKOX;j*et zkZ4rRw>Phz_>>b<6#yuyxWBvrf&yf%dU@1}4!a3PSYXUuI2DH;y#%U%8!r3R`|!R` zy#jx_?YACb71F~U&UK0W4l!1WfcmOfv(>=QfBS8md;ZDz@$Wu|zCn!x4q1qqb9+$g zZ!gH$5tO1GmOruMdZXE>UGVV_!3igw!xi=B@QK4?YtEmn4FA5>sy(W8^ATfOH&|Ey z=t%v+7dk_~?U`8<{pFbs0M32Wr6?9kxb5l<&#nRQIsbJ0||h!8Pz&|T}y%N2P2E8mafjyef|-+GMNnIb?L7UiI1 zfFy}=Q$4R`fm%d zeLdXL!=wW9DnY&f`RQ}6x@e!*Lrw1o?)omw`!76^ozqYe$-Va8!*1HR38%h&0bY3Q z3wNrmJJoNat{I(=7_D2kO@LaNTG1co!8*pkG&FK`~JDG;YJ*A=mN}`-3J*m zWI%rTQa}g-0j2!91V(2Ucsn`+$aisrw<2F zz(N2Z3n47#FPee<4w;4Z{yQXJ7XL(^U#w+TVe)CAma7wwnA&` zNEq|A-|fw(op>-#J7IrRDn~F0ZP*45>`>~nSTg+}%$dFiuDo<;r*wYCH0J#OJQcSt zy8(MI+7HD-8A53M*B9=`8RyO=Ye51bw22vE%&s;S);TO$v?mtru~68!=z`E3;AH*& zYP?n%H!6h827}nA{zB3uKmd>TzJ`AaMa-k;?_UkDrOJvbK_zCGqG zS_LkU%CBS;J1kY&ktmtD%F}%AScAn1!`rH8H4Wx0=*Pr(4Xvs`-_#<6wCM`TZ0%Xc zGcvoL<}P`1$bR{h)*8e`L~=G@3Z`1Es%^t-Rwx;~xY`;XE(e1!PIGm#g`0n~>A8^Z zS&zRHO5FLeeB0%??zeX$Dg6~Lp5Mj_)1LKZ3X`Rw+)CR1vh9DUz34tQm3ct0m>)7j`{o*_J`~IhWHtD(n@@Liu zIJfs&uKV^1Yquf(mfpYqG4sR>4^bYXo%SD_(3%E{zF1W8SQ#SnDmYJ(pMhr_w6?cnyrMj9+v}s zdu(OaS81acCULxf94EpU$AU`~1yd2KUJyrMr@*WL4&ZD`C|1a`X_f#Kh!uzeND4s| zK!^~6B1joRsRATLkTQax2!sL%5r`rXhX99Qr{J7|(*o8guu~3BS#4X=*qQ+8$AU0? z%kc2J-wEmyM;vj2tJfdHjVmfR<&b~DPcOaYd866$zIE{}*FTIGzIX zSQwP#o{JW_&%XCsocNlB*mrOaEXMKhJS=J!VWPSbjxDB7St7QL zuB38tx;^Q*vuECT>rYp09eupF+#7IM2&owLAPW0Y2>PH@(RW6BY|`UFWWjJCB1Z&H zyY$mMK&0y#gdk*#yJbgdwG)G~a8AS67>TZPyTsKTCFNtdIGT-hjvvsZUMqUN&zJUgsK2R0ZCC1 zp(;?IN))ORML~%IRiHvtLaA6rp-@B=MF^t+Dj*2u;JAf2nMAcViqX-n*tBs2#Cmj8MC|07kNe(W+0 z$d2>B{7TH3GaqB46PPl!k3R6`%lVJXzB~Q)yRLm=<*NIqwHlV2bwf$)7i*C4n`{J; zL=Z`Yp@32fg<=s>f%~VH?+-#XDM(EbLKcM}_Bn-O9lIrsMy+IxL!y&>3*#g+3ui(IzkR{wpI^Sq=(EfJ zhs>8gdL6#`%d_!+-uDZ9``70J0KzDAK_s|XR#1u%MgltBpTQ)))uh#MXjVDhhMo}x z7Ol8pbwj>u`8}KOKmH7arD@<0ply@je?RlTrd)mfFK>SA$p;T4NGAjdAMPrTiYf^y zebf|20x}?k5s_d{65FZ|&KR&O?p=+s%~NpjOCnS^7ZAtIT}pglH~kwcsnS&bTbS2@EKBEdP1Bn0PBgumxA@4T2xe)}9)BAIuB z`>yAoU4F-Iqsea3fD8i2@b^|SPErX{fj|_c8z~hf3h7zuktp^kL`5&LA_dWe^hEsn z$Nmbf8IB9+EzII`PP&GcF4?yZLL&v*Sf&}V3R3hl5(o|k;nk!v?nz)7gBm@m5MkF0!SIyT4SR6 z+ViGBn--t;wncE%0#EU+9-Y~5?gPSQ2=9tbG}TKf6@A2H8% z>^2`zES69#^kHb|N%;0vvVw?h+QdlA;B5aOmu_urvpO*#IYJ;E*ITP%1OTH9KtU?v z*PgPEWOhzU)d~W|5RQXTLInaUkRG&{{iLudV|?5HV-I`rAPkF$qB07F9z=z*D@46$ z#^V&*;ct_`q_IY9cqHcj8M~GKyEhZ=Db7bweU05~;Tkbz8g3t6MgPu>i~DmseyDp`}_M6@#}p zXMfV)Gjmp{)C=okM?$bv3W5}@WzneDMI{*#QpBGh-n{vHhaI+`KtbF6j_*gSx_c9W z-KGIj5=JH-!%=)57S4Ey+p=XuY#)2#8;yGF)x*PEme(qpgc(o)&r$);PznPIt{}8d zwiw%Ze^OlW?nYeT-o65yW$q~~M%-$`I*lZ0V%4fgU92aBl;S24Brj?tTYeNL6SXib zik{Md>?ux@g|Jr=gt4x5j}xuaO{4tjB}?}cebXhMwDcWVH#C7;ezj${GGLd((VfRt zk9-#Q-SPlV*!Ln_bI+U5)Z1lTW81Xb3Xz(2VlkR}Tp{XTq+}==Zd0OL_f1xZZYqaM z$80m8n72X(f|FK)sZ-~pS{cEdh5fK@9HXNXsMa@O!Mwwz3}Rcbi!oxB&F?QSIIdWj zx>(6VaVGmk*5<(bg6N3tnEv$EiVjmlm zKuU#5Wh;L1&Bp-%AN|S+IN+dtu>8SW;MiEQQXoi>G#VR3kNlOA0hCa%=}ubL{Rw#g z8>O^z*aor(V1b*ij4|}&n%zkb0KoqRbb1&ct<2Ko0000bbVXQnWMOn=I%9HWVRU5x zGB7bQEigGPGBQ*!IXW{kIx{jYFgH3dFsPDZ%m4rYC3HntbYx+4WjbwdWNBu305UK! pF)c7TEipD!FgH3fH###mEigAaFfey&@l*f+002ovPDHLkV1iQC3p)S+ diff --git a/mobicore/TuiService/res/drawable-xxhdpi/sym_def_app_icon.png b/mobicore/TuiService/res/drawable-xxhdpi/sym_def_app_icon.png deleted file mode 100644 index 20a47a046fd8c309db8012e30a7693ef7ad325da..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 23909 zcmV)VK(D`vP)jYx%p1cFr*<%P*gA>W?XY3=<2e@HLhU|yKCN6*EQ?v ziU~1`0aO$WsDLOSnQ?#_!sNO6-V-`h)%*LSs=E8!8DIv6y)&QRx8`%_o_kVvS3UiP z=M6>JPsVSzoQ?VOYOrh}DHbg~!PDajZ{0K^k~UiaUcWxc*daIH zzV;JK59)ubo>3~Q3%z0Ob~L9myy=)6a6z?Sr8EUc|2gOpRG!wuW>yS8pV z?2e7MfBU`9yYlb1n?!&3ODEGmJmyNC>+`*@q2~Goc6VHG!}+N7j}rkfdE-9~>qEeC zuBiUcw_Q7Wxs>>^RFSk6rdE&U`gHGeOzG`-ME(2tL-Uz}qqbQf5Bc~#lN%p4y1ki> zZcEQR{hto|l~Q!xruB&gpy&F0?`!Ng02<%igYDz%p>swp>c69ZevSo;`)$46K>uLR zr#9cc{fc(0y<_pRMRdgRi}^D@e+1rm`qguN+B=Q)=Ivlu+>*aq)|4mKEQsY!T{j?Uwj6Q-Zh`4i2IiwyY?^hm*VjL!TwAs z8Bb45|6tW2!!Med$mE~?u+bd0W*AdrjDLRKmG}C6ck!7Z3}X@&gGdphhXi6oXplfm z5)l-7!C<6lB1Z;|gfnzFGvsIx)#xp%L3_ z(lc#GHZhNuW2&PV^dS@1187X*~Dl& z-m<~0`{Pf{d)D7>@XWJfd-zF&OMW!hGk@P>zmh;7Joib6=WPdPHDx%}x;6Np!%Opb z4ln4*8;wTPZnwwAc1)gRt=Z7i+atdD-y7^J-nItMJM9$AU>g)_=)(fpgH;saDB~Re zHvWh+Fo_97fLei5=FP`ZLlFjt6?%tb^cf3Af+?9`W}=Pp@vXRF@>+A_Lb0FyvI(%=FC9AOG0no_X`SyT#pq+iu_VoU5^&-y{Zbps3?W13ZNZgpUGr z7G83|0Mc_HaeAWTHlIp zyCM1L@Pg=_BuEiQdi$m}zWv#o=6cHSckEXH0)P*G={W#PXc`kqldO>9#GxfKSI%1! z#eMyK+FGNgCa2%jXsFLDS+FQRZOt>xrgVe(YV9L97LZTC>yGcms^`TReyT*{Xn;_MR7f1kJQ9$EG*(l-WS0Hf~ln9{%0Y(a9I@*fO1sY@3PKUDvtci|^a=Xke`K z#OJQ2BaUCho7T7S({KDg06iq*{r~$U$le{WI#PL_Y2*X{GPET7$h?J(yk2iaNz!Rg zjLw|Y%930D^@X?M4!mIbA{_P729}(q(04QdWSB&P?MN|ZEHn#56rrCK`beP%0x=N? z8cj@N3tHF)g9H}L42FSa0L+j~h^U4^8DkiV2O!Yk+?t!3X8Qci&AT=BO8|ZB zE3ZJ)-i+4PgK+Hge<@ye-HvTjizh~#`Ns9l==K}3j}FYI zcSeEpe8_8)7ul_e?GYXfCtzQCD5&WCi*Z4fMKAimsiMyr}PZA z9=8z3em=pbldagobzVqJk|la*0geG7MiX~q8h61UMGZsf!D2Kp42e3rG|8e=HA;)~hwkFosEML)I_>;DO<2h{(PwH&dev77YDGN-fhw z6A7>s0;j)h8Gd%&#<`yI`yKlYfNtTJp}zo6B3I)}_Cg$|hS2l%VI26*J}kx**7FG6 zEP81f7T{<^=*1Xr!36FAp@v>8Lm!r)hJFY{AVdJ_{wMZ7%1=w+f1Cu$(1L|Qu#I*C zPyrezzt}Qt7nlI!rI9gA#$-$)B>;anJ=Ixx-JiDp?D)qF^7sxdnVFd-p8BH0aPfEc zZEtM9P+>Rmv(bZPAP88b@*e!r3}D5)6?phXLs)fk4So3t)~ZRYrvV&*1y}=(3?sM| zIohaW7&Q!_h5^K$yAhthaZ|tm3>X&hMzI5kMT!|TF@h9R(B6!`>!)W(g=azMDOrA=WcI5BVj(xV((Uhzu!Wv@%AkQDgOMY_2-bpOP{$Ay z>ZoA=3Uw&dpil>aV35NggFyxh?IjHRX%S!m8VOR&KqD;x6a2F9e*qrr0ONpTU;>Cd zcmkNJATpYvbCahXj`Boalc&*hiQ-MhG^N(LVFr?>unvGl4MSiE5Nfbs#YStLKb*Av zWuE4bVcS0`Zh96<X@Z9vn^$@vMKg%US1w`6)@nZUY$> zVCz8?9y1lv228Nwb&tScWCH+*KtxJN(n8orH~RJ0pZ3a0s76XEQectb!{2=PTrbN` zW1sZGu4=vnQYiE%C!$ePDxn?boCODce1Mk!eGLP7hE6n&JCR@#bu2)P0pv*0#C8A* z0x>jF1aHa~A&LwJ8mLGV0EP0J4WR0C7TqkgWrnp3W=A4g>)&T9&sW@dX7-+$|6wk` zWQ}``EnqDKGv~(GqwZddSP1%!HAb~&v?U>M+H+Upw?E!I*Gp84ebNSEXjm)JYFr}? zQaz#b7tK?v-x{IcEM`Fplps)EM`P#AbmD*z{e0-i{8(#9ADTLD;dKWxF)6q3xA;wX|5#z_0_PLuvB z1YOY6Q=h40yAxmfz}pDHjO;bVXXzRgc3a-T*h%knvv%gI!kv)4@#gc@1UnY!Eo&)EWrsF$<}_fCWaPSSZ$E24yKUm85jdd z4Zl$sO6mY*}&yXwb%YJp)`X^^39 zM$t)k005-u0YM!4hV1i*<9Y!gA)M3^RJz^-03rXGE6#jH ztpostI9GTae%M-=>SI%pNCxPn(>P|~8?a{K3%yD1KzsMtWw`9Ne|1vLl9yJDJhRX_ z!{owr+NsPEdX^A;5r|}N$4ol05+8rtmAgH+57pSGys#{9LSYeIa^-i;jko+Hj^x1m zmFz)|jB-wqnl`em4WkW=w#f4oGo7tiM9;vo+TVdapTj;8V{z>XXz;6@Y%A|62|^vnLgRy|0YnDSCPPguz=6Y01psgnxzBOH{3qaq zm9ImRH31f-m*(CHfJjOOK)-+Ett;et?>yB=o)1e?bG=*u_8~9q(v2^HkQz}G%T-Gb z;RVBMUeTz{f2C3lW2~0i=E(9k(rgCW=1xuM9BdTU^t}J=poVNk>UarLVU)YnSmnLN>xKH#5M0M0^PdAHYK1fe2@nWo1U-1jNEivJg*WBE%-ovt{+Zna#&M@%C$(S?W~qqfT3etA4#@PS?+<=4fR*z)HZt zfP{aSUpQDQ-W^itfvNRS+H`3k|dq;!oz(=g&A$Z46$VK;aIrf zpce?#4z-3&o~I(qQ>0l7S=NF!x%XBq*a~#gDWtg*=fwhZ4glER`V*$p4SPgm z{*H~1LOBqID1LZ1TOoupBU(qHl;Gq(+{` zpNmxQ0R&=WwaD`XSvG@QcRbxj*8Lw_Ffmy<6%R1LW=XQAB^6~R}2NSf$2XW$Km*JY8700j#fn4cAxSiZ2&AGvSI?$1vvV9_AGh_kg+~K? zvs9VLGMZB{v`+xYNf|oq(-EIa!pwX{!&B%Lj z^Vm{YB*jr|69Z2b*PTF1oXI949k1EnJW-NIj^rx-|p+>Jv-q=}#y`Z*-c%}fx?^*II5 zobx~ztvwq;X*zPzC;7mECG^vEr(YjO^<$N)TZR_ev|(%qATFdrSbSzc2=WncLas9i zl8_=UB3(i_@=!`o7*hCMUOw}zX{dq-v!oEZ0a3oz4Vog%!L~~^TFZbHu+}2WHP{H` znJo=#DpNt22_|Rc+8|3aq)BSq%}jJ!xO&Z#ZaeA3M+4vd*JGiRUVQDp=Z2Y{a|x7Z z7806n-0~*AX^S|@vOU^bhSoV*&Y(@|D+RGJTaRNqsiys|4x6eM84kg81k2p462kTs}5gc%@$ zHTt;ge{}R=*Ii(5Q&BFA$>vN7%{hPo0b{fPvn5iGF>HkqT3c(Cu_-L)AYz}q#om5F zk%?N#hA0+^e1dy;9>iV}1)T&G@S!q4r;5+ns%*9jD;Jf!7P>p+(QPvoV6r73t4VC( zJ8j^rEDAozr-={%Ljn;fJDG&NjX}cX;{VS8VrY{v7?46d#u$wpPVHFEz_6Gtc*5UZ zPgg?e9MYVrjJsQ7D|XZDPgnS#s{3sH7b3XTB?tiLxd9a-5~!%QT>%M|zy0TZR${3R zZ5Mb#q`%~*h`m?%c!>7bnTS<1f6i8K9{>>WykjpmYChoyzkS}Z#uyOg0&r;^E{Z-& z>I49hS2)Gp9Hff>Vuq`upz3QBA_SF>PzfA{^VW9ZfrVjbsW0w&yz}4ImVo0~U@9bA zmntkhF?Z;|D*?u^aG2qC6sWM* z{=?RDO_(K#3S--=Dx-sR^3umJv}WksB26^XPR{LSPSfLdsx`XcFlMu(-k;M2=iV|W ztn{2qAhsY&8UQb6L%pzy4JSlieUP9+`Zyf87#C63S|jB9gcw+`iK-q~c-_6*8_eAO zEkthdC`h}C>H>Dmb9yT;8J}BRTeY~QK@c#u8fS5GYWtZ2<%*i1}O7y z0!0u;#r!F9gUWNBO)hrZM^!ae9A~H8A{4KMh(t+Tq7sa?1;^x)^#urIthEx*%PgDg ztu4j!b^L4$U=_x(8Flnw9xoRS8X|={NyO-222DG|Gx-GXnAv38x`{=-%P~2<15aIX z@&7%5*7A!{$08V{AP^LKh@ilbNKAre*5nf!Z^0&f2X~I&ipS0GZu-Z@2^$6$u}iFC zW)bSiJ$u{@qT+AvUi8@-EP$wL_yPqR>HnevB(sE3nN-H*cU2`&NH{|kP~eKu%UxhA z4Qq7eL}M19ss=b0jI^gDh@dsI1DIaKY+wx0pIa}&U~L&Tq*vosa}!Q$yiyL)O4c-C z85(_f8Hk2)(7ypceCL_|xJJ}WpSbm=yL1#u{CMrtk#Zo^Z>etUxyVq1sW+P za0m6_5UJ41F@_8Pw9!T^Ye?$TVzaqKY-=X=CqMm>ecpcouX({sF+MSdmz?kmN18b) zaj^R>*_yz;0#p!e?4^%;%(H;f4IuW$a8(Qi>E%=$SN<*lQ8B`~3v|vN31X@Q+r7E? zRrh~3h)N?o04JoF6gLFB7+7iZ1sXtrtwsM}#I30u&5RG$CP!Qo7>Eu9tiW>fXmNCH z34X4>ZT`Vti<$T%%M?Y&PUGtbB>XkBFd^Euy(PEm+TZ-fZtB=y+QU`}(QYTOoLMmN z*8WY%>FKvbggftCi^v?TU?a`YZ&CH+6S8NA&hw1&yh9)t{|WXjiE@F1 z8Y-j={Bu;A%i$MQ4CV0I@-r35Q}N0IGaTIW5@gks#hn3CeGaq1)8*=;;D)LJU6&FI z80}JGUG*v)Bb~F&Q^WI@DBN>FZ2&Z>YqRSG!1BR(9khhJ@|UNoj>wS zMdHl_dkVwUH4?Ni0?iq;wa7GQom5{lGuipV-)@-r?()^S-F&wto#z$|OpfLF;4AOH z8g`E)&^5{5Bf>B;0Gde*(@Kg#W(MC}ayTCUVhetXg+0u|&bQR2zNl}8Ia;5R{qq5< z2EIL1k8WJM{#LsEj`bp{NvmWXTh|HGT>Dgr+RW#MkG*u2ttYQhwX{xBb6g{+m>da+ z00j0%ZfVbys)`Ha7?sy6nZ`bBQ5rWPz*-u~2n3L~S1Pw!m&z<9N-34R6tY!`gaRDS zKrWvv)hmhyRmGiMQL*m6P{4w-Q14?jdIf5Ai6|0?Vg;!@v&_}2=;nF~FwI_-S(n{qPj%yKCutL2D1}i) z@>IO2t`LY1P0V)t%k0QtG&{+YXN)`p@`RDL1+q@W&6y5qlUyQ{{?v{;`+mRrSlu4E zhv@Q)x9|nm{yinR<;n5!r3bHG`Fm1hhjP@?1JN?-$0E^#AtFTB#_KSe+<`pRNRyP4 zB(qtnIcXa;Gnwxg-=3cq#dNcbgt+785t}x9aPEKHx_1Ed^YzaMF>vVWl|qW#PMfI% zmdT@jtkF7N!&r^n#^|Fu=8;5=CV30Cv~K1sNjXV6oOW^n+auaj(d5KP{_J`q{zJRn zmOuOcRp#Yq{SzkB^`hRB+NR!qVr#7TZBsj(IdDo-u6CS-|4o-&d)qth~AU4uy@K-XaN7&;NqIU~thXm-Z7w$quPCwlS= zx*1(JZ%Ix3@Fy>@TWn4yt?_NQZu)V3VCFfh(aHt~md1m3=($cX+j zc|Ir8XguqnfBU1hof9>(%rZwp)ToE&!&(iHKrg|ukvBw{SdY`qHlb23z9XN0Mh6v-E1kX$+G&3`Udp6yHq+^g}8hM^0 z&obmXhf)$zO(2Sd15qqd>yfB61ZoXNt)ZY|7m=^mYml*lQVO-YZ~!Cr08@}sLMQ_v zia1EOMB?u0a?-*X<64_SE$N)0b0Eud=#-EoIgB<)6N@}G$Pz}QdwTm_HHvg8FD{GIAj>jjS?Z$uX^t$(k#saVZIjQ8n`mM*d4&-Cb)iU^ zPM`kNyY9QS%x>F2gY#<0+dblh+G|WUn7m`M-9B-ubyp^!Vr$toe&RboBt2Il!Is>l zrHr)0NIPxSZg+HRrZuQ@{qX~j%AdOW;Kf98qe*gl*rJ7pe*LhO$MBYAo6KLXy+V%v zZ4%>SEwpqSt+qzeVq~d>)xsN`#xuMI#%S-I3oyINjKZ6;Z~*ZoJyHosRW?14LV`#j zs>1`Q1WVP}4pJ%DJ6Ym#vyCl7E=Du7cE$1`)iu~_PC^O)WiG}ig#roTrKKp;qBGDe zloHssV>23k0`nI(uKoljA zGAblxo@;2Wk>?tDmLtz~Ap!GLicUMn^hA1k|1iETAbG>O$@|5{ZUbm~YMRz>xXE-n zWAQ<&A93~sO(IFhm78kmi}sZJfdn&o8r~q!awMG$olc5QD^pp@9L2RKt-Z4E=pTLV zo}1tD-v=XY(J|AtY0=lXTOV-1VzqF^DcJJ(8_}F`>ROFsiC1%xn=F+oLy-o6OE0}*=qBJ}i2^bIQX55?#m5U4c-*jmcu@z zb>C=zeD`hBYmPc`@!FA*jfk-1fJAo?*9kfYqButsDM%#?;D@~JkjI_pPWt7kMbc)p zrZvX4Wy7_415zrU8sCcm%33|Npzo1P{bJGBjyslXI|(6#Ujpp_Byzx({cv17$3o`@ zS*nqx8fj`kkhVRe<u_qjX zn(RS4n?NUNB1tlI+8Nr-4DF^yYbwX|WQv)o6wT=r?WRVjrO|HYNZJ}n+aO5{vc&kN zPOgO5XfA#V!`2qWLFI8EGpVd@6@Zik5)K?n5rlLQIq@kOV0O`uhhkZ+?V0sv(MM5We!1z^(@(6LPHqOUQHztu5F$ zI?%a6mZu&(J|W)oFKijP&7n=^lIXokaVpUjBZ2@yLE<>6Lj<4s=%kwv?zNI?@Z~?+ z=TG}$M<)pkbnd_ss#5cuVKrd1gwYDtSR^_@mUNJ18h|>CMcXYrIoGdRs8LObD+te` z@k4jizxsY-gX+D16M6S}ASMN%JY|1Z15ycp7io}4;V?@jf8)!Pg$!y`KnMvbq_=w%q*Rc?*+4=_2ojJr zf!=zLd(M9jL9!6Jmc7v41+Ub5+0eeuREiQkFe>W7Xa@+Bgno&>Y)IR(a>J`xXV0OC z%3JF^HYTxeVP;>yE&!n{q;x7Gs0tD&8YTen5qnz+poYkM*}{dWV%E$`sxLzq#odCkbzOz< zt6W3DHW$24wa{=@F(OxTq74_({!qDE{axwg3X_N5&f^2eFnQ)W;pYs)`DRHqSf1%> z08y>BB~b*cy8^W#;vDj+$_xS^Po146XfFb&D2D+R97hrTuGk4&4Gje5)!$iF31tjJ zNW?+{*2G{Vb889YCl3r5VhBUfM1{c`R6`JY4m_1ool58;04bbkFqmgwQ{kRh2*Pl( zrAnxTABv~Ah|TU40Ijgog)tw(78UZalsaVy!%1ydm4S*$0545~Iu$}7js-@ODXeIy z`5qv}6_p8(W$-vmft~%H;*tr>zS$`6MF536cc%=#%9@0W438_sZCB9I8h1+@W7${@ zi5|eV0G8fE@}gIS?`05sgO&)!awRIib4Vk^%z_9CMsMk1(X0zY0fh28P`Qp>gz2l- z>~n#_xfT*P{hy!Xib_MXsD5K`MoxeG7QaIikNSd=gHv z>Q>GoLT48bFns)tHLMi?-+yz@J&J`@gO()9WUMYj4YL-v}lmb?LL zLBij$AdvrlSGwbq%a{v*bVakk*tEu8N$Xt}BPDN-mxatg0Qw0GkSc zXPX8UX%vFQ?&4gB52R&6996ExNv&Yd`Quo0sk0(w#2?BT(HV>d;;6Cr02IzS*bMGu zOF&g-vv_^>9J^NpY+=lWh6JTJ7qdhv3Ba;z*aA!bZ!e8d-aR{yie0vg1)Y6vZjsz= z+)0{9ItiA|I{_<}ACIl$H)G@I)rcaAMtuNmfKX;#+JWT}yHh(*sIS@22fHxLO_|>6 zRU0Z#`V^C3SB3Y03D^QK6GV}%=_m=oUf70UaV1K;Q(`~BPV(Cwc~S=(qR3av?lk~` zDokzRsLVq7tO@K|D9bRMRaB3+Uqp}=puT( z3!nXo5IZ%Mq|->!9E%5z!BZdh4>;<;r$7n?W{cZ5U5+bmITss8|AHtMXw>>aBwX=e zHC-ftDJ&SH*xRrhtd+oP7r?@NmLLf?TyYc3G9|Ft#p9IWZdzt&#;+?(cap$X?m(1c6qVmqbwLCWOAv*)l^oC}D|2H47-tK#E~C|Z zB85tD?z*7vMd`L{C~@F<*g!b@@J%Ev*;$lu8Z1cAd=J`RVj zcr4a!`~&{-w{PN}(W^j0qfsA#APMWlQujI9(oXBLY1|CDUTQntXr+T7gwKTB#obsO z0~R<0FeZfp!7@XTDh=ey_jZA17x$E_Hv?J2u*6WJXYT>X-R0iOs&uvpi{?&{3R@tY zSg?Tt1)yXd-~<3eMQR~L3Y~M|?pL=<+R3}~-%tLocCKvsp5o@*MG8jon8~YAgLX0w zs}&Afaw;Bi*jYGu*`vLE=YS(ff_w)Y2PDGbs~(TTS3MqgZ~H5*xaF(3bNl76=%7*S zhm;YRO`#gXF-s4v1Vh!sDnRC?Vo+bzh2Et}z|MBWd_T{{b%z_wd9U5@+(}RuCWvo) z!^XG>K(5oh2OzfKNcDh-+RSKMgSt0>DqKRhDl47}^-m}#%o%SCDMQvgy6%uJ@Puxv zeiDNXgzEQICZo&vEc_7XQE8K+lQa>DejL8^*?9P2XJO@{WBqrzP2;M-2_ukd0Z0cd zIROVOIRRV8*5S%qzJ}Yk{1(mj2paVPC>a;*_3S&`&t>JDsj!iX72bvBrK*JGa8AOB zt2+RCeEEVk210h56tk&^Dm`Jn>a3#ET80$&50BjjkQ5PCE;#`MeG8kLx8K?ng60|P zWkR`Lg+ARC4;1E$ytU^j|H7E#;-U(Kb$cNJu-%dg6~3t3ICP|<0E3WaZFJH$`s+(^ z;z2LMBi5XW`2(v8;4s(&=f1~mAT6DL7@q&Qk6?UyBd-42cX8vL7h$Tk8MU|vk?Qd+ zfo;VjoGndeNl3WsAp@9@smRnNSxXfsD6ZA;$q#*^@8-L|wirkOfEX4a*(J%l)p{3J zx+XI)_y7>s;=KnT5&%R7%bk+lq^2u(RhT^Xv%rPOvXH906~ob>MbLr0|*r45XL75EK4VvolLtePG1mvy_NF?_r4@3+L4Z|6_?C4-; z@T>){8h~AQRJT#-BIE*6%1z-p=8E>Jg2NlQAwWp}%1c9DV5U8R2!nXo0WZe!hdduE z7aw0%b9j$xcY=fu1V|<0YY?dz#~$(w9CPr~ao5(r;?K8!7i;gj6iGgc{=Q*=DrpoI z52-t;zbwQqZ=h}o1|}#e3u>U?<#u6!bLBle`$d25Qivq%08y{??qvXR4sFvSNy#l- zX{@@FC{zw*xRMYzy%%4UVHd@RgbDq>*}5=kSZTl^|BK&-P(b_{Ow!#?JxnxK+htyN9Q3=U3b=^p#r)+&~idi@jQ)}*gh^ufKmjd1mZ|}!m*O|;ODmp zOcU+2Rv}9<{Oxz0rjRl4_|p&Bn*g%N^A57S>8FRf)?_w;SmCV8yyLF-F^C`-8gW#I zQW1nuJGrU_Qv8>Tu49%7Qfb;ko@e;cr60o!&N%`=M(~o2TZS(GR>ACx1Ln-hq zo}oBt_kMB*k5*oLC(voA%ZmMlD!dK&W>KwiX>&>bQu_>N#;7YiOpn+lJiAd)1w!a$J>R*A6{ z92h%F(ESgTge4)%QyjSXQF!!`&f8kO_*=N_s_$dNhPC*>Ctr#mUi4+W;*7WA36Fi6 zS8eWiLhQXp{nqOa;VT-iz3xx=@_GM-tN!{cH2N)8AG!p`9q~lG=vlA9u}3}mCpG zEyfwAzXOkY*y*_Nx1Y!Lf4c5RAJFE^kg-Vf+1e&Fc5)ezSMoE$Z=nG~ybJ9S7JzMfV>E+amy3!-%37Q5?gA zy(FPfip}Z?hCjLt#4bb5B95y~B&jF?4jPgzfkXY3_xcKjR*+*MT;V3kvc>8ZN8ybx z{XDK)`&(Rm`RB1=(>2&K@;kikL%+u{hdvpveZ{}yh&4yM0HSrg(4GJ(^eqfD#NGF7 zz!$#yVO)9b&(JfJ;-I5@Ft2|lo_z8-c*) z(Kp(fg)AXlpMcCv_7bQk+`!gqNXYW@;ile&ksfYLtutt&K~O#>xqD8>9z^3Uq>La% zRN)!8xWH};pU}muR`hbQL>~D`(^K~qkDzePEAthy8bioL5cznGQ)*MK?f$c_%EEf1 z@`NK#!_kMFf~#))DK7o_ zZs0f&NGUNkHiGlN|3&=dm*+w>Cb9US2KxIKUIAEjQFd9PzkBjO;^k+&0rTc9D1cODzok@Y zw_Et;cmD_9`O)X0!szIB{NjpF;OD>oCZ6-uf5a=!egpdY`U?X&O%r_Qf^+e$?|lIi z?K`o2br0q(T!bT5KL*cu+-q?3VJ8CsLT9G?v!}vb*{W);HWaV8+5}l{C0<(3&?Xyk z^XOggkgec%Y%G%HD`a8e5m!i9YZ=4_E{t$2O z^z<{<9J?3~f7q#b)@iTBF>6lo*BRV+xyR9xV#_G&?!?08@>11F94ak?!o+dZKiPXZB$|=g>7X7};ZCF?xLWW)731-N0to*WdbU%#1TEH*n-(kHm|g`3@Yj=21HV=YfE@$fvRZWH$v8c(ibif&}#J#5494 zy21rMJw7UNLCiLAx@eDZFqc4P{Jv@cSo+WJUf_B6i4U?~)QQ3a>n5qn3!5F!D&sOJ zJpcxzkV9|%%O~q;;&N~8>|*~a!4^JS=<`a)(+9AA-D@d|3Jc2y2QEJvuRr69ICS;H zFmIW~vK0&Q#+QEv$E*glxP*GGEz&IUZnyi+(0-;+dtK_!AKiC1DJ?2NL=0_Po=*HEsmn-=P_|A>6*ZPl3e-(a+B3Mv$6y zmsP*JLXs6mV%0U>I}2N!FhV0Lw~|8aCFJ-M9U0r&<#d!ZS~m$xq#SrEQo0OjlmX>1 zM_q{z6{%DBErnVvUld--S?gQLzE4V5{sE+m!WAzXM+ z<<@VBWSM<~N*6wGWh5a2U-qjh=bnqyhrne}!71&X^(|)~MGKa_`rUpcX{W-zQ{lcd zN><**MJtJ|T$vLFR4gE+fVHf^5VNI55drbn5^T{Ts_zfd)z8QZSSt|9yzg)9Hh{kU z$A3g{q>D{qt8RR-M?&zfk}3(H3lv34thF#!m-^k?Rw320y!eXrsZ2lsRMFI6FOS)Y z?0a(*JPVhSx@go{srx6PDh4)p&9#z>YV{aOiKRqBAZ!rJC~odD&1cth6gqN*>x<$D zajXzUd)W&+^Ref;R&uWO98>5{S`aj)%QSm0tT4LuzLOkzmb#jE+0F5E5p6)1G%8|9 z;jj;Zgs7hJ-Ud&&BHz`w4BJ#_i;_R{woPRM!;}l5Dy{sem{Z2Air^x!TH%L+Gy{7t z)P1+48U$hx?!U1Du&4cj{G@WIVXmB9P}*H~QN=|qK3|z6YZwk%T=eXi(O&u5S?Ao4sxsw`m=xGcyxA0HEHpd*S#!Z0}N7`&=zGp6zyZsjUhb$lczY4G5gpnJPs6rz9ctFQ`}M!v?s+IPuIA4d|}QZfsKu(Zxi zJ_C4LtxCX#AhTs4lsM0d&2}5)BG`MT)o$m42)WMpE)NvW!c|qMdx~YGuJbDHq#!1{ zQX|W23Ubax zAQFoz4tCvCrEeO^wo>{Wz8|w(@yZQZJ%`}Bho%li$J*Vr3-(L`p{Nke0|`~ttwGdx zvB+M<%&z|mr#Cs8F`F7{abufzYaP)Py0{cyRc0L)HBPfiRrdO**cE%-6C)IjwYnOU zBG^L=Ky)RR6*=Q5DkwOdpO6)ad9R@F&ebZ0k9)b|0|kPBl)DFwJ>0Rdv{*$oYp(!H zkPyLJD^Iq_2P->b!CFAZVZ)PINAg~lltH2aT$14B-PLv6y*oky<1TCeALJlZcMmF$ zVQne3g^*CPjtn`hF;4n-)isst5o}EYoH-EIq>_YW#u~`I60fTAP7nUOtTn~;CuyrFMYf@NrvE!M&;o#5 zC$6z4E12AXSrqn?&Y9CTL#JYlh?s~(S7@hdN+3Kxn{E+^WF15)n2pJru;Wc2-#r_8 z&x~jy!Aix5RDF{tpUOZ>Fnnii=~#8t%DqA1)sTQrl>ctHs!RAgzmkvA)zhyy7kDbb zqF(FAEgOD~ORxBPi1NFw3id`3Ayf?|NB0~lHE%*0sH`>gd=$9EYGSX%_xx$Xw{ptm8!>ix%82s+?3*CMgUbjD(YSiG(JP-*KjvW&5uD|&z zyy0EX!Q0>e5+rF8e(#aOoemxN%ekt?8y(6dH6UdTaE;gbwwt#B6&>p0;o2?#*;YJ! zUe=DFbJA8v(76Dt1XzJt0xZESVXc6*5>^YhJ(jM+q;=bxNzm%-IQRE|`Z0cU*-vTd z@R7Z2`1Lhw>2a(7_rtJ_%UaVMlO4_)YK0X%4}ymvFa)wg5Eum6 z0kG~to<=}E-$r&-mb7ft?Cki)<4%6|4^KMoX(HwAX3M5+yLGL5WCKl%B>b~YpO#Y8 z6Q$~(>P*)^YiUL+8Apb5666byD-y^Wg0%#b6FM!6G!Z6GWt6lrl6Rs{+;Z(CZoTaa zB-sRNaX)HtuS;Gd1wz^6v6$ZqoiC^&>IKl~BP?Ax4+Db(xM%A%c>4#RgGV0sG`#%9 z@4&G~JrYF`AyKy%c`u_%J?xGOa~(`V)`Gy+ZTH~ZZ+#TM{O$K(kzvu2d8pL|q-6B; ztFG33LR8dEphad$US^9}^?*$s#!RBWw+~U?!Ko`x5`W(DhP=Oi;Ilh={f{RmCZ5=c z7uf#3Wrl@jW=+}{GFpRe&YY*L(>B4xA~nspnT&k<&dt}o=Df?U!&#>u!n)HyZ~yK= zV~-@z!ezZ^Pu9&PfBGK1`&H+E&ZNCxn;f-qdpb5!uh1r$&z+eXnp1@735%IY#`FYZ zdYmvlu58k*=UGR}>4`K+n)b|GY~A>RSDd28#ztXm0x1;__aBH_G}yIhRH@Z2ix0!Z zm)*;14T-)1g`ouz4mxZx4n1NCZrN}tUjLq_;NL%b4%Xj!tJ~hv8`}5h`cu{WyC2|$ zIw~n7Ca1>m$uGVeXTJ8)xcGPHVZq`)9C*-T3@=m|oUhP79HHJL%Q75WN}FH<7I#S{ zpQpHatovLXM~GsD*0fmCYh&3O7zM`G%V`TkWivm zf|UeY*~zwVm~7v9_KTnX#@i@3M9feX)DyIYvpBMCG!nc!pZ`7Yk| zQNt_VaWQ@R-!41nAK&@#@rm(?wL;-b=#TeM1MvxLpCIl$dEw;oBE{ z9zVJGtC((Y$D+maFfgRwi8@cUmOBWvX zy{YLPZ*R6Io?cV^eM&ZjYvL`yRwLJKo8`$J+T>qr)EfU&Q#92{rlrQXY0h-WXbWxi zSZ{--Kz6XZX0qFj=7RsBf-9*GAqffusTk4_q8O<6)G#o-3eyt_es$%S@axOJi|0J; zHF(jpUW<9d3+@w0)xc(TgnD`@C6c6#AOHO8_}+zI#P-qkSh`{XmaSd^RRffQ-_5X_ z1tx*ARi97t4AFP0T+^ zc3g(e0puZ55!`);cJVRPT}xg_`j9!up$L&+$pvav#E5Hk49+_clVfdMaLGsU^WS_O zFL=g3;f2qBHF_GoV74&U7GSAXvJN4>Ce8lQgmpYX0vKM}c^ z=9+@;?VC>^mP*#?!{;7vk3IO6%#`E0znv>odmd?>u+FtL)|$GC5K%uq@yvDVQU%nco2^{?HFpdW;o5-y~~!YUYDEp^6A!APO?!l+$wTrq@Y6jlyrdOF^arj zu7pYgxGH}e?VfadyA#Gon%H>PD296v#F@{13!e4#mmyLSjM0!%;r*X@Id0$nGaPil z(Rk-8E<#VE-+{j@@;cMUdIBs6|CoEbrh{a2XQR@Mu0;Hm1ztnP+glM=qNVuJ? zgN;|lxdIDaL!-6`Ruilduv&m@&ECCnt=O?`{N~Gkvh|qPK7w)g>f`Z??_b}2qkrki zsMQr}y&5y)j66>~RZ>S|kYRI$q;2t`*Zt;!LIA*n2xWZwy_ewKA3Fn+(_3-+sc$mZ z-t-In?Y8Ubuh*X|RxVpfD_#}C9RgC+t&%lvwkEWtHu`!N;r!2C1ps)|a<;GxNcQz@BJ9vJD=CP<#kSkC6U(}Sy8f4n9LE&JZlM<~>%-7+FSc)+ z#Am$(5C_g>D+e)u!2q^yz6&4v%**lPi@%H)KkE&c zX^o=Zr~x9ybvOSJKf36ATz2J8(9;{?;5Ez9+b>aTkOP_`zqf079z}Z=MhOfCr1W5+ z%6_fzCmDjnmP3+Ih4&&Dt+|tQ5Jl02OXn{|6h%U*_#uea?cR8ZGivUCeEQqxAZfB- z7M5WSR*|?dv*SJOY#UoNNl06$t*Vp>E-1n~ zIEJwuZLBzOJ`Ox=5JEC;x_Ub%$1*HlIv<0>F={$CVpb5i$bCka z)HK?=@B-x)Pu4=97xieN+wD3h2yXD$*bdr0a@XX%!PQ6Qy0b-_gz|O||MXi|&B^*b zC<(MTMwT!vv}J}Aq}J=)e8U*^TAe9lNho0~NOG}2AqAoeh(fhh{M=nqJX|%n$%jD7 z)+$oEuCBHEBFtZ?5!alAi)s?94qAx$3k+%vM-?a~3R}n3W%)yg4S_|s8V%V7mc2v@ z^2wIhWKG#c%ovMW-0O%~4Zz0eBpp35y)kMu8ef=f-?2rIl7oFKOlLPsa2|>==Mo42 zK6dUo$n%WqwO+QY7qvUhtDEhSRXL9vlDQPpR(KS2-R*@9aW8p0MIWKr$!AqbL;ym2 zTk9l3nmDac?{QKl?O3E8TW&ipT#shoUIk_FKcrZ68*JqJAr|9 z>PI750-Y0J71)y5I<^8PN=D z$ENQTj6Cb_oqtX%yJt#kBVih*uW$DfzaFZwPXNdmmw}+9GM!{bvZdd|QSaGNHgI0E z(~=^$TE#+1W#O7YMt+|$3u|1>g5!HiDMVp=&XB#xz^v^&fXaf0Bz7U4G*G^|z3>H; zBp6XFU`z>2AxfYTsuBB=qY8FeHI7@Pw7~6D9qce`EWi=i#Au}xe)r^5XL(auYqCb8 z_qm2={%AC0)`3w9_~z&4#`X#0q2D}WH^y&&b^}g(=EIPrZ5W#}5h-TAu@?8;WGz28 zNn5ejTC*V-YY8kNQHKx>NKyBJR|U2bfJ<9o_M67BW5kOLK9+#r3xe6z`V&c?Nbdd? zLi*wX_kFIXkpxJBNV)FwDuN)_bX3a7*Jwo`ir~2L2!MMGL?Dg;s3N_B{drj{z{c0P zTM45XN!mh|w```H#&V*RlGBaG!1I-o7i(?R}>d=CC#wM3#ue&y;GshB@EdZl!8+dW!}a3x^KJmp}5Sxn8n; z3qSzy@1J@R{&v^z5ve*>E_s;z?Vm5SfB6CU9UptfE1K<*_odnNDq}Myk|acgdaWP5 zjbSwE{ZJ|bkpq&kIT#*Hz7rWds6tKV&gA24;E1m0LK1t}aF3X}?H;B|!_i8oeGXL= zWm{kCK?Qbs;nr$xY$}Y+1Ve*B8zNPE@3q(e>HLKY7SQnEQZYRAe;r(+en9YE~KyG%o z>8&Q^huo#mYueZx#%8dbBF|GWG=uHsAo}!zc`GlPoZ6nvOixKc5o?=TW=4PS5`6kS zznkkND#ktuAOQHcPrU%SPBGNC3`)h=Ho7i)#;LE&M<+K7-*Da9^|!3Ma+snP4-7S^ zR+o?}*f0u`8i=Dl)S^DbQ3H{RT{8o6fkBaf;EMuS!VWp1)nEC1 z_um10)f^_55vdE%7*3&ehqElDq@8yfJ<%6bq`vjhH~;=R0Qkp$J)GjGA%+K+8)I{H zl4*b?KK-7{=XzKFU@L zl951fe~f{l273Ezs5O-1Xh?uaIb)YgR7oT{{Job@ryeS zzx!D)#o$r5$VQ)_TGVTD-C<^nzMe(+&$nDW*GsX>u}`@1_ch-81{ZJp2#j1=2)gVx*1HZ7m2P5Z4syJrR2PBGelSwT5zGhgd-=>G$x8{MG{s zQYaV$Ns!*7l10-c$MsbDLJEdbVao!)Ijy&|+~#r`Mr&kwhAc_ZX?M_Wr%2iIn_C`)t+P`Nogm8)&^OoVR8$t-B#v0cOI6j zW%s^Y2;fSAngpU6K}ZG>@%#SyeEp7Be-f>kAK?S9zi6(fd$-4a10X3GAOnVmRD`%D z5a$xsxCnTjSqMXr(q#d<3Qh8a9Tj99 zw5+#2?`4ky5s9gpu{n#ZKajEC07xi8UwqfBAL`o5&*g|VYp1Isc zw}A^F+?L`H*1OfpRf$MNh$8_D32P;wgxq{*hLfMZM4o*5LY`?gdBM<1 zn4kXew}Xh|#m4QsWh_JG1f4Tf1mvlO)~-=x=zw9ZYt3g(WtX3jyG4L8 zFbkL0aQC`tbHuU7*ulO8+GMEJ+!S#p*zM`z4eJV*6oUI9%P_>qL}`G-XLG}c@L&rb zs*;vM;Jvwv;{V0ie*jeJxF)3wa=HXA0n*kPx`H7iKt;l*tvYFBa<~{)=)Y_L5t7Q_ zDkLm9rkVuszSmy3)A8T^p>se^oRvV4PBjUCKEfxIiAtcADrHB$fTWD2$uf=x_{iL> zz0&sevEKlwtE-0~XKyHX+e#&&GnevVwAerArzU3eXuN&wRJ9kdgr^N^Atvy)K{-lB1}Oh-=$i{tr>e1#)|d zm6?g5jK>+)}5mlA0|8v6}^;1>^ZnNaU4IzuKq+&+C= zmJWya3BkxSfUSj8&Kon409k^urKfaXZCuK}lU&+3UTsCOQ&lPwh4djIoRN%K#e?ih ziGL)(AKV$y^P*7pH`&GEdKA*Yp$3sqz1i)Mv+Ab$26d;mITQ%+{cumYf zV(dKJBD4Qa<-ihDmX|(CIpbbP^0i^zpkx7%6(9=RF?st31WytCKO5+w8X=4^d>B9i zT$J?y2;EDqD5|TRt4`z!6D1&-Tn1w9!V5xs4@pD-b^Mk}_FlJobn45IIDvJJA_1YC z3X>i@!448cU7S$Z+@t`Lclm9Qq^^sSPea*%#{L5!4~|F^gz&-g$_P6*mra{olY*k` zSpX_>;S4DS+&Ym@XC*{Y1R{n~_XZ%qZFyy(B8e!H9yH`@??r{13hsPm>m+|(f*6*m zu%lR0X|D-@_Ox~P9FP45K+M30zjnHK=ZDU)0F98KP~BX*$pJ)ye7zMF3H6rTYbtV$ zyMuiqs4f5?%aSQ=GKfg+(hm|6fY1P2L{W?=j-9KnN{>twuDrK@X1Amvz-VtMS2!Rc z2!;({fhdZ1b4K=!vEKlQpwQRXL$QiLK#L0g*2Bhw2EuQhiEb6=Y$3N`QU@0ttf)>z zLeI3urx^yM>bpL^uwcr;uvRGrr6d8?yX~SPg+xIt7FF*AAB%I6&~+hm=WJoX%w}q4 z1X2-t8_VZPYKiooD)LdZ-?6_dzWNxhbN_kMS_W$ zyTO!i>8mZ>+K3jQ7RS3(VOr;W?2)J7)W@8@39xrYaRd^?uDn@5MJ^IwfQS5!%HeO} z-Y29em_sRI7@LEHzRqw8ki}Gc`&>`;9*zA5K(Bh{*U)KePTN4z;veWtz*^S}IP?Sx z-dMSzo$rcKDZdG}2?+tVMkm=6qL?m-2S+-+3#R1Y@Zc^1lyi%Jbn$1^SHJtwoRt1X zqftj(QznX(k7-dM*@6KrJZPlP7jkJHt~pf{NjuZtrkb72+l0aoi7ZqM(^p?G*HgVm zW4}>hU;gjxqakPVKo0~!SKQ7XSqB(j#Wk^V`Ea!<)CPV;v|r8ypM9pXPOC8 zSXi=#D2?I>+eKXegs&m9W7{TndHh)RA+NX0K`R~uYxJj^$<`Mli;l0?hH@z>GMp9Q zlp!ZbNM8mmioT9oYvj4+EYT*-W`vCB!@~>eqX5aQBh1wFmbsqlJsSHBfY>q?E$zqn z_<`Kpb0B&f(Hmx(1bv%&HHD_sVSa&GnsVIu0Pg*_xIg{4K5l0_x{(9Bl@Qd%Ro9n6Gqp@Gn zp8s*~i@>G^CrmcTPgAT`c zKD&GEb@!FA-`GF^&}nImPmBOyTk8?x`gK1YdHUnu{}g7tddJxMjhnWvl`}I_QrL#9 zi3Oq&Eux-yA=TBOkRq13PE|V@PtttiOWI5w!<1fTa>zVSOL1copgLM(-Y@0 zwI3#>_zba9Qo(kbIp*~rv)_RS*v}*o0KD(BFT{@V^Hmaz{GKH@5tC) zPcgMRWqZ5U$*=Of^|Mae*%HeEVT~msX#l{O4Bz?8ZTEZp zfBW3i(QI!6gP~+iq*)UO95iSj@yJKfML)gtXhQr%rRs-As))DK{jG5Mw}?_4!K zv;FsdJp&VL>(pv?gtgi@S6|?Z@4J4kr}hDj{SH6?@Xr5wCMKI(5JwG28DVOAt7^Ar zOlv0PE6$&XvGg{);sZxTJwnZ!n#pFq^|8OT*RDMqM;voLRzD6n?U5%*Z8|PC?kh^a z`qArm`}iL|_c@qqZbPJM5JI7oOsYK3EeMuC_|!YP8$P}F^Jn2vM|~Dgf5JSx{l8C@ z+O$~+X^9lFtc}mS>zcWq(g!^DO8|xOy7!#~Yja2$fte}G+cM8{u&EiXQ||9ugn5I9 z0AOk+n`Ew=0IdDu2d=hH{72yM6(>WA7@z(3%O242-}|N0kmXHSYanF|W-9<8q^KiO z16+%S*>F>6-Jx73oac#Yh(V49dN4D&6+|)q^Nqiq>uG#Y - - diff --git a/mobicore/TuiService/res/menu/tui_manager.xml b/mobicore/TuiService/res/menu/tui_manager.xml deleted file mode 100644 index d227c49..0000000 --- a/mobicore/TuiService/res/menu/tui_manager.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values-v11/styles.xml b/mobicore/TuiService/res/values-v11/styles.xml deleted file mode 100644 index 5f7ad80..0000000 --- a/mobicore/TuiService/res/values-v11/styles.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values-v14/styles.xml b/mobicore/TuiService/res/values-v14/styles.xml deleted file mode 100644 index f20e015..0000000 --- a/mobicore/TuiService/res/values-v14/styles.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values/attrs.xml b/mobicore/TuiService/res/values/attrs.xml deleted file mode 100644 index 50e474b..0000000 --- a/mobicore/TuiService/res/values/attrs.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values/colors.xml b/mobicore/TuiService/res/values/colors.xml deleted file mode 100644 index 5841565..0000000 --- a/mobicore/TuiService/res/values/colors.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - #66000000 - #fafafa - #fafafa - #5b5b5b - #5b5b5b - #fafafa - #FFFFFF - - #00A9E0 - #81B2D7 - #0C6CB1 - #237AB1 - #AAACAB - #EFEFEF - #CFCFCF - #615F5F - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values/dimens.xml b/mobicore/TuiService/res/values/dimens.xml deleted file mode 100644 index dc72173..0000000 --- a/mobicore/TuiService/res/values/dimens.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - 16dp - 16dp - - - 600px - 1024px - 168px - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values/strings.xml b/mobicore/TuiService/res/values/strings.xml deleted file mode 100644 index 6eb8407..0000000 --- a/mobicore/TuiService/res/values/strings.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - tuiService - Dummy Button - DUMMY\nCONTENT - TuiManager - Settings - Start/Stop - Start - Stop - TUI service is running! - TUI service is not running! - Secured by Trustonic! - - \ No newline at end of file diff --git a/mobicore/TuiService/res/values/styles.xml b/mobicore/TuiService/res/values/styles.xml deleted file mode 100644 index 1e866d5..0000000 --- a/mobicore/TuiService/res/values/styles.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/mobicore/TuiService/src/com/trustonic/tuiservice/BuildTag.java b/mobicore/TuiService/src/com/trustonic/tuiservice/BuildTag.java deleted file mode 100644 index 5f3f0c8..0000000 --- a/mobicore/TuiService/src/com/trustonic/tuiservice/BuildTag.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -package com.trustonic.tuiservice; -public interface BuildTag { - public static final String BUILD_TAG = "t-base-EXYNOS64-Android-310B-V006-20160331_140301_7136"; -} diff --git a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiActivity.java b/mobicore/TuiService/src/com/trustonic/tuiservice/TuiActivity.java deleted file mode 100644 index dfdc2e5..0000000 --- a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiActivity.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -package com.trustonic.tuiservice; - -import com.trustonic.tuiapi.TUI_Event; -import com.trustonic.tuiapi.TUI_EventType; -import com.trustonic.util.tLog; - -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.app.Activity; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Matrix; -import android.graphics.drawable.BitmapDrawable; -import android.view.MotionEvent; -import android.view.View; -import android.view.WindowManager; -import android.widget.ImageView; -import android.widget.LinearLayout; - -public class TuiActivity extends Activity { - - private static final String TAG = TuiActivity.class.getSimpleName(); - - private LinearLayout mainView; - private PerformActionInBackground mTuiHandler; - - @Override - protected void onCreate(Bundle savedInstanceState) { - android.util.Log.i(TAG, BuildTag.BUILD_TAG); - super.onCreate(savedInstanceState); - tLog.d(TAG, "onCreate()"); - setContentView(R.layout.activity_tui); - - mTuiHandler = new PerformActionInBackground(); - TuiTlcWrapper.setHandler(mTuiHandler); - - try { - mainView = (LinearLayout) findViewById(R.id.tuiLayout); - mainView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); - } catch (Exception e) { - e.printStackTrace(); - } - TuiTlcWrapper.setIsActivityCreated(true); - } - - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - if(hasFocus) { - tLog.d(TAG, "Focus gained"); - synchronized(TuiTlcWrapper.getStartSignal()){ - TuiTlcWrapper.setIsActityAlive(true); - TuiTlcWrapper.getStartSignal().notify(); - } - } else { -// tLog.d(TAG, "Focus lost"); -// synchronized(TuiTlcWrapper.getFinishSignal()){ -// TuiTlcWrapper.getFinishSignal().notify(); -// } - } - } - - @Override - protected void onDestroy() { - tLog.d(TAG, "onDestroy()"); - super.onDestroy(); - - TuiTlcWrapper.setIsActivityCreated(false); - TuiTlcWrapper.setIsActityAlive(false); - synchronized(TuiTlcWrapper.getFinishSignal()){ - TuiTlcWrapper.getFinishSignal().notify(); - } - } - - @Override - public void onBackPressed() { - // Cancel the TUI session when the back key is pressed during a TUI - // session - final TUI_Event cancel = new TUI_Event(TUI_EventType.TUI_CANCEL_EVENT); - if(!TuiTlcWrapper.notifyEvent(cancel.getType())) { - tLog.e(TAG, "notifyEvent failed!"); - } - } - - /* - * Handler that receives messages from the TimerTask, to adapt the UI. - */ - class PerformActionInBackground extends Handler { - - @Override - public void handleMessage(Message msg) { - switch(msg.what){ - case TuiTlcWrapper.CLOSE_SESSION: - tLog.d(TAG, " handle message CLOSE_SESSION"); - // Call the finish method to close the activity - finish(); - /* Remove the animation when the activity is finished */ - overridePendingTransition(0, 0); - break; - - default: - tLog.d(TAG, " handle unknown message"); - break; - } - } - } -} diff --git a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiService.java b/mobicore/TuiService/src/com/trustonic/tuiservice/TuiService.java deleted file mode 100644 index 12acfca..0000000 --- a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiService.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -package com.trustonic.tuiservice; - -import com.trustonic.tuiapi.TUI_Event; -import com.trustonic.tuiapi.TUI_EventType; -import com.trustonic.util.tLog; - -import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Bundle; -import android.os.IBinder; -import android.telephony.TelephonyManager; - -public class TuiService extends Service{ - private static final String TAG = TuiService.class.getSimpleName(); - - @Override - public IBinder onBind(Intent intent) { - // TODO Auto-generated method stub - return null; - } - - // Executed if the service is not running, before OnStartCommand - @Override - public void onCreate() - { - tLog.d(TAG, "onCreate!!"); - TuiTlcWrapper.init(this); - - IntentFilter filter = new IntentFilter(); - Intent screenIntent = new Intent(Intent.ACTION_SCREEN_OFF); - Intent batteryIntent = new Intent(Intent.ACTION_BATTERY_LOW); - filter.addAction(screenIntent.getAction()); - filter.addAction(batteryIntent.getAction()); - filter.addAction("android.intent.action.PHONE_STATE"); - registerReceiver(mReceiver, filter); - - } - - // Executed each time startservice is called - @Override - public int onStartCommand(Intent intent, int flags, int startId) - { - tLog.d(TAG, "onStartCommand!!"); - return Service.START_STICKY; - } - - private BroadcastReceiver mReceiver= new BroadcastReceiver() { - - @Override - public void onReceive(Context context, Intent intent) { - - Runnable notifyEvent = new Runnable() { - public void run() { - final TUI_Event cancel = new TUI_Event(TUI_EventType.TUI_CANCEL_EVENT); - if(!TuiTlcWrapper.notifyEvent(cancel.getType())) { - tLog.e(TAG, "notifyEvent failed!"); - } - } - }; - - if (TuiTlcWrapper.isSessionOpened()) { - - if((intent.getAction() == Intent.ACTION_SCREEN_OFF)){ - tLog.d(TAG,"event screen off!"); - TuiTlcWrapper.acquireWakeLock(); - notifyEvent.run(); - } - if(intent.getAction() == "android.intent.action.PHONE_STATE"){ - Bundle bundle = intent.getExtras(); - if(bundle != null){ - if(bundle.getString(TelephonyManager.EXTRA_STATE). - equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){ - tLog.d(TAG,"event incoming call!"); - notifyEvent.run(); - } - } - } - if((intent.getAction() == Intent.ACTION_BATTERY_LOW)){ - tLog.d(TAG,"event battery low!"); - /* TODO: get the battery level and only send a cancel event - * if this level is below a threshold that will be defined */ - notifyEvent.run(); - } - } - } - }; -} diff --git a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiServiceAutoStart.java b/mobicore/TuiService/src/com/trustonic/tuiservice/TuiServiceAutoStart.java deleted file mode 100644 index 48bec0e..0000000 --- a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiServiceAutoStart.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -package com.trustonic.tuiservice; - -import com.trustonic.util.tLog; - -import android.app.ActivityManager; -import android.app.ActivityManager.RunningServiceInfo; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import com.trustonic.tuiservice.TuiService; - -public class TuiServiceAutoStart extends BroadcastReceiver { - private static final String TAG = TuiServiceAutoStart.class.getSimpleName(); - - @Override - public void onReceive(Context context, Intent intent) { - - if (this.isServiceRunning(context)) { - tLog.d(TAG, "Start of service is not necessary, it is already running"); - return; - } - - Intent service = new Intent(context, TuiService.class); - context.startService(service); - } - - private boolean isServiceRunning(Context context) { - - ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); - for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) - if ("com.trustonic.tuiservice.TuiService".equals(service.service.getClassName())) - return true; - - return false; - } - -} diff --git a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiTlcWrapper.java b/mobicore/TuiService/src/com/trustonic/tuiservice/TuiTlcWrapper.java deleted file mode 100644 index f436416..0000000 --- a/mobicore/TuiService/src/com/trustonic/tuiservice/TuiTlcWrapper.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ - -package com.trustonic.tuiservice; - -import java.util.LinkedList; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.trustonic.tuiservice.TuiActivity.PerformActionInBackground; -import com.trustonic.util.tLog; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -//import android.os.Build; -//import android.util.DisplayMetrics; -import android.os.PowerManager; -//import android.view.Surface; - -public class TuiTlcWrapper { - private static final String TAG = TuiTlcWrapper.class.getSimpleName(); - -// public static final int INIT_SESSION = 1; - public static final int CLOSE_SESSION = 2; - - private static Context context = null; - private static PerformActionInBackground handler = null; - private static final Object sessionSignal = new Object(); - private static final Object startSignal = new Object(); - private static final Object finishSignal = new Object(); - private static boolean sessionOpened = false; - private static AtomicBoolean isActityAlive = new AtomicBoolean(); - private static AtomicBoolean isActivityCreated = new AtomicBoolean(); - - private static PowerManager pm; - private static PowerManager.WakeLock wl; - - - public static boolean isSessionOpened() { - synchronized (sessionSignal) { - return sessionOpened; - } - } - public static void setSessionOpened(boolean sessionOpened) { - synchronized (sessionSignal) { - TuiTlcWrapper.sessionOpened = sessionOpened; - } - } - - public static Object getStartSignal() { - return startSignal; - } - public static Object getFinishSignal() { - return finishSignal; - } - - public static PerformActionInBackground getHandler() { - return handler; - } - public static void setHandler(PerformActionInBackground handler) { - TuiTlcWrapper.handler = handler; - } - - public static void setIsActityAlive(boolean status) { - TuiTlcWrapper.isActityAlive.set(status); - } - - public static void setIsActivityCreated(boolean status) { - TuiTlcWrapper.isActivityCreated.set(status); - } - - public static boolean startTuiSession(){ - - try { - synchronized (startSignal) { - /* create activities */ - Intent myIntent = new Intent(context, TuiActivity.class); - myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_DEBUG_LOG_RESOLUTION - | Intent.FLAG_ACTIVITY_NO_ANIMATION); - context.startActivity(myIntent); - /* Wait activity created*/ - startSignal.wait(5000); - if( ! TuiTlcWrapper.isActityAlive.get()) { - tLog.d(TAG, "ERROR ACTIVITY timout"); - finishTuiSession(); - return false; - } - } - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - /* Enable cancel events catching */ - synchronized (sessionSignal) { - TuiTlcWrapper.sessionOpened = true; - } - - return true; - } - - public static void acquireWakeLock() { - /* Ensure that CPU is still running */ - try { - wl.acquire(); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - public static void finishTuiSession(){ - tLog.d(TAG, "finishTuiSession!"); - if(TuiTlcWrapper.isActivityCreated.get()) { - /* Disable cancel events catching */ - synchronized (sessionSignal) { - TuiTlcWrapper.sessionOpened = false; - } - - try{ - synchronized (finishSignal) { - /* Send a message to the activity UI thread */ - handler.sendMessage(handler.obtainMessage(CLOSE_SESSION)); - /* Wait activity closed */ - finishSignal.wait(5000); - if(TuiTlcWrapper.isActivityCreated.get()) { - tLog.d(TAG, "ERROR ACTIVITY timout"); - } - } - }catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - } - } - try { - if (wl.isHeld()) { - wl.release(); - } - } catch (Exception e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - } - } - - - /* Initialize static members */ - public static void init(Context ctxt) { - /* Save context */ - context = ctxt; - - pm = (PowerManager) ctxt.getSystemService(Context.POWER_SERVICE); - wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TuiService"); - - /* Start the TlcTui native thread */ - startTlcTui(); - } - - /* Native functions */ - public static native int startTlcTui(); - public static native boolean notifyEvent(int eventType); - - /** - * this is used to load the library on application startup. The - * library has already been unpacked to the app specific folder - * at installation time by the package manager. - */ - static { - System.loadLibrary("Tui"); - } -} diff --git a/mobicore/common/DrSecureStorage/dci.h b/mobicore/common/DrSecureStorage/dci.h new file mode 100644 index 0000000..c805f5c --- /dev/null +++ b/mobicore/common/DrSecureStorage/dci.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * @file dci.h + * @brief Contains DCI (Driver Control + * Interface) definitions and data structures + * + */ + +#ifndef __DCI_H__ +#define __DCI_H__ + + +typedef uint32_t dciCommandId_t; +typedef uint32_t dciResponseId_t; +typedef uint32_t dciReturnCode_t; + +/**< Responses have bit 31 set */ +#define RSP_ID_MASK (1U << 31) +#define RSP_ID(cmdId) (((uint32_t)(cmdId)) | RSP_ID_MASK) +#define IS_CMD(cmdId) ((((uint32_t)(cmdId)) & RSP_ID_MASK) == 0) +#define IS_RSP(cmdId) ((((uint32_t)(cmdId)) & RSP_ID_MASK) == RSP_ID_MASK) + +/** + * Return codes of driver commands. + */ +#define RET_OK 0 +#define RET_ERR_UNKNOWN_CMD 1 +#define RET_ERR_NOT_SUPPORTED 2 +#define RET_ERR_INTERNAL_ERROR 3 +/* ... add more error codes when needed */ + +/** + * DCI command header. + */ +typedef struct{ + dciCommandId_t commandId; /**< Command ID */ +} dciCommandHeader_t; + +/** + * DCI response header. + */ +typedef struct{ + dciResponseId_t responseId; /**< Response ID (must be command ID | RSP_ID_MASK )*/ + dciReturnCode_t returnCode; /**< Return code of command */ +} dciResponseHeader_t; + +#endif // __DCI_H__ diff --git a/mobicore/common/DrSecureStorage/drError.h b/mobicore/common/DrSecureStorage/drError.h new file mode 100644 index 0000000..d686bc1 --- /dev/null +++ b/mobicore/common/DrSecureStorage/drError.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * @file drError.h + * @brief Error id definitions + * + */ + +#ifndef __DRERROR_H__ +#define __DRERROR_H__ + +/** + * Driver fatal error codes. + */ +typedef enum { + E_DR_OK = 0, /**< Success */ + E_DR_IPC = 1, /**< IPC error */ + E_DR_INTERNAL = 2, /**< Internal error */ + /* ... add more error codes when required */ +} drError_t; + + +#endif // __DRERROR_H__ + + diff --git a/mobicore/common/DrSecureStorage/drSecureStorage_Api.h b/mobicore/common/DrSecureStorage/drSecureStorage_Api.h new file mode 100644 index 0000000..0ca7549 --- /dev/null +++ b/mobicore/common/DrSecureStorage/drSecureStorage_Api.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * @file drSecureStorage_Api.h + * @brief Contains DCI command definitions and data structures + * + */ + +#ifndef __DRTEMPLATEAPI_H__ +#define __DRTEMPLATEAPI_H__ + +#include "dci.h" +#include "tee_internal_api.h" + + +#define RW_DATA_SIZE 4096 + +/** + * Command ID's for communication + * FSD <--> STH + */ + +#define STH_MESSAGE_TYPE_LOOK 0 +#define STH_MESSAGE_TYPE_READ 1 +#define STH_MESSAGE_TYPE_WRITE 2 +#define STH_MESSAGE_TYPE_DELETE 3 + +#define CMD_ST_SYNC 5 +#define NOTIFY_DCIH 6 +#define NOTIFY_IPCH 7 +/*... add more command ids when needed */ + +#define STH_PUBLIC_FILE_NAME_SIZE 20 + +typedef struct { + uint32_t status; + uint8_t type; + uint8_t reserved0; + uint16_t flags; + uint32_t payloadLen; + TEE_UUID uuid; + unsigned char filename[STH_PUBLIC_FILE_NAME_SIZE]; + unsigned char payload[]; +} STH_FSD_message_t; + +typedef struct +{ + char header[5]; + unsigned char version; + uint16_t cryptoLen; + uint32_t dataLen; +}FSD_plaintext; + +/** + * command message. + * + * @param len Lenght of the data to process. + * @param data Data to be processed + */ +typedef struct { + dciCommandHeader_t header; /**< Command header */ + uint32_t len; /**< Length of data to process */ +} cmd_t; + + +/** + * Response structure + */ +typedef struct { + dciResponseHeader_t header; /**< Response header */ + uint32_t len; +} rsp_t; + +/** + * DCI message data. + */ +typedef struct { + union { + cmd_t command; + rsp_t response; + }; + + STH_FSD_message_t sth_request; +} dciMessage_t; + +/** + * Driver UUID. Update accordingly after reserving UUID + */ +#define DRV_STH_UUID { { 0x07, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } + + +#endif // __DRTEMPLATEAPI_H__ diff --git a/mobicore/common/DrSecureStorage/tee_internal_api.h b/mobicore/common/DrSecureStorage/tee_internal_api.h new file mode 100644 index 0000000..05119a3 --- /dev/null +++ b/mobicore/common/DrSecureStorage/tee_internal_api.h @@ -0,0 +1,1109 @@ +/* + * Copyright (c) 2012 Trusted Logic Mobility SAS. + * All Rights Reserved. + * + * The present software is the confidential and proprietary information of + * Trusted Logic Mobility SAS. You shall not disclose the present software + * and shall use it only in accordance with the terms of the license + * agreement you entered into with Trusted Logic Mobility SAS. + * "Trusted Logic" is a registered trademark of Trusted Logic SAS. + * This software may be subject to export or import laws in certain + * countries. + */ + +//TODO: Remove functions that are not provided in potato release + +#ifndef __TEE_INTERNAL_API_H__ +#define __TEE_INTERNAL_API_H__ + +typedef uint32_t TEE_Result; + +#define TEE_SUCCESS ((TEE_Result)0x00000000) + +/** + * Generic error code : Generic error + **/ +#define TEE_ERROR_GENERIC ((TEE_Result)0xFFFF0000) + +/** + * Generic error code : The underlying security system denies the access to the + * object + **/ +#define TEE_ERROR_ACCESS_DENIED ((TEE_Result)0xFFFF0001) + +/** + * Generic error code : The pending operation is cancelled. + **/ +#define TEE_ERROR_CANCEL ((TEE_Result)0xFFFF0002) + +/** + * Generic error code : The underlying system detects a conflict + **/ +#define TEE_ERROR_ACCESS_CONFLICT ((TEE_Result)0xFFFF0003) + +/** + * Generic error code : Too much data for the operation or some data remain + * unprocessed by the operation. + **/ +#define TEE_ERROR_EXCESS_DATA ((TEE_Result)0xFFFF0004) + +/** + * Generic error code : Error of data format + **/ +#define TEE_ERROR_BAD_FORMAT ((TEE_Result)0xFFFF0005) + +/** + * Generic error code : The specified parameters are invalid + **/ +#define TEE_ERROR_BAD_PARAMETERS ((TEE_Result)0xFFFF0006) + +/** + * Generic error code : Illegal state for the operation. + **/ +#define TEE_ERROR_BAD_STATE ((TEE_Result)0xFFFF0007) + +/** + * Generic error code : The item is not found + **/ +#define TEE_ERROR_ITEM_NOT_FOUND ((TEE_Result)0xFFFF0008) + +/** + * Generic error code : The specified operation is not implemented + **/ +#define TEE_ERROR_NOT_IMPLEMENTED ((TEE_Result)0xFFFF0009) + +/** + * Generic error code : The specified operation is not supported + **/ +#define TEE_ERROR_NOT_SUPPORTED ((TEE_Result)0xFFFF000A) + +/** + * Generic error code : Insufficient data is available for the operation. + **/ +#define TEE_ERROR_NO_DATA ((TEE_Result)0xFFFF000B) + +/** + * Generic error code : Not enough memory to perform the operation + **/ +#define TEE_ERROR_OUT_OF_MEMORY ((TEE_Result)0xFFFF000C) + +/** + * Generic error code : The service is currently unable to handle the request; + * try later + **/ +#define TEE_ERROR_BUSY ((TEE_Result)0xFFFF000D) + +/** + * Generic error code : security violation + **/ +#define TEE_ERROR_SECURITY ((TEE_Result)0xFFFF000F) + +/** + * Generic error code : the buffer is too short + **/ +#define TEE_ERROR_SHORT_BUFFER ((TEE_Result)0xFFFF0010) + +/** + * Generic error code : the operation is not terminated + **/ +#define TEE_PENDING ((TEE_Result)0xFFFF2000) + +/** + * Generic error code : A timeout occurred + **/ +#define TEE_ERROR_TIMEOUT ((TEE_Result)0xFFFF3001) + +/** + * Generic error code : Overflow + **/ +#define TEE_ERROR_OVERFLOW ((TEE_Result)0xFFFF300F) + +/*------------------------------------------------------------------------------ + Communication Error Codes +------------------------------------------------------------------------------*/ + +/** + * Generic communication error + **/ +#define TEE_ERROR_COMMUNICATION ((TEE_Result)0xFFFF000E) + +/** + * Error of communication: The target of the connection is dead + **/ +#define TEE_ERROR_TARGET_DEAD ((TEE_Result)0xFFFF3024) + +/*------------------------------------------------------------------------------ + Storage Error Codes +------------------------------------------------------------------------------*/ + +/** File system error code: not enough space to complete the operation. */ +#define TEE_ERROR_STORAGE_NO_SPACE ((TEE_Result)0xFFFF3041) + +/*------------------------------------------------------------------------------ + Crypto error codes +------------------------------------------------------------------------------*/ +#define TEE_ERROR_MAC_INVALID ((TEE_Result)0xFFFF3071) + +#define TEE_ERROR_SIGNATURE_INVALID ((TEE_Result)0xFFFF3072) + +/*------------------------------------------------------------------------------ + Date error codes +------------------------------------------------------------------------------*/ +#define TEE_ERROR_TIME_NOT_SET ((TEE_Result)0xFFFF5000) + +#define TEE_ERROR_TIME_NEEDS_RESET ((TEE_Result)0xFFFF5001) + + +/** Definition of an UUID (from RFC 4122 http://www.ietf.org/rfc/rfc4122.txt) */ +typedef struct +{ + uint32_t timeLow; + uint16_t timeMid; + uint16_t timeHiAndVersion; + uint8_t clockSeqAndNode[8]; +} TEE_UUID; + +/** Type definition for a TEE Identity */ +typedef struct TEE_Identity +{ + uint32_t login; + TEE_UUID uuid; +} TEE_Identity; + +typedef uint32_t S_HANDLE; + +#define S_VAR_NOT_USED(variable) do{(void)(variable);}while(0); + +#define OUT +#define IN + +#define TEE_EXPORT +#define TA_EXPORT + + +/*--------------------------------------------------------- + Common type definition +---------------------------------------------------------*/ + +typedef union +{ + + struct + { + void* buffer; + size_t size; + } memref; + + struct + { + uint32_t a; + uint32_t b; + } value; + +} +TEE_Param; + +typedef S_HANDLE TEE_TASessionHandle; +typedef S_HANDLE TEE_PropSetHandle; +typedef S_HANDLE TEE_ObjectHandle; +typedef S_HANDLE TEE_ObjectEnumHandle; +typedef S_HANDLE TEE_OperationHandle; + +#define TEE_HANDLE_NULL ((S_HANDLE)0) + +#define TEE_PARAM_TYPES(t0,t1,t2,t3) ((t0) | ((t1) << 4) | ((t2) << 8) | ((t3) << 12)) +#define TEE_PARAM_TYPE_GET(t, i) (((t) >> (i*4)) & 0xF) + +typedef enum { + TEE_DATA_SEEK_SET, + TEE_DATA_SEEK_CUR, + TEE_DATA_SEEK_END + } TEE_Whence; + +typedef struct TEE_Time +{ + uint32_t seconds; + uint32_t millis; +} TEE_Time; + +typedef struct { + uint32_t algorithm; + uint32_t operationClass; + uint32_t mode; + uint32_t digestLength; + uint32_t maxKeySize; + uint32_t keySize; + uint32_t requiredKeyUsage; + uint32_t handleState; + } TEE_OperationInfo; + + +typedef enum { + TEE_MODE_ENCRYPT, + TEE_MODE_DECRYPT, + TEE_MODE_SIGN, + TEE_MODE_VERIFY, + TEE_MODE_MAC, + TEE_MODE_DIGEST, + TEE_MODE_DERIVE + } TEE_OperationMode; + + +typedef struct { + uint32_t attributeID; + union + { + struct + { + void* buffer; + size_t length; + }ref; + struct + { + uint32_t a, b; + }value; + }content; + } TEE_Attribute; + +typedef struct { + uint32_t objectType; + uint32_t objectSize; + uint32_t maxObjectSize; + uint32_t objectUsage; + uint32_t dataSize; + uint32_t dataPosition; + uint32_t handleFlags; + } TEE_ObjectInfo; + + +/*------------------------------------------------------------------------------ + Constants +------------------------------------------------------------------------------*/ + +#define TEE_TIMEOUT_INFINITE 0xFFFFFFFF + +/* Login types */ +#define TEE_LOGIN_PUBLIC 0x00000000 +#define TEE_LOGIN_USER 0x00000001 +#define TEE_LOGIN_GROUP 0x00000002 +#define TEE_LOGIN_APPLICATION 0x00000004 +#define TEE_LOGIN_APPLICATION_USER 0x00000005 +#define TEE_LOGIN_APPLICATION_GROUP 0x00000006 +#define TEE_LOGIN_TRUSTED_APP 0xF0000000 + +/* Parameter types */ +#define TEE_PARAM_TYPE_NONE 0x0 +#define TEE_PARAM_TYPE_VALUE_INPUT 0x1 +#define TEE_PARAM_TYPE_VALUE_OUTPUT 0x2 +#define TEE_PARAM_TYPE_VALUE_INOUT 0x3 +#define TEE_PARAM_TYPE_MEMREF_INPUT 0x5 +#define TEE_PARAM_TYPE_MEMREF_OUTPUT 0x6 +#define TEE_PARAM_TYPE_MEMREF_INOUT 0x7 + +#define TEE_MEMORY_ACCESS_READ 0x00000001 +#define TEE_MEMORY_ACCESS_WRITE 0x00000002 +#define TEE_MEMORY_ACCESS_ANY_OWNER 0x00000004 + +#define TEE_ORIGIN_API 1 +#define TEE_ORIGIN_COMMS 2 +#define TEE_ORIGIN_TEE 3 +#define TEE_ORIGIN_TRUSTED_APP 4 + +/* Property Sets Pseudo Handles */ +#define TEE_PROPSET_CURRENT_TA (TEE_PropSetHandle)0xFFFFFFFF +#define TEE_PROPSET_CURRENT_CLIENT (TEE_PropSetHandle)0xFFFFFFFE +#define TEE_PROPSET_TEE_IMPLEMENTATION (TEE_PropSetHandle)0xFFFFFFFD + +/* Allocation hints */ +#define TEE_ALLOCATION_HINT_ZEROED 0x00000000 + +/* Crypto Usage Constants */ +#define TEE_USAGE_EXTRACTABLE 0x00000001 +#define TEE_USAGE_ENCRYPT 0x00000002 +#define TEE_USAGE_DECRYPT 0x00000004 +#define TEE_USAGE_MAC 0x00000008 +#define TEE_USAGE_SIGN 0x00000010 +#define TEE_USAGE_VERIFY 0x00000020 +#define TEE_USAGE_DERIVE 0x00000040 + +/* Crypto Handle Flag Constants */ +#define TEE_HANDLE_FLAG_PERSISTENT 0x00010000 +#define TEE_HANDLE_FLAG_INITIALIZED 0x00020000 +#define TEE_HANDLE_FLAG_KEY_SET 0x00040000 +#define TEE_HANDLE_FLAG_EXPECT_TWO_KEYS 0x00080000 + +/* Crypto Operation Constants */ +#define TEE_OPERATION_CIPHER 1 +#define TEE_OPERATION_MAC 3 +#define TEE_OPERATION_AE 4 +#define TEE_OPERATION_DIGEST 5 +#define TEE_OPERATION_ASYMMETRIC_CIPHER 6 +#define TEE_OPERATION_ASYMMETRIC_SIGNATURE 7 +#define TEE_OPERATION_KEY_DERIVATION 8 + +/* Crypto Algortithm Constants */ +#define TEE_ALG_AES_ECB_NOPAD 0x10000010 +#define TEE_ALG_AES_CBC_NOPAD 0x10000110 +#define TEE_ALG_AES_CTR 0x10000210 +#define TEE_ALG_AES_CTS 0x10000310 +#define TEE_ALG_AES_XTS 0x10000410 +#define TEE_ALG_AES_CBC_MAC_NOPAD 0x30000110 +#define TEE_ALG_AES_CBC_MAC_PKCS5 0x30000510 +#define TEE_ALG_AES_CMAC 0x30000610 +#define TEE_ALG_AES_CCM 0x40000710 +#define TEE_ALG_AES_GCM 0x40000810 +#define TEE_ALG_DES_ECB_NOPAD 0x10000011 +#define TEE_ALG_DES_CBC_NOPAD 0x10000111 +#define TEE_ALG_DES_CBC_MAC_NOPAD 0x30000111 +#define TEE_ALG_DES_CBC_MAC_PKCS5 0x30000511 +#define TEE_ALG_DES_CMAC 0x30000611 +#define TEE_ALG_DES3_ECB_NOPAD 0x10000013 +#define TEE_ALG_DES3_CBC_NOPAD 0x10000113 +#define TEE_ALG_DES3_CBC_MAC_NOPAD 0x30000113 +#define TEE_ALG_DES3_CBC_MAC_PKCS5 0x30000513 +#define TEE_ALG_DES3_CMAC 0x30000613 +#define TEE_ALG_RSASSA_PKCS1_V1_5_MD5 0x70001830 +#define TEE_ALG_RSASSA_PKCS1_V1_5_SHA1 0x70002830 +#define TEE_ALG_RSASSA_PKCS1_V1_5_SHA224 0x70003830 +#define TEE_ALG_RSASSA_PKCS1_V1_5_SHA256 0x70004830 +#define TEE_ALG_RSASSA_PKCS1_V1_5_SHA384 0x70005830 +#define TEE_ALG_RSASSA_PKCS1_V1_5_SHA512 0x70006830 +#define TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1 0x70212930 +#define TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224 0x70313930 +#define TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256 0x70414930 +#define TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384 0x70515930 +#define TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512 0x70616930 +#define TEE_ALG_RSAES_PKCS1_V1_5 0x60000130 +#define TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1 0x60210230 +#define TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224 0x60310230 +#define TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256 0x60410230 +#define TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384 0x60510230 +#define TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512 0x60610230 +#define TEE_ALG_RSA_NOPAD 0x60000030 +#define TEE_ALG_DSA_SHA1 0x70002131 +#define TEE_ALG_DH_DERIVE_SHARED_SECRET 0x80000032 +#define TEE_ALG_MD5 0x50000001 +#define TEE_ALG_SHA1 0x50000002 +#define TEE_ALG_SHA224 0x50000003 +#define TEE_ALG_SHA256 0x50000004 +#define TEE_ALG_SHA384 0x50000005 +#define TEE_ALG_SHA512 0x50000006 +#define TEE_ALG_HMAC_MD5 0x30000001 +#define TEE_ALG_HMAC_SHA1 0x30000002 +#define TEE_ALG_HMAC_SHA224 0x30000003 +#define TEE_ALG_HMAC_SHA256 0x30000004 +#define TEE_ALG_HMAC_SHA384 0x30000005 +#define TEE_ALG_HMAC_SHA512 0x30000006 + +/* Storage ID Values */ +#define TEE_STORAGE_PRIVATE 0x00000001 + +/* Data Flags */ +#define TEE_DATA_FLAG_ACCESS_READ 0x00000001 +#define TEE_DATA_FLAG_ACCESS_WRITE 0x00000002 +#define TEE_DATA_FLAG_ACCESS_WRITE_META 0x00000004 +#define TEE_DATA_FLAG_SHARE_READ 0x00000010 +#define TEE_DATA_FLAG_SHARE_WRITE 0x00000020 +#define TEE_DATA_FLAG_CREATE 0x00000200 +#define TEE_DATA_FLAG_EXCLUSIVE 0x00000400 + +/* Misc */ +#define TEE_DATA_MAX_POSITION 0xFFFFFFFF +#define TEE_OBJECT_ID_MAX_LEN 0x40 + +/* Object Types */ +#define TEE_TYPE_AES 0xA0000010 +#define TEE_TYPE_DES 0xA0000011 +#define TEE_TYPE_DES3 0xA0000013 +#define TEE_TYPE_HMAC_MD5 0xA0000001 +#define TEE_TYPE_HMAC_SHA1 0xA0000002 +#define TEE_TYPE_HMAC_SHA224 0xA0000003 +#define TEE_TYPE_HMAC_SHA256 0xA0000004 +#define TEE_TYPE_HMAC_SHA384 0xA0000005 +#define TEE_TYPE_HMAC_SHA512 0xA0000006 +#define TEE_TYPE_RSA_PUBLIC_KEY 0xA0000030 +#define TEE_TYPE_RSA_KEYPAIR 0xA1000030 +#define TEE_TYPE_DSA_PUBLIC_KEY 0xA0000031 +#define TEE_TYPE_DSA_KEYPAIR 0xA1000031 +#define TEE_TYPE_DH_KEYPAIR 0xA1000032 +#define TEE_TYPE_GENERIC_SECRET 0xA0000000 + +/* Object Attribute Identifier Flags - bits 28 and 29 indicate the type (value/ref) and its visibility */ +#define TEE_ATTR_FLAG_VALUE 0x20000000 +#define TEE_ATTR_FLAG_PUBLIC 0x10000000 + +/* Operation and Object Attribute ID Values */ +#define TEE_ATTR_SECRET_VALUE 0xC0000000 +#define TEE_ATTR_RSA_MODULUS 0xD0000130 +#define TEE_ATTR_RSA_PUBLIC_EXPONENT 0xD0000230 +#define TEE_ATTR_RSA_PRIVATE_EXPONENT 0xC0000330 +#define TEE_ATTR_RSA_PRIME1 0xC0000430 // p +#define TEE_ATTR_RSA_PRIME2 0xC0000530 // q +#define TEE_ATTR_RSA_EXPONENT1 0xC0000630 // dp +#define TEE_ATTR_RSA_EXPONENT2 0xC0000730 // dq +#define TEE_ATTR_RSA_COEFFICIENT 0xC0000830 // iq +#define TEE_ATTR_DSA_PRIME 0xD0001031 // p +#define TEE_ATTR_DSA_SUBPRIME 0xD0001131 // q +#define TEE_ATTR_DSA_BASE 0xD0001231 // g +#define TEE_ATTR_DSA_PUBLIC_VALUE 0xD0000131 // y +#define TEE_ATTR_DSA_PRIVATE_VALUE 0xC0000231 // x +#define TEE_ATTR_DH_PRIME 0xD0001032 // p +#define TEE_ATTR_DH_SUBPRIME 0xD0001132 // q +#define TEE_ATTR_DH_BASE 0xD0001232 // g +#define TEE_ATTR_DH_X_BITS 0xF0001332 // type "Value" not "Ref" +#define TEE_ATTR_DH_PUBLIC_VALUE 0xD0000132 // y +#define TEE_ATTR_DH_PRIVATE_VALUE 0xC0000232 // x +#define TEE_ATTR_RSA_OAEP_LABEL 0xD0000930 +#define TEE_ATTR_RSA_PSS_SALT_LENGTH 0xF0000A30 // type "Value" not "Ref" + +/*------------------------------------------------------------------------------ + Trusted Application Interface + ------------------------------------------------------------------------------*/ + +TEE_Result TA_EXPORT TA_CreateEntryPoint(void); + +void TA_EXPORT TA_DestroyEntryPoint(void); + +TEE_Result TA_EXPORT TA_OpenSessionEntryPoint(uint32_t nParamTypes, + TEE_Param pParams[4], + void** ppSessionContext); + +void TA_EXPORT TA_CloseSessionEntryPoint(void* pSessionContext); + +TEE_Result TA_EXPORT TA_InvokeCommandEntryPoint( + void* pSessionContext, + uint32_t nCommandID, + uint32_t nParamTypes, + TEE_Param pParams[4] + ); + + +/*------------------------------------------------------------------------------ + Trusted Core Framework APIs + ------------------------------------------------------------------------------*/ + +void TEE_EXPORT TEE_Panic(TEE_Result nPanicCode); + + +/*------------------------------------------------------------------------------ + Property Access Functions + ------------------------------------------------------------------------------*/ + +TEE_Result TEE_EXPORT TEE_GetPropertyAsString( + TEE_PropSetHandle propsetOrEnumerator, + char* name, + char* valueBuffer, + size_t* valueBufferLen ); + +TEE_Result TEE_EXPORT TEE_GetPropertyAsBool( + TEE_PropSetHandle propsetOrEnumerator, + char* name, + bool* value ); + +TEE_Result TEE_EXPORT TEE_GetPropertyAsU32 ( + TEE_PropSetHandle propsetOrEnumerator, + char* name, + uint32_t* value ); + +TEE_Result TEE_EXPORT TEE_GetPropertyAsBinaryBlock( + TEE_PropSetHandle propsetOrEnumerator, + char* name, + void* valueBuffer, + size_t* valueBufferLen ); + +TEE_Result TEE_EXPORT TEE_GetPropertyAsUUID( + TEE_PropSetHandle propsetOrEnumerator, + char* name, + TEE_UUID* value ); + +TEE_Result TEE_EXPORT TEE_GetPropertyAsIdentity( + TEE_PropSetHandle propsetOrEnumerator, + char* name, + TEE_Identity* value ); + +TEE_Result TEE_EXPORT TEE_AllocatePropertyEnumerator( + TEE_PropSetHandle* enumerator ); + +void TEE_EXPORT TEE_FreePropertyEnumerator( + TEE_PropSetHandle enumerator ); + +void TEE_EXPORT TEE_StartPropertyEnumerator( + TEE_PropSetHandle enumerator, + TEE_PropSetHandle propSet ); + +void TEE_EXPORT TEE_ResetPropertyEnumerator( + TEE_PropSetHandle enumerator ); + +TEE_Result TEE_EXPORT TEE_GetPropertyName( + TEE_PropSetHandle enumerator, + void* nameBuffer, + size_t* nameBufferLen ); + +TEE_Result TEE_EXPORT TEE_GetNextProperty( + TEE_PropSetHandle enumerator ); + + +/*------------------------------------------------------------------------------ + Internal Client API + ------------------------------------------------------------------------------*/ + +TEE_Result TEE_EXPORT TEE_OpenTASession( TEE_UUID* destination, // [in] + uint32_t cancellationRequestTimeout, + uint32_t paramTypes, + TEE_Param params[4], // [inout] + TEE_TASessionHandle* session, // [out] + uint32_t* returnOrigin + ); + +void TEE_EXPORT TEE_CloseTASession(TEE_TASessionHandle session); + +TEE_Result TEE_EXPORT TEE_InvokeTACommand(TEE_TASessionHandle session, + uint32_t cancellationRequestTimeout, + uint32_t commandID, + uint32_t paramTypes, + TEE_Param params[4], + uint32_t* returnOrigin + ); + +/*------------------------------------------------------------------------------ + Cancellation Functions + ------------------------------------------------------------------------------*/ + +bool TEE_EXPORT TEE_GetCancellationFlag( void ); +bool TEE_EXPORT TEE_UnmaskCancellation( void ); +bool TEE_EXPORT TEE_MaskCancellation( void ); + + +/*------------------------------------------------------------------------------ + Memory Management Functions + ------------------------------------------------------------------------------*/ + +TEE_Result TEE_EXPORT TEE_CheckMemoryAccessRights(uint32_t accessFlags, + void* buffer, size_t size + ); + +void TEE_EXPORT TEE_SetInstanceData( void* instanceData ); + +TEE_EXPORT void* TEE_GetInstanceData( void ); + +/** + * Allocates a block of memory from a heap. The address of the allocated block + * is aligned on a 8-bytes boundary. A block allocated by {malloc} must + * be freed by {free}. + * + * @param nSize Number of bytes to be allocated. A zero value is invalid. + * + * @return A pointer to the allocated memory block or + * NULL if the block cannot be allocated. + **/ +TEE_EXPORT void* TEE_Malloc(uint32_t size, uint32_t hint); + +/** + * Reallocates a block of memory from a heap. + * This function enables you to resize a memory block. + * + * If pBlock is NULL, {realloc} is equivalent to {malloc}. + * In particular, if nNewSize is 0, the function returns NULL. + * + * If pBlock is not NULL and nNewSize is 0, then + * {realloc} is equivalent to {free} and returns NULL. + * + * If nNewSize is less or equal to the current size of the block, + * the block is trucated, the content of the block is left unchanged and + * the function returns pBlock. + * + * If nNewSize is greater than the current size of the block, the size + * of the block is increased. The whole content of the block is copied at the + * beginning of the new block. If possible, the block is enlarged in place and + * the function retuns pBlock. If this is not possible, a new block + * is allocated with the new size, the content of the current block is copied, + * the current block is freed and the function retuns the pointer on the new + * block. + * @param pBlock Pointer to the block of memory that the function + * reallocates. This value may be null or returned by an + * earlier call to the {malloc} or {realloc} + * function. + * + * @param nNewSize New size of the memory block, in bytes. + * This value may be zero. A memory block's size can be + * increased or decreased by using this function. + * + * @return A pointer to the reallocated memory block or + * NULL if nNewSize is zero or if an error is detected. + **/ +TEE_EXPORT void* TEE_Realloc(void* buffer, uint32_t newSize); + +/** + * Frees a memory block allocated from a heap by the {malloc} or + * {realloc} function. + * + * This function does nothing if pBlock is set to NULL. + * + * @param pBlock Pointer to the memory block to be freed. + * This pointer is returned by an earlier call + * to the {malloc} or {realloc} function. + **/ +void TEE_EXPORT TEE_Free(void *buffer); + +void TEE_EXPORT TEE_MemMove(void* dest, void* src, uint32_t size); + +int32_t TEE_EXPORT TEE_MemCompare(void* buffer1, void* buffer2, uint32_t size); + +void TEE_EXPORT TEE_MemFill(void* buffer, uint32_t x, uint32_t size ); + + +/*------------------------------------------------------------------------------ + Time Functions + ------------------------------------------------------------------------------*/ + +TEE_Result TEE_EXPORT TEE_Wait(uint32_t timeout); + +void TEE_EXPORT TEE_GetSystemTime(TEE_Time* time); + +void TEE_EXPORT TEE_GetREETime(TEE_Time* time); + +TEE_Result TEE_EXPORT TEE_GetTAPersistentTime(TEE_Time* time); + +TEE_Result TEE_EXPORT TEE_SetTAPersistentTime(TEE_Time* time); + + +/*------------------------------------------------------------------------------ + Arithmetical Functions +------------------------------------------------------------------------------*/ + +typedef uint32_t TEE_BigInt; +typedef uint32_t TEE_BigIntFMMContext; +typedef uint32_t TEE_BigIntFMM; + +#define TEE_BigIntSizeInU32(n) ((((n)+31)/32)+2) + +void TEE_EXPORT TEE_BigIntInit( + OUT TEE_BigInt *bigInt, + IN size_t len); + +int32_t TEE_EXPORT TEE_BigIntCmp( + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +int32_t TEE_EXPORT TEE_BigIntCmpS32( + IN TEE_BigInt *op, + IN int32_t shortVal); + +TEE_Result TEE_EXPORT TEE_BigIntConvertFromOctetString( + OUT TEE_BigInt *dest, + IN uint8_t *buffer, + IN size_t bufferLen, + IN int32_t sign); + +TEE_Result TEE_EXPORT TEE_BigIntConvertToOctetString( + OUT void *buffer, + OUT size_t *bufferLen, + IN TEE_BigInt *bigInt); + +void TEE_EXPORT TEE_BigIntConvertFromS32( + OUT TEE_BigInt *dest, + IN int32_t shortVal); + +TEE_Result TEE_EXPORT TEE_BigIntConvertToS32( + OUT int32_t *dest, + IN TEE_BigInt *src); + +void TEE_EXPORT TEE_BigIntShiftRight( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op, + IN size_t bits); + +bool TEE_EXPORT TEE_BigIntGetBit( + IN TEE_BigInt *src, + IN uint32_t bitIndex); + +uint32_t TEE_EXPORT TEE_BigIntGetBitCount( + IN TEE_BigInt *src); + +void TEE_EXPORT TEE_BigIntAdd( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +void TEE_EXPORT TEE_BigIntSub( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +size_t TEE_EXPORT TEE_BigIntFMMContextSizeInU32( + size_t modulusSizeInBits); + +size_t TEE_EXPORT TEE_BigIntFMMSizeInU32( + size_t modulusSizeInBits); + +void TEE_EXPORT TEE_BigIntInitFMMContext( + OUT TEE_BigIntFMMContext *context, + size_t len, + IN TEE_BigInt *modulus); + +void TEE_EXPORT TEE_BigIntInitFMM( + OUT TEE_BigIntFMM *bigIntFMM, + size_t len); + +void TEE_EXPORT TEE_BigIntNeg( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op); + +void TEE_EXPORT TEE_BigIntMul( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +void TEE_EXPORT TEE_BigIntSquare( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op); + +void TEE_EXPORT TEE_BigIntDiv( + OUT TEE_BigInt *dest_q, + OUT TEE_BigInt *dest_r, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +void TEE_EXPORT TEE_BigIntMod( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op, + IN TEE_BigInt *n); + +void TEE_EXPORT TEE_BigIntAddMod( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2, + IN TEE_BigInt *n); + +void TEE_EXPORT TEE_BigIntSubMod( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2, + IN TEE_BigInt *n); + +void TEE_EXPORT TEE_BigIntMulMod( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2, + IN TEE_BigInt *n); + +void TEE_EXPORT TEE_BigIntSquareMod( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op, + IN TEE_BigInt *n); + +void TEE_EXPORT TEE_BigIntInvMod( + OUT TEE_BigInt *dest, + IN TEE_BigInt *op, + IN TEE_BigInt *n); + +bool TEE_EXPORT TEE_BigIntRelativePrime( + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +void TEE_EXPORT TEE_BigIntComputeExtendedGcd( + OUT TEE_BigInt *gcd, + OUT TEE_BigInt *u, + OUT TEE_BigInt *v, + IN TEE_BigInt *op1, + IN TEE_BigInt *op2); + +int32_t TEE_EXPORT TEE_BigIntIsProbablePrime( + IN TEE_BigInt *op, + uint32_t confidenceLevel); + +void TEE_EXPORT TEE_BigIntConvertToFMM( + OUT TEE_BigIntFMM *dest, + IN TEE_BigInt *src, + IN TEE_BigInt *n, + IN TEE_BigIntFMMContext *context); + +void TEE_EXPORT TEE_BigIntConvertFromFMM( + OUT TEE_BigInt *dest, + IN TEE_BigIntFMM *src, + IN TEE_BigInt *n, + IN TEE_BigIntFMMContext *context); + +void TEE_EXPORT TEE_BigIntComputeFMM( + OUT TEE_BigIntFMM *dest, + IN TEE_BigIntFMM *op1, + IN TEE_BigIntFMM *op2, + IN TEE_BigInt *n, + IN TEE_BigIntFMMContext *context); + + /*------------------------------------------------------------------------------ + Cryptographic Operations API + ------------------------------------------------------------------------------*/ + + /*------------------------------------------------------------------------------ + Generic Operations Functions + ------------------------------------------------------------------------------*/ +TEE_Result TEE_EXPORT TEE_AllocateOperation(TEE_OperationHandle* operation, + uint32_t algorithm, + uint32_t mode, + uint32_t maxKeySize); + +void TEE_EXPORT TEE_FreeOperation(TEE_OperationHandle operation); + +void TEE_EXPORT TEE_GetOperationInfo(TEE_OperationHandle operation, + TEE_OperationInfo* operationInfo); + + +void TEE_EXPORT TEE_ResetOperation(TEE_OperationHandle operation); + +TEE_Result TEE_EXPORT TEE_SetOperationKey(TEE_OperationHandle operation, + TEE_ObjectHandle key); + +TEE_Result TEE_EXPORT TEE_SetOperationKey2(TEE_OperationHandle operation, + TEE_ObjectHandle key1, + TEE_ObjectHandle key2); + +void TEE_EXPORT TEE_CopyOperation(TEE_OperationHandle dstOperation, + TEE_OperationHandle srcOperation); + + +/* Message Digest Functions */ +void TEE_EXPORT TEE_DigestUpdate(TEE_OperationHandle operation, + void* chunk, + size_t chunkSize); + +TEE_Result TEE_EXPORT TEE_DigestDoFinal(TEE_OperationHandle operation, + void* chunk, + size_t chunkLen, + void* hash, + size_t* hashLen); + +/* Symmetric Cipher Functions */ +void TEE_EXPORT TEE_CipherInit(TEE_OperationHandle operation, + void* IV, + size_t IVLen); + +TEE_Result TEE_EXPORT TEE_CipherUpdate(TEE_OperationHandle operation, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen); + +TEE_Result TEE_EXPORT TEE_CipherDoFinal(TEE_OperationHandle operation, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen); + +/*---------------------------------------------------------------------------- + MAC Functions +-----------------------------------------------------------------------------*/ +void TEE_EXPORT TEE_MACInit(TEE_OperationHandle operation, + void* IV, + size_t IVLen); + +void TEE_EXPORT TEE_MACUpdate(TEE_OperationHandle operation, + void* chunk, + size_t chunkSize); + +TEE_Result TEE_EXPORT TEE_MACComputeFinal(TEE_OperationHandle operation, + void* message, + size_t messageLen, + void* mac, + size_t* macLen); + +TEE_Result TEE_EXPORT TEE_MACCompareFinal(TEE_OperationHandle operation, + void* message, + size_t messageLen, + void* mac, + size_t macLen); + +/*---------------------------------------------------------------------------- + Authenticated Encryption Functions ---------------------------------------- + ---------------------------------------------------------------------------*/ +TEE_Result TEE_EXPORT TEE_AEInit(TEE_OperationHandle operation, + void* nonce, + size_t nonceLen, + uint32_t tagLen, + uint32_t AADLen, + uint32_t payloadLen); + +void TEE_EXPORT TEE_AEUpdateAAD(TEE_OperationHandle operation, + void* AADdata, + size_t AADdataLen); + +TEE_Result TEE_EXPORT TEE_AEUpdate(TEE_OperationHandle operation, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen); + + TEE_Result TEE_EXPORT TEE_AEEncryptFinal(TEE_OperationHandle operation, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen, + void* tag, + size_t* tagLen); + +TEE_Result TEE_EXPORT TEE_AEDecryptFinal(TEE_OperationHandle operation, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen, + void* tag, + size_t tagLen); + +/*----------------------------------------------------------------------------- + Asymmetric Functions +-----------------------------------------------------------------------------*/ +TEE_Result TEE_EXPORT TEE_AsymmetricEncrypt(TEE_OperationHandle operation, + TEE_Attribute* params, + uint32_t paramCount, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen); + +TEE_Result TEE_EXPORT TEE_AsymmetricDecrypt(TEE_OperationHandle operation, + TEE_Attribute* params, + uint32_t paramCount, + void* srcData, + size_t srcLen, + void* destData, + size_t* destLen); + +TEE_Result TEE_EXPORT TEE_AsymmetricSignDigest(TEE_OperationHandle operation, + TEE_Attribute* params, + uint32_t paramCount, + void* digest, + size_t digestLen, + void* signature, + size_t* signatureLen); + +TEE_Result TEE_EXPORT TEE_AsymmetricVerifyDigest(TEE_OperationHandle operation, + TEE_Attribute* params, + uint32_t paramCount, + void* digest, + size_t digestLen, + void* signature, + size_t signatureLen); + +/*----------------------------------------------------------------------------- + Key Derivation Functions +-----------------------------------------------------------------------------*/ +void TEE_EXPORT TEE_DeriveKey(TEE_OperationHandle operation, + TEE_Attribute* params, + uint32_t paramCount, + TEE_ObjectHandle derivedKey); + + +/*----------------------------------------------------------------------------- + Random Data Generation Function +-----------------------------------------------------------------------------*/ +void TEE_EXPORT TEE_GenerateRandom(void* randomBuffer, + size_t randomBufferLen); + + +/*------------------------------------------------------------------------------ + Trusted Storage Functions +------------------------------------------------------------------------------*/ + +/* Generic Object Functions */ +void TEE_EXPORT TEE_GetObjectInfo(TEE_ObjectHandle object, + TEE_ObjectInfo* objectInfo); + +void TEE_EXPORT TEE_RestrictObjectUsage(TEE_ObjectHandle object, + uint32_t objectUsage); + +TEE_Result TEE_EXPORT TEE_GetObjectBufferAttribute(TEE_ObjectHandle object, + uint32_t attributeID, + void* buffer, + size_t* size); + +TEE_Result TEE_EXPORT TEE_GetObjectValueAttribute(TEE_ObjectHandle object, + uint32_t attributeID, + uint32_t* a, + uint32_t* b); + +void TEE_EXPORT TEE_CloseObject(TEE_ObjectHandle object); + +/* Transient Object Functions */ +TEE_Result TEE_EXPORT TEE_AllocateTransientObject(uint32_t objectType, + uint32_t maxObjectSize, + TEE_ObjectHandle* object); + +void TEE_EXPORT TEE_FreeTransientObject(TEE_ObjectHandle object); + +void TEE_EXPORT TEE_ResetTransientObject(TEE_ObjectHandle object); + +TEE_Result TEE_EXPORT TEE_PopulateTransientObject(TEE_ObjectHandle object, + TEE_Attribute* attrs, + uint32_t attrCount); + +void TEE_EXPORT TEE_InitRefAttribute(TEE_Attribute* attr, + uint32_t attributeID, + void* buffer, + size_t length); + +void TEE_EXPORT TEE_InitValueAttribute(TEE_Attribute* attr, + uint32_t attributeID, + uint32_t a, + uint32_t b); + +void TEE_EXPORT TEE_CopyObjectAttributes(TEE_ObjectHandle destObject, + TEE_ObjectHandle srcObject); + +TEE_Result TEE_EXPORT TEE_GenerateKey(TEE_ObjectHandle object, + uint32_t keySize, + TEE_Attribute* params, + uint32_t paramCount); + +/* Persistant Object Functions */ +TEE_Result TEE_EXPORT TEE_CreatePersistentObject(uint32_t storageID, + void* objectID, + size_t objectIDLen, + uint32_t flags, + TEE_ObjectHandle attributes, + void* initialData, + size_t initialDataLen, + TEE_ObjectHandle* object); + +TEE_Result TEE_EXPORT TEE_OpenPersistentObject(uint32_t storageID, + void* objectID, + size_t objectIDLen, + uint32_t flags, + TEE_ObjectHandle* object); + +void TEE_EXPORT TEE_CloseAndDeletePersistentObject(TEE_ObjectHandle object); + +TEE_Result TEE_EXPORT TEE_RenamePersistentObject(TEE_ObjectHandle object, + void* newObjectID, + size_t newObjectIDLen); + +TEE_Result TEE_EXPORT TEE_AllocatePersistentObjectEnumerator(TEE_ObjectEnumHandle* objectEnumerator); + +void TEE_EXPORT TEE_FreePersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator); + +void TEE_EXPORT TEE_ResetPersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator); + +TEE_Result TEE_EXPORT TEE_StartPersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator, + uint32_t storageID); + +TEE_Result TEE_EXPORT TEE_GetNextPersistentObject(TEE_ObjectEnumHandle objectEnumerator, + TEE_ObjectInfo* objectInfo, + void* objectID, + size_t* objectIDLen); + +TEE_Result TEE_EXPORT TEE_ReadObjectData(TEE_ObjectHandle object, + void* buffer, + size_t size, + uint32_t* count); + +TEE_Result TEE_EXPORT TEE_WriteObjectData(TEE_ObjectHandle object, + void* buffer, + size_t size); + +TEE_Result TEE_EXPORT TEE_TruncateObjectData(TEE_ObjectHandle object, + uint32_t size); + +TEE_Result TEE_EXPORT TEE_SeekObjectData(TEE_ObjectHandle object, + int32_t offset, + TEE_Whence whence); + +#endif /* __TEE_INTERNAL_API_H__ */ diff --git a/mobicore/common/DrSecureStorage/tlDriverApi.h b/mobicore/common/DrSecureStorage/tlDriverApi.h new file mode 100644 index 0000000..6f42056 --- /dev/null +++ b/mobicore/common/DrSecureStorage/tlDriverApi.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * @file tlDriverApi.h + * @brief Contains trustlet API definitions + * + */ + +#ifndef __TLDRIVERAPI_H__ +#define __TLDRIVERAPI_H__ + +#include "tlStd.h" +#include "TlApi/TlApiError.h" + + +/** + * Open session to the driver with given data + * + * @return session id + */ +_TLAPI_EXTERN_C uint32_t tlApiOpenSession( void ); + + +/** + * Close session + * + * @param sid session id + * + * @return TLAPI_OK upon success or specific error + */ +_TLAPI_EXTERN_C tlApiResult_t tlApiCloseSession( uint32_t sid ); + + +/** + * Inits session data (sample data 01) + * + * @param length data length + * @param address data address + * + * @return TLAPI_OK upon success or specific error + */ +_TLAPI_EXTERN_C tlApiResult_t tlApiInitSampleData01( + uint32_t sid, + uint32_t length, + uint32_t address); + + +/** + * Inits session data (sample data 02) + * + * @param data + * + * @return TLAPI_OK upon success or specific error + */ +_TLAPI_EXTERN_C tlApiResult_t tlApiInitSampleData02( + uint32_t sid, + uint32_t data); + + +/** + * Executes command + * + * @param sid session id + * @param commandId command id + * + * @return TLAPI_OK upon success or specific error + */ +_TLAPI_EXTERN_C tlApiResult_t tlApiExecute( + uint32_t sid, + uint32_t commandId); + + +/** tlApi function to call driver via IPC. + * Sends a MSG_RQ message via IPC to a MobiCore driver. + * + * @param driverID The driver to send the IPC to. + * @param pMarParam MPointer to marshaling parameters to send to the driver. + * + * @return TLAPI_OK + * @return E_TLAPI_COM_ERROR in case of an IPC error. + */ +_TLAPI_EXTERN_C tlApiResult_t tlApi_callDriver( + uint32_t driver_ID, + void* pMarParam); + + +#endif // __TLDRIVERAPI_H__ diff --git a/mobicore/common/LogWrapper/log.h b/mobicore/common/LogWrapper/log.h new file mode 100644 index 0000000..387f648 --- /dev/null +++ b/mobicore/common/LogWrapper/log.h @@ -0,0 +1,237 @@ +/** Log wrapper for Android. + * @{ + * @file + * + * Maps LOG_*() macros to __android_log_print() if LOG_ANDROID is defined. + * Adds some extra info to log output like LOG_TAG, file name and line number. + * + * + * + * 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 TLCWRAPPERANDROIDLOG_H_ +#define TLCWRAPPERANDROIDLOG_H_ + +#ifndef WIN32 +#include +#define GETPID getpid +#else +#include +#define GETPID _getpid +#endif +#include +#ifndef WIN32 +#include +#endif +#include +#include + +/** 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 +// 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 + // 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 + // 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: + // I/McDrvBasicTest_0_1( 4075): setUp + #define _LOG_x(_x_,...) \ + do \ + { \ + printf("%s/%s(%d): ",_x_,LOG_TAG,GETPID()); \ + printf(__VA_ARGS__); \ + printf(EOL); \ + } while(1!=1) + + +#ifdef NDEBUG // no logging in debug version + #define LOG_I(fmt, ...) DUMMY_FUNCTION() + #define LOG_W(fmt, ...) DUMMY_FUNCTION() +#else + #define LOG_I(...) _LOG_x("I", __VA_ARGS__) + #define LOG_W(...) _LOG_x("W", __VA_ARGS__) +#endif + #define _LOG_E(...) _LOG_x("E", __VA_ARGS__) + + #define LOG_i(...) printf(__VA_ARGS__) + #define LOG_w(...) printf(__VA_ARGS__) + #define LOG_e(...) printf(__VA_ARGS__) + +#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. + */ +#define LOG_E(...) \ + do \ + { \ + _LOG_E(" *****************************"); \ + _LOG_E(" *** ERROR: " __VA_ARGS__); \ + _LOG_E(" *** Detected in %s/%u()", __FUNCTION__, __LINE__); \ + _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 + +#ifndef WIN32 +__attribute__ ((unused)) +#endif +static void LOG_I_Buf( + const char * szDescriptor, + const void * blob, + size_t sizeOfBlob +) { + + #define CPL 0x10 // chars per line + #define OVERHEAD 20 + + char buffer[CPL * 4 + OVERHEAD]; + + uint32_t index = 0; + + uint32_t moreThanOneLine = (sizeOfBlob > CPL); + uint32_t blockLen = CPL; + uint32_t addr = 0; + uint32_t i = 0; + + if (NULL != szDescriptor) + { + index += sprintf(&buffer[index], "%s", szDescriptor); + } + + if (moreThanOneLine) + { + if (NULL == szDescriptor) + { + index += sprintf(&buffer[index], "memory dump"); + } + index += sprintf(&buffer[index], " (0x%" PRIxPTR ", %zu bytes)", (uintptr_t)blob,sizeOfBlob); + LOG_I("%s", buffer); + index = 0; + } + else if (NULL == szDescriptor) + { + index += sprintf(&buffer[index], "Data at 0x%" PRIxPTR ": ", (uintptr_t)blob); + } + + if(sizeOfBlob == 0) { + LOG_I("%s", buffer); + } + else + { + while (sizeOfBlob > 0) + { + if (sizeOfBlob < blockLen) + { + blockLen = sizeOfBlob; + } + + // address + if (moreThanOneLine) + { + index += sprintf(&buffer[index], "0x%08X | ",addr); + addr += CPL; + } + // bytes as hex + for (i=0; i32)?c:'.'); + } + + blob = &(((const char *)blob)[blockLen]); + sizeOfBlob -= blockLen; + + // print line to logcat / stdout + LOG_I("%s", buffer); + index = 0; + } + } +} + +#endif /** TLCWRAPPERANDROIDLOG_H_ */ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApi.h b/mobicore/common/MobiCore/inc/DrApi/DrApi.h new file mode 100644 index 0000000..9ae1187 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApi.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPI_H__ +#define __DRAPI_H__ + +#if defined(DRIVER) +#include "drStd.h" +#endif +#include "DrApi/version.h" +#include "DrApi/DrApiError.h" +#include "DrApi/DrApiMcSystem.h" +#include "DrApi/DrApiMm.h" +#include "DrApi/DrApiThread.h" +#include "DrApi/DrApiLogging.h" +#include "DrApi/DrApiHeap.h" +#include "DrApi/DrApiFastCall.h" +#include "DrApi/DrApiTime.h" + +#endif // __DRAPI_H__ diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiCommon.h b/mobicore/common/MobiCore/inc/DrApi/DrApiCommon.h new file mode 100644 index 0000000..973d86d --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiCommon.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPICOMMON_H__ +#define __DRAPICOMMON_H__ + +#include "DrApi/DrApiError.h" + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------------------------------------------------ +/** Definitions */ + +#define SHIFT_4KB (12U) /**< SIZE_4KB is 1 << SHIFT_4KB aka. 2^SHIFT_4KB. */ +#define SIZE_4KB (1 << SHIFT_4KB) /**< Size of 1 KiB. */ +typedef uint8_t page4KB_t[SIZE_4KB]; /**< 4 KiB page. */ +typedef page4KB_t *page4KB_ptr; /**< pointer to 4 KiB page. */ + +#define PTR2VAL(p) ((uintptr_t)(p)) +#define VAL2PTR(v) ((addr_t)(v)) +#define FUNC_PTR(func) VAL2PTR( PTR2VAL( func ) ) + +//Stack types +typedef uint32_t stackEntry_t; +typedef stackEntry_t *stackEntry_ptr; +typedef stackEntry_ptr stackTop_ptr; + +//============================================================================== +//Common integer types +typedef unsigned int u32_t; +typedef unsigned short u16_t; +typedef unsigned char u08_t; +typedef u32_t word_t; + +//Common result type +typedef word_t drApiResult_t; + +//MTK types +typedef word_t taskid_t, *taskid_ptr; /**< task id data type. */ +typedef word_t threadno_t, *threadno_ptr; /**< thread no. data type. */ +typedef word_t threadid_t, *threadid_ptr; /**< thread id data type. */ + + +// interrupt mode flags. The design of the bits is that most common setting +// RISING, EDGE, PERIODIC maps to the value the value 0. Not all mode +// combinations may be available for each interrupt. +#define INTR_MODE_MASK_TRIGGER (1U<<0) +#define INTR_MODE_TRIGGER_LEVEL INTR_MODE_MASK_TRIGGER +#define INTR_MODE_TRIGGER_EDGE 0 +#define INTR_MODE_MASK_CONDITION (1U<<1) +#define INTR_MODE_CONDITION_FALLING INTR_MODE_MASK_CONDITION +#define INTR_MODE_CONDITION_LOW INTR_MODE_MASK_CONDITION +#define INTR_MODE_CONDITION_RISING 0 +#define INTR_MODE_CONDITION_HIGH 0 +#define INTR_MODE_MASK_OCCURANCE (1U<<2) +#define INTR_MODE_OCCURANCE_ONESHOT INTR_MODE_MASK_OCCURANCE +#define INTR_MODE_OCCURANCE_PERIODIC 0 + +// convenience constants +#define INTR_MODE_RAISING_EDGE (INTR_MODE_TRIGGER_EDGE | INTR_MODE_CONDITION_RISING) +#define INTR_MODE_FALLING_EDGE (INTR_MODE_TRIGGER_EDGE | INTR_MODE_CONDITION_FALLING) +#define INTR_MODE_LOW_LEVEL (INTR_MODE_TRIGGER_LEVEL | INTR_MODE_CONDITION_LOW) +#define INTR_MODE_HIGH_LEVEL (INTR_MODE_TRIGGER_LEVEL | INTR_MODE_CONDITION_HIGH) + +//Interrupt types +typedef word_t intrNo_t, *intrNo_ptr; /**< interrupt number. */ +typedef word_t intrMode_t, *intrMode_ptr; /**< interrupt mode. */ + +#ifdef __cplusplus +} +#endif + +#endif //__DRAPICOMMON_H__ + diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiError.h b/mobicore/common/MobiCore/inc/DrApi/DrApiError.h new file mode 100644 index 0000000..fbac0b1 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiError.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPIERROR_H__ +#define __DRAPIERROR_H__ + +/* + * DRAPI error codes. + * MAJOR part of error code is stable. + * MAJOR part may be used in testing for specific error code. + * + * Detail error codes may change in different releases + * Please do not test DETAIL part when comparing error codes. + */ +#define DRAPI_ERROR_MAJOR(ecode) ((ecode) & 0xFFF) /**< Get MAJOR part of error code. */ +#define DRAPI_ERROR_MAJOR_CODE(ecode) ((ecode) & 0xFF) /**< Get MAJOR_CODE part of error code. */ +#define DRAPI_ERROR_MAJOR_COMPONENT(ecode) (((ecode)>>8) & 0xF) /**< Get MAJOR_COMPONENT part of error code. */ + +#define DRAPI_ERROR_DETAIL(ecode) (((ecode)>>12) & 0xFFF) /**< Get detail part of error code. */ + +#define DRAPI_ERROR_CREATE(ecode, detail) (((ecode)&0xFFF)|((detail&0xFFF)<<12)) /**< Create error code */ + +//============================================================================== +// Error code defintitions + +#define DRAPI_OK 0x0 /**< Returns on successful execution of a function. */ + +#define E_DRAPI_KERNEL_ERROR 0xF01 /**< Kernel returned error. */ +#define E_DRAPI_INVALID_PARAMETER 0xF02 /**< Invalid parameter. */ +#define E_DRAPI_NOT_PERMITTED 0xF03 /**< Permission error */ +#define E_DRAPI_IPC_ERROR 0xF04 /**< Error in IPC. */ +#define E_DRAPI_TASK_NOT_ACCEPTABLE 0xF05 /**< Task not acceptable for operation. */ +#define E_DRAPI_CANNOT_MAP 0xF06 /**< Cannot create mapping. */ +#define E_DRAPI_DRV_NO_SUCH_CLIENT 0xF07 /**< Client does not exist. */ +#define E_DRAPI_CANNOT_INIT 0xF08 /**< Cannot be initialized. */ +#define E_DRAPI_NOT_IMPLEMENTED 0xF09 /**< Function not yet implemented. */ + + +// Error codes inherited from MTK +#define E_OK 0 /**< no error. */ +#define E_INVALID 1 /**< invalid argument. */ +#define E_BADTASK 2 /**< current task does not own target task. */ +#define E_NOTACTIVATED 3 /**< task has not been activated. */ +#define E_NOTOWNER 4 /**< current task does not own specified task. */ +#define E_ACTIVATED 5 /**< task has been activated. */ +#define E_LIMIT 6 /**< limit broken. */ +#define E_NOABILITY 7 /**< no permission. */ +#define E_STARTED 8 /**< task or thread does have been started. */ +#define E_BADMAP 9 /**< invalid mapping. architecture specific error. */ +#define E_MAPPED 10 /**< mapping overlaps existing mapping. */ +#define E_NOTSTARTED 11 /**< thread has been started. */ +#define E_TIMEOUT 12 /**< timeout period expired. */ +#define E_ABORT 13 /**< operation aborted. */ +#define E_MSGTYPE 14 /**< message to send is not of the type the receiver is waiting for. */ +#define E_MSGLENGTH 15 /**< message to send exceeds message length the receiver is waiting for. */ + + +#endif // __DRAPIERROR_H__ + diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiFastCall.h b/mobicore/common/MobiCore/inc/DrApi/DrApiFastCall.h new file mode 100644 index 0000000..6477fe3 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiFastCall.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef FASTCALL_H_ +#define FASTCALL_H_ + +/** Firmware Driver and Fastcall Handlers + * + * Mobicore can have one firmware driver. Such driver is loaded + * typically at boot, and cannot be unloaded. Firmware driver is + * intended to act as system integration means, and is not intended + * to act as typical peripheral driver. + * + * Fastcall handlers + * Firmware driver can register fastcall handler in some platforms. + * Fastcall handler is called for fastcalls unknown to Mobicore. + * + * Fastcall handlers get driver memory mappings in range of 0-2MB + * at the time handler is installed. Driver must not unmap any of + * these mappings. If new mappings are made, they cannot be relied + * to be visible in fastcall hook function. + * + * Fastcall handler may map sections (of size 1M). These mappings are not + * visible to driver. + * + * Fastcall handler gets access to number of registers at the time of + * fastcall was made in NWd. Actual number of registers depends on + * platform, but is always at least 4 (r0-r3). + * + * Notes on use of Fastcall handlers + * Fastcall handlers + * - cannot call any TlApi or DrApi functions. + * - cannot have synchronization with firmware driver. + * - do not have large stack. If stack is needed, switch to your own. + * - may be executed concurrently in all CPUs. + * - must not cause exceptions. There is no means to recover in case + * of exception. + * + */ + +#define FASTCALL_OWNER_TZOS (0xFF000000) +#define FASTCALL_OWNER_SIP (0x81000000) +#define FASTCALL_OWNER_OEM (0x83000000) +#define FASTCALL_OWNER_STD (0x84000000) + +#define FASTCALL_OWNER_MASK (0xFF000000) + +#define FCH_L1_MAX 12 + +typedef word_t *fastcall_registers_t; + +/** Context for FCs hook call + * + * This is (currently) shared between all processors + */ +struct fcContext { + word_t size; // Size of context + // Callback to modify L1 entry. + // idx is the address in MBytes of the entry to modify (starting at 8MB). + // (for example idx=2 will modify the entry for address 10MB) + // Return the virtual address corresponding to modified entry. + // Return NULL if there is an error. + // 64 bits version must be used to modify L1 table in LPAE mode. + void *(*setL1Entry)(struct fcContext *context, word_t idx, word_t entry); + word_t registers; // Number of registers available in fastcall + void (*prepareIdenticalMapping)(struct fcContext *context, addr_t start, word_t length, word_t flags); + void (*generateFcNotification)(struct fcContext *context); + void *(*setL1Entry64)(struct fcContext *context, word_t idx, uint64_t entry); +}; + +/* Fastcall handler initialization + * + * Called once before any fastcall. + * Can map memories for fastcall context. + * This function must never cause any exceptions. + * Call is executed in SVC mode. + * + * Return value + * 0 Successfull initialization. + * Other cancel hook installation + */ +typedef word_t (*fcInitHook)( + struct fcContext *context +); + + +/* Fastcall handler + * + * Executed possibly concurrently in all CPUs. + * This function must never cause any exceptions. + * Call is executed in IRQ mode. + * On Entry + * fastcall_regs_t[0]...fastcall_regs_t[15] contain input registers. + * On exit + * fastcall_regs_t[0]...fastcall_regs_t[N] contain r0...rN. + * If driver did not handle fastcall, registers must be unmodified. + * If driver handled fastcall registers r0...r3 may be modified. + * Registers beyond r3 must not be modified. Result of any + * modification is unpredictable. + * Return values + * Nonzero return value means that fastcall is handled. + */ +typedef word_t (*fcEntryHook)( + fastcall_registers_t *regs_t, + struct fcContext *context +); + + +#endif /* FASTCALL_H_ */ diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiHeap.h b/mobicore/common/MobiCore/inc/DrApi/DrApiHeap.h new file mode 100644 index 0000000..4037672 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiHeap.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPIHEAP_H__ +#define __DRAPIHEAP_H__ + +#if TBASE_API_LEVEL >= 3 + +#include "DrApi/DrApiCommon.h" +#include "DrApi/DrApiError.h" + +/** + * Allocates a block of memory from the heap. + * The address of the allocated block is aligned on a 8-bytes boundary. A block + * allocated by drApiMalloc must be freed by drApiFree. + * If the size of the space requested is zero, the value returned is still a + * non-NULL pointer that the Trusted Application must not attempt to access. + * + * @param size: [in] the number of bytes to be allocated. + * + * @param hint: [in] must be 0 + * + * @return Upon successful completion, with size not equal to zero, the + * function returns a pointer to the allocated space. + * Otherwise, a NULL pointer is returned. + **/ +_DRAPI_EXTERN_C void* drApiMalloc(uint32_t size, uint32_t hint); + +/** + * Reallocates a block of memory from a heap. + * This function allows resizing a memory block. + * If buffer is NULL, drApiRealloc is equivalent to drApiMalloc. + * If buffer is not NULL and newSize is 0, then drApiRealloc is equivalent to + * drApiFree and returns a non-NULL pointer that the Trusted Application must + * not attempt to access. + * If newSize is less or equal to the current size of the block, the block is + * truncated, the content of the block is left unchanged and the function + * returns buffer. + * If newSize is greater than the current size of the block, the size of the + * block is increased. The whole content of the block is copied at the beginning + * of the new block. If possible, the block is enlarged in place and the + * function returns buffer. If this is not possible, a new block is allocated + * with the new size, the content of the current block is copied, the current + * block is freed and the function returns the pointer on the new block. + * + * @param buffer: [in] Pointer to the block of memory that the function + * reallocates. + * This value may be null or returned by an earlier call + * to drApiMalloc or drApiRealloc. + * + * @param newSize: [in] size of the memory block in bytes. + * This value may be zero. + * + * @return A pointer to the reallocated memory block, a non-NULL pointer if the + * newSize is zero or NULL if an error is detected. + **/ +_DRAPI_EXTERN_C void* drApiRealloc(void* buffer, uint32_t newSize); + + +/** + * Frees a memory block allocated from a heap by drApiMalloc or drApiRealloc. + * This function does nothing if buffer is NULL. + * + * @param buffer: [in] Pointer to the block of memory to be freed. + **/ +_DRAPI_EXTERN_C void drApiFree(void* buffer); + +#endif /* TBASE_API_LEVEL */ + +#endif /* !defined(__DRAPIHEAP_H__) */ diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiIpcMsg.h b/mobicore/common/MobiCore/inc/DrApi/DrApiIpcMsg.h new file mode 100644 index 0000000..410a6e3 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiIpcMsg.h @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ +#ifndef __DRAPI_IPCMSG_H__ +#define __DRAPI_IPCMSG_H__ + +#include "DrApiCommon.h" + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------------------------------------------------ +/** Possible message types/event types of the system. */ +typedef enum { + MSG_NULL = 0, // Used for initializing state machines + MSG_RQ = 1, + // Client Request, blocks until MSG_RS is received + // Client -> Server + MSG_RS = 2, + // Driver Response, answer to MSG_RQ + // Server -> Client + MSG_RD = 3, + // Driver becomes ready + // Server -> IPCH + MSG_NOT = 4, + // Notification to NWd for a session, send-only message with no + // response + // client/server -> IPCH; + MSG_CLOSE_TRUSTLET = 5, + // Close Trustlet, must be answered by MSG_CLOSE_TRUSTLET_ACK + // MSH -> IPCH, IPCH -> Server + MSG_CLOSE_TRUSTLET_ACK = 6, + // Close Trustlet Ack, in response to MSG_CLOSE_TRUSTLET + // Server -> IPCH + MSG_MAP = 7, + // Map Client into Server, send-only message with no reponse + //Server -> IPCH; + MSG_ERR_NOT = 8, + // Error Notification + // EXCH/SIQH -> IPCH + MSG_CLOSE_DRIVER = 9, + // Close Driver, must be answered with MSG_CLOSE_DRIVER_ACK + // MSH -> IPCH, IPCH -> Driver/Server + MSG_CLOSE_DRIVER_ACK = 10, + // Close Driver Ack, response to MSG_CLOSE_DRIVER + // Driver/Server -> IPCH, IPCH -> MSH + MSG_GET_DRIVER_VERSION = 11, + // Get driver version, used for response also + // Client <-> IPCH + MSG_GET_DRAPI_VERSION = 12, + // Get DrApi version, used for response also + // Driver <-> IPCH */ + MSG_SET_NOTIFICATION_HANDLER = 13, + // Set (change) the SIQ handler thread, used for response also + // Driver <-> IPCH + MSG_GET_REGISTRY_ENTRY = 14, + // Get registry entry, available only if MC_FEATURE_DEBUG_SUPPORT is + // set, used for response also + // Driver <-> IPCH + MSG_DRV_NOT = 15, + // Notification to a Trustlet, looks like a notification from NWd for + // the Trustlet, send-only message with no response + // Driver -> Trustlet + MSG_SET_FASTCALL_HANDLER = 16, + // install a FastCall handler, used for response also + // Driver <-> IPCH + MSG_GET_CLIENT_ROOT_AND_SP_ID = 17, + // get Root DI and SP ID, used for response also + // Driver <-> IPCH + MSG_SUSPEND = 18, + // Suspend, requires MSG_SUSPEND_ACK as response + // MSH -> IPCH, IPCH -> driver + MSG_SUSPEND_ACK = 19, + // Suspend Ack, response to MSG_SUSPEND + // driver -> IPCH, IPCH -> MSH + MSG_RESUME = 20, + // resume, , requires MSG_RESUME_ACK as response + // MSH -> IPCH, IPCH -> driver + MSG_RESUME_ACK = 21, + // resume, , response to MSG_RESUME + // driver -> IPCH, IPCH -> MSH + MSG_GET_ENDORSEMENT_SO = 22, + // get SO from RTM for the Endorsement functionality + // Driver <-> IPCH + MSG_GET_SERVICE_VERSION = 23, + // get version of service (TA) + // Driver <-> IPCH + MSG_ERROR = 24, + // IPCH returns error to Driver + // IPCH <-> DRIVER + MSG_CALL_FASTCALL = 25, + // Call fastcall from driver + // DRIVER -> IPCH -> MTK -> FASTCALL -> return +} message_t; + + +//------------------------------------------------------------------------------ +/** Waits with infinite timeout for IPC. + * + * @param ipcPartner IPC partner to signal. + * @param pMr0 IPC register 0. + * @param pMr1 IPC register 1. + * @param pMr2 IPC register 2. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIpcWaitForMessage( + threadid_t *pIpcPartner, + uint32_t *pMr0, + uint32_t *pMr1, + uint32_t *pMr2 +); + +//------------------------------------------------------------------------------ +/** + * Send ready message or answer to IPCH and waits for a client request + * + * @param ipcPeer Destination to send message to. + * @param ipcMsg IPC message. + * @param ipcData Additional IPC data. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIpcCallToIPCH( + threadid_t *pIpcPeer, + message_t *pIpcMsg, + uint32_t *pIpcData +); + +//------------------------------------------------------------------------------ +/** Sets signal. + * The signal (SIGNAL) is used by a thread to inform another thread about an event. + * The signal operation is asynchronous, which means that the operation will return + * immediately without blocking the user. Function uses auto-clear signals, meaning that + * the signal is cleared automatically when the receiver receives it. + * + * It is up to the destination of the signal to pick up and process the information. + * + * @param receiver Thread to set the signal for. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIpcSignal( + const threadid_t receiver +); + +//------------------------------------------------------------------------------ +/** Signal wait operation. + * A thread uses the sigWait operation to check if a signal has occurred. If no signal is + * pending the thread will block until a signal arrives. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIpcSigWait( void ); + +//------------------------------------------------------------------------------ +/** Notify NWd driver + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiNotify( void ); + + +//------------------------------------------------------------------------------ +/** + * Makes control syscall with given parameters + * + * @param controlid control id + * @param param1 parameter 1 + * @param param2 parameter 2 + * @param param3 parameter 3 + * @param param4 parameter 4 + * @param *data set by control syscall + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiSyscallControl( + uint32_t controlid, + uint32_t param1, + uint32_t param2, + uint32_t param3, + uint32_t param4, + uint32_t *data +); + + +//------------------------------------------------------------------------------ +/** Reads OEM data starting from given offset + * + * @param offset data offset + * @param data set by control syscall + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiReadOemData( + const uint32_t offset, + uint32_t *data +); + +//------------------------------------------------------------------------------ +/** Sends notification to client + * + * @param client Client's thread id + * * + * @return MTK return code + */ +drApiResult_t drApiNotifyClient( + const threadid_t client +); + +//------------------------------------------------------------------------------ +/** Returns ID of Root and Service Provider ID of the specified client + * + * @param rootId ID of Root + * @param spId Service Provider ID + * @param client Thread ID + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiGetClientRootAndSpId( + uint32_t *rootId, + uint32_t *spId, + const threadid_t client +); + + +//------------------------------------------------------------------------------ +/** + * Handles unknown messages + * This function has to be called by Driver if it receives a message it doesn’t recognize + * + * @param ipcPeer Sender of message. + * @param ipcMsg IPC message. + * @param ipcData Additional IPC data. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIpcUnknownMessage( + threadid_t *pIpcPeer, + message_t *pIpcMsg, + uint32_t *pIpcData +); + +//------------------------------------------------------------------------------ +#if TBASE_API_LEVEL >= 3 +/** + * Makes request to t-base to update notification thread + * + * @param threadNo Number of the new notification thread. + * + * @retval DRAPI_OK or relevant error code. + */ +drApiResult_t drApiUpdateNotificationThread( + threadno_t threadno +); +#endif /* TBASE_API_LEVEL */ + +#ifdef __cplusplus +} +#endif + +#endif /** __DRAPI_IPCMSG_H__ */ + diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiLogging.h b/mobicore/common/MobiCore/inc/DrApi/DrApiLogging.h new file mode 100644 index 0000000..39f8811 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiLogging.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPILOGGING_H__ +#define __DRAPILOGGING_H__ + +#include "DrApi/DrApiCommon.h" +#include "DrApi/DrApiError.h" + +/** Formatted logging functions. + * + * drApiLogvPrintf, drApiLogPrintf + * + * Minimal printf-like function to print logging message to NWd log. + * + * Supported formatters: + * %s String, NULL value emit "". + * %x %X hex + * %p pointer (hex with fixed width of 8) + * %d %i signed decimal + * %u unsigned decimal + * %t timestamp (if available in platform). NOTE: This does not consume any value in parameter list. + * %% outputs single % + * + * %s, %x, %d, and %u support width (example %5s). Width is interpreted as minimum number of characters. + * Hex number is left padded using '0' to desired width. + * Decimal number is left padded using ' ' to desired width. + * String is right padded to desired length. + * + * Newline is used to terminate logging line. + * + * @param fmt Formatter + * @param args Argument list. + */ +_DRAPI_EXTERN_C void drApiLogvPrintf( + const char *fmt, + va_list args); + +_DRAPI_EXTERN_C void drApiLogPrintf( + const char *fmt, + ...); + +#if defined(__INCLUDE_DEBUG) + + #define drDbgPrintf(...) drApiLogPrintf(__VA_ARGS__) + #define drDbgvPrintf(...) drApiLogvPrintf(__VA_ARGS__) + +#else + + #define drDbgPrintf(...) DUMMY_FUNCTION() + #define drDbgvPrintf(...) DUMMY_FUNCTION() + +#endif // __INCLUDE_DEBUG + +#ifndef EOL + #define EOL "\n" +#endif + +#define drDbgPrintLnf(...) do{drDbgPrintf(__VA_ARGS__);dbgS(EOL);}while(FALSE) + + +#endif // __DRAPILOGGING_H__ + diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiMcSystem.h b/mobicore/common/MobiCore/inc/DrApi/DrApiMcSystem.h new file mode 100644 index 0000000..d9a4f04 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiMcSystem.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPIMCSYSTEM_H__ +#define __DRAPIMCSYSTEM_H__ + +#include "DrApiCommon.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Get information about the implementation of the MobiCore Driver API version. + * + * @param drApiVersion pointer to Driver Api version. + * @returns DRAPI_OK if version has been set + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +_DRAPI_EXTERN_C drApiResult_t drApiGetVersion( + uint32_t *drApiVersion); + +/** Install fastcall handler + * + * @param entryTable pointer to entry table. + * @param fastcallId fastcall ID. + * @returns DRAPI_OK if version has been set + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +_DRAPI_EXTERN_C drApiResult_t drApiInstallFc( + void *entryTable, uint32_t fastcallId); + + +_DRAPI_EXTERN_C drApiResult_t drApiFastCall( + uint32_t *fastcall_registers, + uint32_t size); +#ifdef __cplusplus +} +#endif + +#endif // __DRAPIMCSYSTEM_H__ + diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiMm.h b/mobicore/common/MobiCore/inc/DrApi/DrApiMm.h new file mode 100644 index 0000000..0ccd991 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiMm.h @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPIMM_H__ +#define __DRAPIMM_H__ + +#include "DrApiCommon.h" + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------------------------------------------------ +/** Definitions */ + +/** Memory mapping attributes. */ +#define MAP_READABLE (1U << 0) /**< mapping gives have the ability to do read access. */ +#define MAP_WRITABLE (1U << 1) /**< mapping gives have the ability to do write access. */ +#define MAP_EXECUTABLE (1U << 2) /**< mapping gives have the ability to do program execution. */ +#define MAP_UNCACHED (1U << 3) /**< mapping gives have uncached memory access. */ +#define MAP_IO (1U << 4) /**< mapping gives have memory mapped I/O access. Will ignore MAP_UNCACHED, as this would be implied anyway. */ + +//------------------------------------------------------------------------------ +/** Maximum number of parameter . */ +#define MAX_MAR_LIST_LENGTH 8 /**< Maximum list of possible marshaling parameters. */ +/** Marshaled union. */ +typedef struct { + uint32_t functionId; /**< Function identifier. */ + union { + uint32_t parameter[MAX_MAR_LIST_LENGTH]; /* untyped parameter list (expands union to 8 entries) */ + } payload; +} drApiMarshalingParam_t, *drApiMarshalingParam_ptr; + + +//------------------------------------------------------------------------------ +/** Address translation from trustlet to Driver address space. + * Translates an address/pointer given by a Trustlet to the Driver mapping. + * Checks correct address range and null pointer. + * + * @param addr Address in trustlet address space. + * @returns address in Driver virtual space + * @returns NULL if address is equal to NULL or if address is out of D3-D8 address space + */ +addr_t drApiAddrTranslateAndCheck(addr_t addr); + +//------------------------------------------------------------------------------ +#if TBASE_API_LEVEL >= 3 + +/** Addresses translation for a buffer from trustlet to driver address space. + * Checks that the buffer given by its start address and its length fits correct address range. + * Translate the start address/pointer given by a trustlet to the driver's mapping. + * + * @param addr Start address of the buffer in trustlet address space. + * @param len Length of the buffer + * @returns start address in Driver virtual space + * @returns NULL if address is equal to NULL or if the buffer is out of D3-D8 address space + */ +addr_t drApiAddrTranslateAndCheckBuffer(addr_t adr, uint32_t len); + +#endif /* TBASE_API_LEVEL */ + +//------------------------------------------------------------------------------ +/** Maps requesting client and return translated pointer to request parameters + * + * @param ipcReqClient client requesting a service + * @param params pointer to marshaled parameter in client address space + * @returns pointer to parameter for request in the current address space + * @returns NULL in case of error + */ +drApiMarshalingParam_ptr drApiMapClientAndParams( + threadid_t ipcReqClient, + uint32_t params +); + +//------------------------------------------------------------------------------ + +/** Maps a physical page to a virtual address. + * All addresses and lengths must be multiples of page size (4K). + * + * @param startVirt virtual address in Driver address space + * @param len Length of area + * @param startPhys physical address of hardware + * @param attr mapping attributes + * @returns DRAPI_OK in case of success + * @returns E_DRAPI_INVALID_PARAMETER in case any input parameter is not page size aligned or designated virtual memory area does not fit into D1-D2 address range + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ + +drApiResult_t drApiMapPhys( + const addr_t startVirt, + const uint32_t len, + const addr_t startPhys, + const uint32_t attr +); +#if TBASE_API_LEVEL >= 3 +drApiResult_t drApiMapPhys64( + const addr_t startVirt, + const uint32_t len, + const uint64_t startPhys, + const uint32_t attr +); +#endif /* TBASE_API_LEVEL */ + +/** Removes mapping for virtual pages. + * All addresses and lengths must be multiples of page size (4K). + * + * @param startVirt virtual address in Driver address space + * @param len Length of area + * @returns DRAPI_OK in case of success + * @returns E_DRAPI_INVALID_PARAMETER in case any input parameter is not page size aligned or designated virtual memory area does not fit into D1-D2 address range + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ + +drApiResult_t drApiUnmap( + const addr_t startVirt, + const uint32_t len +); + +//------------------------------------------------------------------------------ +/** The function removes mapping for a single page. + * + * @param startVirt virtual address in Driver address space + * @returns DRAPI_OK in case of success + * @returns E_DRAPI_INVALID_PARAMETER in case any input parameter is not page size aligned or designated virtual memory area does not fit into D1-D2 address range + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiUnmapPage4KB( + const page4KB_ptr virtPage +); + +//------------------------------------------------------------------------------ +/** Maps a single physical page to a virtual address + * + * @param physPage virtual address in Driver address space + * @param startPhys physical address of hardware + * @param attr mapping attributes + * @returns DRAPI_OK in case of success + * @returns E_DRAPI_INVALID_PARAMETER in case any input parameter is not page size aligned or designated virtual memory area does not fit into D1-D2 address range + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiMapPhysPage4KB( + const page4KB_ptr virtPage, + const page4KB_ptr physPage, + const uint32_t attr +); +#if TBASE_API_LEVEL >= 3 +drApiResult_t drApiMapPhysPage4KB64( + const page4KB_ptr virtPage, + const uint64_t physPage, + const uint32_t attr +); +#endif /* TBASE_API_LEVEL */ + +//------------------------------------------------------------------------------ +/** Maps a physical page with hardware interface + * This is prepared auxiliary function that at first removes mapping of the virtPage (if present) + * and then maps it with MAP_READABLE | MAP_WRITABLE | MAP_IO attributes + * + * @param physPage virtual address in Driver address space + * @param startPhys physical address of hardware + * @returns DRAPI_OK in case of success + * @returns E_DRAPI_INVALID_PARAMETER in case any input parameter is not page size aligned or designated virtual memory area does not fit into D1-D2 address range + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiMapPhysPage4KBWithHardware( + const page4KB_ptr virtPage, + const page4KB_ptr physPage +); +#if TBASE_API_LEVEL >= 3 +drApiResult_t drApiMapPhysPage4KBWithHardware64( + const page4KB_ptr virtPage, + const uint64_t physPage +); +#endif /* TBASE_API_LEVEL */ + +//------------------------------------------------------------------------------ +/** Converts virtual address (in Driver address space) to physical address + * + * @param taskid Reserved for Future Use. It must be set to zero. + * @param virtAddr virtual address in Driver address space + * @param physAddr physical address + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiVirt2Phys( + const taskid_t taskid, + const addr_t virtAddr, + addr_t * physAddr +); +#if TBASE_API_LEVEL >= 3 +drApiResult_t drApiVirt2Phys64( + const taskid_t taskid, + const addr_t virtAddr, + uint64_t * physAddr +); +#endif /* TBASE_API_LEVEL */ + +//------------------------------------------------------------------------------ +/** Clean all data cache + * + * NOTE: Currently addr is always NULL. + * When extending this for not-clean-all, one can assume that there is + * more parameters ONLY if addr is non-NULL. + * Also this ensures that more specific cleans are mapped to cleanall, if specific clean is not supported. + * + * @param none + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiCacheDataCleanAll( void ); + + +//------------------------------------------------------------------------------ +/** Cleans and invalidates all data cache + * + * NOTE: Currently addr is always NULL. + * When extending this for not-clean-invalidate-all, one can assume that there is + * more parameters ONLY if addr is non-NULL. + * Also this ensures that more specific cleans are mapped to cleanall, if specific clean is not supported. + * + * @param none + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiCacheDataCleanInvalidateAll( void ); + + +//------------------------------------------------------------------------------ +#if TBASE_API_LEVEL >= 3 + +/** Clean a portion of the data cache by MVA + * + * @param virtAddrStart + * @param virtAddrEnd + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiCacheDataCleanRange( + addr_t *virtAddrStart, + uint32_t len, + uint32_t flags +); + + +//------------------------------------------------------------------------------ +/** Cleans and invalidates a portion of data cache by MVA + * + * @param virtAddrStart + * @param virtAddrEnd + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiCacheDataCleanInvalidateRange( + addr_t *virtAddrStart, + uint32_t len, + uint32_t flags +); + +//------------------------------------------------------------------------------ +/** Cache clean attributes */ +#define DRAPI_CACHE_ALL (0xff) +#define DRAPI_CACHE_L1_ONLY (0x1) +#define DRAPI_CACHE_L1_L2 (0x2) +#endif /* TBASE_API_LEVEL */ + +//------------------------------------------------------------------------------ +/** Memory type attributes */ +#define DRAPI_PHYS_MEM_TYPE_HIGH_SECURE (1U<<0) /**< High secure memory. (Typically iRam) */ +#define DRAPI_PHYS_MEM_TYPE_SECURE (1U<<1) /**< Secure memory in Dram */ +#define DRAPI_PHYS_MEM_TYPE_NON_SECURE (1U<<2) /**< NonSecure memory in Dram. Accessible from NonSecure world */ + +/** Returns physical memory type (secure or non-secure) + * + * @param type pointer to address where type is returned + * @param addr start address of checked memory + * @param size size checked memory + * @returns E_OK in case of success + */ + +drApiResult_t drApiGetPhysMemType( + uint32_t *type, + addr_t addr, + uint32_t size + ); +#if TBASE_API_LEVEL >= 3 +drApiResult_t drApiGetPhysMemType64( + uint32_t *type, + uint64_t addr, + uint32_t size + ); +#endif /* TBASE_API_LEVEL */ + +#ifdef __cplusplus +} +#endif + +#endif // __DRAPIMM_H__ diff --git a/mobicore/common/MobiCore/inc/DrApi/DrApiThread.h b/mobicore/common/MobiCore/inc/DrApi/DrApiThread.h new file mode 100644 index 0000000..45c297f --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/DrApiThread.h @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __DRAPI_THREAD_H__ +#define __DRAPI_THREAD_H__ + +#include "DrApiCommon.h" +#include "DrApiIpcMsg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------------------------------------------------ +/** Definitions */ +#define NILTASK 0 /**< returns NILTASK. */ +#define NILTHREAD 0 /**< returns NILTHREAD. */ + +#define MAX_PRIORITY (15U) /**< maximum priority of a task or thread. */ + +#if defined(DRIVER) +#define ANYINTR 0x0000FFFF /**< returns ANYINTR. */ +#endif + +#define TASK_THREAD_QUOTA_SHL 24 +#define TASK_TIME_QUOTA_MASK ((1 << TASK_THREAD_QUOTA_SHL) - 1) /**< mask to get/set time quota of a task. */ +#define TIME_INFINITE ((time_t)TASK_TIME_QUOTA_MASK) /**< returns infinite. */ + +/* Control ids for drApiThreadExRegs() API call */ +#define THREAD_EX_REGS_IP (1U << 0) /**< currently set instruction pointer of the thread is replaced by the specified instruction pointer. */ +#define THREAD_EX_REGS_SP (1U << 1) /**< currently set stack pointer of the thread is replaced by the specified stack pointer. */ + +//------------------------------------------------------------------------------ +// Time data type +typedef word_t time_t, *time_ptr; + + +//------------------------------------------------------------------------------ +/** + * Returns task ID for current task. + * + * @returns taskid + * @returns 0 in case of any error + */ +taskid_t drApiGetTaskid( void ); + +//------------------------------------------------------------------------------ +/** + * The function returns thread ID corresponding to task ID and thread number specified. + * + * @param taskid taskid having the thread. + * @param threadno Thread number in task. + * + * @returns Thread ID in case of success + * @returns 0 if task ID or thread number are invalid. + */ +threadid_t drApiTaskidGetThreadid( + taskid_t taskid, + threadno_t threadNo +); + +//------------------------------------------------------------------------------ +/** + * The function returns thread ID for current task corresponding to thread number specified. + * + * @param threadNo Thread number in current task. + * + * @returns Thread ID in case of success + * @returns 0 thread number is invalid. + * + */ +threadid_t drApiGetLocalThreadid( + threadno_t threadNo +); + +//------------------------------------------------------------------------------ +/** Suspend current thread. + * + * @param timeout Time to suspend thread. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiThreadSleep( + time_t timeout +); + +//------------------------------------------------------------------------------ +/** Starts a thread in Driver. + * @param threadNo Thread number in task. + * @param threadEntry Thread entry function + * @param stackPointer Thread top stack pointer (declared statically using DECLARE_STACK) + * @param priority Thread priority (Maximum level is defined as MAX_PRIORITY, higher priority level corresponds to higher priority thread) + * @param localExceptionHandler The parameter specifies the number of a thread that serves as an exception handler + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiStartThread( + const threadno_t threadNo, + const addr_t threadEntry, + const stackTop_ptr stackPointer, + const uint32_t priority, + const threadno_t localExceptionHandlerThreadNo +); + + +//------------------------------------------------------------------------------ +/** Stop a thread in Driver. + * If thread no. of thread to stop is set to NILTHREAD, + * the current thread is stopped. The to stopped thread is detached from any + * previously attached interrupts. If any thread is waiting for stopped thread + * to do any ipc, this ipc is aborted. + * + * @param threadNo Thread number in task. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ + +drApiResult_t drApiStopThread( + const threadno_t threadNo +); + + +//------------------------------------------------------------------------------ +/** Resumes a thread in Driver. + * + * @param threadNo Thread number in task. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ + +drApiResult_t drApiResumeThread( + const threadno_t threadNo +); + + +//------------------------------------------------------------------------------ +/** Sets priority level for a thread in Driver. + * @param threadNo Thread number in task. + * @param priority Thread priority (Maximum level is defined as MAX_PRIORITY, higher priority level corresponds to higher priority thread) + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiSetThreadPriority( + const threadno_t threadNo, + const uint32_t priority +); + +//------------------------------------------------------------------------------ +/** + * Sets the value registers for specified thread. + * if the @ref THREAD_EX_REGS_IP bit of argument ctrl is set, the currently set instruction pointer is exchanged by the value of the argument ip (3). + * if the @ref THREAD_EX_REGS_SP bit of argument ctrl is set, the currently set stack pointer is exchanged by the value of the argument sp (4). + * + * @param threadNo Number of the thread. + * @param ctrl Control flags + * @param ip ip value + * @param sp sp value + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiThreadExRegs( + const threadno_t threadNo, + const uint32_t ctrl, + const addr_t ip, + const addr_t sp +); + +//------------------------------------------------------------------------------ +#if TBASE_API_LEVEL >= 3 +/** + * Restart an internal thread with given IP and SP. + * + * @param threadNo Number of the thread. + * @param ip ip value + * @param sp sp value + * + * @retval DRAPI_OK or relevant error code. + */ +drApiResult_t drApiRestartThread( + const threadno_t threadno, + const addr_t ip, + const addr_t sp +); +#endif /* TBASE_API_LEVEL */ + +//------------------------------------------------------------------------------ +/** Attaches an interrupt with the specified trigger condition to current thread. + * Please refer to the target platform specific MobiCore documentation about + * the trigger modes supported for each interrupt. In most cases, the mode + * parameters will be INTR_MODE_RAISING_EDGE, as interrupts usually indicate + * that a certain event has happened. + * + * @param intrNo interrupt number. + * @param intrMode interrupt mode. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIntrAttach( + intrNo_t intrNo, + intrMode_t intrMode +); + + +//------------------------------------------------------------------------------ +/** Detaches interrupt from current thread. + * + * @param intrNo interrupt number. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiIntrDetach( + intrNo_t intrNo +); + +//------------------------------------------------------------------------------ +/** Wait with infinite timeout for interrupt message from kernel. + * + * @param intrNo interrupt number (if ANYINTR is used, the interrupt is returned in the parameter intrRet). + * @param timeout timeout to wait (allowed the same values as for MTK signal_wait()). + * @param pIntrRet receives interrupt. Parameter can be NULL if caller does not need this. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiWaitForIntr( + const intrNo_t intrNo, + const uint32_t timeout, + intrNo_t *pIntrRet +); + +//------------------------------------------------------------------------------ +/** + * Trigger software interrupt in the NWd to notify it. + * + * @param intrNo interrupt number. + * + * @returns DRAPI_OK in case of success + * @returns any combination of DRAPI_ERROR_CREATE(Driver specific error code, MTK error code) + */ +drApiResult_t drApiTriggerIntr( + intrNo_t intrNo +); + + +#ifdef __cplusplus +} +#endif + +#endif // __DRAPI_THREAD_H__ diff --git a/mobicore/common/MobiCore/inc/DrApi/version.h b/mobicore/common/MobiCore/inc/DrApi/version.h new file mode 100644 index 0000000..b8621b4 --- /dev/null +++ b/mobicore/common/MobiCore/inc/DrApi/version.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ +#ifndef DRAPI_VERSION_H_ +#define DRAPI_VERSION_H_ + +#define DRAPI_VERSION_MAJOR 1 +#define DRAPI_VERSION_MINOR 1 + +#endif /** DRAPI_VERSION_H_ */ diff --git a/mobicore/common/MobiCore/inc/FwDrv/DrApiFastCall.h b/mobicore/common/MobiCore/inc/FwDrv/DrApiFastCall.h new file mode 100644 index 0000000..6477fe3 --- /dev/null +++ b/mobicore/common/MobiCore/inc/FwDrv/DrApiFastCall.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef FASTCALL_H_ +#define FASTCALL_H_ + +/** Firmware Driver and Fastcall Handlers + * + * Mobicore can have one firmware driver. Such driver is loaded + * typically at boot, and cannot be unloaded. Firmware driver is + * intended to act as system integration means, and is not intended + * to act as typical peripheral driver. + * + * Fastcall handlers + * Firmware driver can register fastcall handler in some platforms. + * Fastcall handler is called for fastcalls unknown to Mobicore. + * + * Fastcall handlers get driver memory mappings in range of 0-2MB + * at the time handler is installed. Driver must not unmap any of + * these mappings. If new mappings are made, they cannot be relied + * to be visible in fastcall hook function. + * + * Fastcall handler may map sections (of size 1M). These mappings are not + * visible to driver. + * + * Fastcall handler gets access to number of registers at the time of + * fastcall was made in NWd. Actual number of registers depends on + * platform, but is always at least 4 (r0-r3). + * + * Notes on use of Fastcall handlers + * Fastcall handlers + * - cannot call any TlApi or DrApi functions. + * - cannot have synchronization with firmware driver. + * - do not have large stack. If stack is needed, switch to your own. + * - may be executed concurrently in all CPUs. + * - must not cause exceptions. There is no means to recover in case + * of exception. + * + */ + +#define FASTCALL_OWNER_TZOS (0xFF000000) +#define FASTCALL_OWNER_SIP (0x81000000) +#define FASTCALL_OWNER_OEM (0x83000000) +#define FASTCALL_OWNER_STD (0x84000000) + +#define FASTCALL_OWNER_MASK (0xFF000000) + +#define FCH_L1_MAX 12 + +typedef word_t *fastcall_registers_t; + +/** Context for FCs hook call + * + * This is (currently) shared between all processors + */ +struct fcContext { + word_t size; // Size of context + // Callback to modify L1 entry. + // idx is the address in MBytes of the entry to modify (starting at 8MB). + // (for example idx=2 will modify the entry for address 10MB) + // Return the virtual address corresponding to modified entry. + // Return NULL if there is an error. + // 64 bits version must be used to modify L1 table in LPAE mode. + void *(*setL1Entry)(struct fcContext *context, word_t idx, word_t entry); + word_t registers; // Number of registers available in fastcall + void (*prepareIdenticalMapping)(struct fcContext *context, addr_t start, word_t length, word_t flags); + void (*generateFcNotification)(struct fcContext *context); + void *(*setL1Entry64)(struct fcContext *context, word_t idx, uint64_t entry); +}; + +/* Fastcall handler initialization + * + * Called once before any fastcall. + * Can map memories for fastcall context. + * This function must never cause any exceptions. + * Call is executed in SVC mode. + * + * Return value + * 0 Successfull initialization. + * Other cancel hook installation + */ +typedef word_t (*fcInitHook)( + struct fcContext *context +); + + +/* Fastcall handler + * + * Executed possibly concurrently in all CPUs. + * This function must never cause any exceptions. + * Call is executed in IRQ mode. + * On Entry + * fastcall_regs_t[0]...fastcall_regs_t[15] contain input registers. + * On exit + * fastcall_regs_t[0]...fastcall_regs_t[N] contain r0...rN. + * If driver did not handle fastcall, registers must be unmodified. + * If driver handled fastcall registers r0...r3 may be modified. + * Registers beyond r3 must not be modified. Result of any + * modification is unpredictable. + * Return values + * Nonzero return value means that fastcall is handled. + */ +typedef word_t (*fcEntryHook)( + fastcall_registers_t *regs_t, + struct fcContext *context +); + + +#endif /* FASTCALL_H_ */ diff --git a/mobicore/common/MobiCore/inc/GP/tee_type.h b/mobicore/common/MobiCore/inc/GP/tee_type.h new file mode 100644 index 0000000..8cf5898 --- /dev/null +++ b/mobicore/common/MobiCore/inc/GP/tee_type.h @@ -0,0 +1,143 @@ +/** + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * Definition of the machine-specific integer types + **/ +#ifndef __TEE_TYPE_H__ +#define __TEE_TYPE_H__ + +/* C99 integer types */ +#if (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) &&(!defined(ANDROID)) + +#include + +/* Figure out if a 64-bit integer types is available */ +#if \ + defined(_MSC_VER) || \ + defined(__SYMBIAN32__) || \ + defined(_WIN32_WCE) || \ + (defined(ULLONG_MAX) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFFULL) || \ + (defined(ULONG_LONG_MAX) && ULONG_LONG_MAX == 0xFFFFFFFFFFFFFFFFULL) +typedef unsigned long long uint64_t; +typedef long long int64_t; +#else +#define __S_TYPE_INT64_UNDEFINED +#endif + +#if UINT_MAX == 0xFFFFFFFF +typedef unsigned int uint32_t; +typedef int int32_t; +#elif ULONG_MAX == 0xFFFFFFFF +typedef unsigned long uint32_t; +typedef long int32_t; +#else +#error This compiler is not supported. +#endif + +#if USHRT_MAX == 0xFFFF +typedef unsigned short uint16_t; +typedef short int16_t; +#else +#error This compiler is not supported. +#endif + +#if UCHAR_MAX == 0xFF +typedef unsigned char uint8_t; +typedef signed char int8_t; +#else +#error This compiler is not supported. +#endif + +#if !defined(__cplusplus) +typedef unsigned char bool; +#define false ( (bool)0 ) +#define true ( (bool)1 ) +#endif + +#else /* !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L */ + +#include +#include + +#endif /* !(!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) */ + +#include + +#ifndef NULL +# ifdef __cplusplus +# define NULL 0 +# else +# define NULL ((void *)0) +# endif +#endif + +#define IN +#define OUT + +/* + * Definition of other common types + */ + +// to delete when all completed +typedef uint32_t TEE_Result; +typedef TEE_Result TEEC_Result; + +typedef uint32_t TEE_HANDLE; + +/** Definition of an UUID (from RFC 4122 http://www.ietf.org/rfc/rfc4122.txt) */ +typedef struct TEE_UUID { + uint32_t timeLow; + uint16_t timeMid; + uint16_t timeHiAndVersion; + uint8_t clockSeqAndNode[8]; +} TEE_UUID; +typedef TEE_UUID TEEC_UUID; + +/** Type definition for a TEE Identity */ +typedef struct TEE_Identity { + uint32_t login; + TEE_UUID uuid; +} TEE_Identity; + +typedef struct __TEE_PropSetHandle { + unsigned char reserved; +} __TEE_PropSetHandle; + +typedef struct __TEE_PropSetHandle* TEE_PropSetHandle; + +/* Property Sets Pseudo Handles */ +#define TEE_PROPSET_CURRENT_TA (TEE_PropSetHandle)0xFFFFFFFF +#define TEE_PROPSET_CURRENT_CLIENT (TEE_PropSetHandle)0xFFFFFFFE +#define TEE_PROPSET_TEE_IMPLEMENTATION (TEE_PropSetHandle)0xFFFFFFFD + + +/* DLL Import/Export directives */ + +#if defined(WIN32) || defined(__ARMCC_VERSION) || defined(__WINSCW__) || defined(_WIN32_WCE) +# define S_DLL_EXPORT __declspec(dllexport) +# define S_DLL_IMPORT __declspec(dllimport) +# define S_NO_RETURN __declspec(noreturn) +#elif defined(__GNUC__) +# define S_DLL_EXPORT __attribute__ ((visibility ("default"))) +# define S_DLL_IMPORT __attribute__ ((visibility ("default"))) +# define S_NO_RETURN __attribute__ ((noreturn)) +#else +# define S_DLL_EXPORT +# define S_DLL_IMPORT +# define S_NO_RETURN +#endif + +#if defined(_MSC_VER) +#define __func__ __FUNCTION__ +#endif + +#endif /* __TEE_TYPE_H__ */ diff --git a/mobicore/common/MobiCore/inc/GP/uuid_attestation.h b/mobicore/common/MobiCore/inc/GP/uuid_attestation.h new file mode 100644 index 0000000..ab8f1be --- /dev/null +++ b/mobicore/common/MobiCore/inc/GP/uuid_attestation.h @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __TEE_UUID_ATTESTATION_H__ +#define __TEE_UUID_ATTESTATION_H__ + +#include "tee_type.h" + +// Sizes of the fields of attestation structure +#define AT_MAGIC_SIZE 8 +#define AT_SIZE_SIZE sizeof(uint32_t) +#define AT_VERSION_SIZE sizeof(uint32_t) +#define AT_UUID_SIZE sizeof(TEE_UUID) + +// Sizes of the fields used to generate signature +#define AT_TAG_SIZE 20 +#define AT_SHA1_HASH_SIZE 20 + +// Max size of RSA modulus supported +#define AT_MODULUS_MAX_SIZE 256 +// Max size of RSA public exponent supported +#define AT_PUBLIC_EXPO_MAX_SIZE 4 + +// Attestation version +#define AT_VERSION 1 + +// Name space ID (the UUID of the RSA OID) +const uint8_t RSA_OID_UUID[AT_UUID_SIZE] = {0x6b, 0x8e, 0x02, 0x6b, 0x63, 0xc1, 0x5d, 0x58, 0xb0, 0x64, 0x00, 0xd3, 0x51, 0x89, 0xce, 0x65}; +// Magic word +const char MAGIC[AT_MAGIC_SIZE] = "TAUUID\0"; + +// Tag for signature generation +const char TAG[AT_TAG_SIZE]="Trusted Application"; + +// Public key structure +typedef struct uuid_public_key { + uint32_t type; // TEE TYPE RSA KEYPAIR: 0xa0000030 + uint16_t modulus_bytes; // Length of the modulus in bytes + uint16_t exponent_bytes; // Length of the exponent in bytes + uint8_t data[]; // Key material +} uuid_public_key; + +// Attestation structure +typedef struct uuid_attestation { + uint8_t magic[AT_MAGIC_SIZE]; // Magic word: "TAUUID\0\0" + uint32_t size; // Attestation size (4 bytes) + uint32_t version; // Version number: 1 (4 bytes) + uint8_t uuid[AT_UUID_SIZE]; // UUID + uuid_public_key key; // Public key +} uuid_attestation; + +#endif /* __TEE_UUID_ATTESTATION_H__ */ diff --git a/mobicore/ClientLib/include/GpTci.h b/mobicore/common/MobiCore/inc/McLib/GpTci.h similarity index 86% rename from mobicore/ClientLib/include/GpTci.h rename to mobicore/common/MobiCore/inc/McLib/GpTci.h index 55639d4..3a561fb 100644 --- a/mobicore/ClientLib/include/GpTci.h +++ b/mobicore/common/MobiCore/inc/McLib/GpTci.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -28,6 +28,7 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + #ifndef _GP_TCI_H_ #define _GP_TCI_H_ @@ -36,9 +37,15 @@ typedef struct { uint32_t b; } TEE_Value; +#if defined (TRUSTEDAPP) typedef struct { - uint32_t sVirtualAddr; /**< The virtual address of the Bulk buffer regarding the address space of the Trustlet, already includes a possible offset! */ + void *sVirtualAddr; /**< The virtual address of the Bulk buffer regarding the address space of the Trustlet, already includes a possible offset! */ uint32_t sVirtualLen; /**< Length of the mapped Bulk buffer */ +} mcBulkMap_t; +#endif + +typedef struct { + mcBulkMap_t mapInfo; uint32_t outputSize; } _TEEC_MemoryReferenceInternal; @@ -71,6 +78,11 @@ typedef struct { uint32_t returnStatus; } _TEEC_TCI; +#define TEEC_MEMREF_WHOLE 0xC +#define TEEC_MEMREF_PARTIAL_INPUT 0xD +#define TEEC_MEMREF_PARTIAL_OUTPUT 0xE +#define TEEC_MEMREF_PARTIAL_INOUT 0xF + /** * Termination codes */ diff --git a/mobicore/common/MobiCore/inc/McLib/TlApiCryptoMarshal.h b/mobicore/common/MobiCore/inc/McLib/TlApiCryptoMarshal.h new file mode 100644 index 0000000..641a0ce --- /dev/null +++ b/mobicore/common/MobiCore/inc/McLib/TlApiCryptoMarshal.h @@ -0,0 +1,388 @@ + /* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + * + * + * @addtogroup TlApi + * @{ + * @file + * Marshaling types and declarations. + * + * Functions for the marshaling of function ID and parameters. + * + */ + +#ifndef __TLAPICRYPTOMARSHAL_H__ +#define __TLAPICRYPTOMARSHAL_H__ + + +#include "mcDriverId.h" + +#include "TlApi/TlApiError.h" +#include "TlApi/TlApiCrypto.h" +#include "TlApi/TlApiSecurity.h" +#include "TlApi/TlApiMcSystem.h" +#include "TlApi/TlApiTime.h" + + +/** Each function must have its own ID. + * Extend this list if you add a new function. + */ +typedef enum { + FID_KPD_GRAB_KEYPAD = 0, /**< Function to reserve the keypad. */ + FID_KPD_GET_C, /**< Function to read a character from the keypad. */ + FID_KPD_GET_MULTIPLE_C, /**< Function to read multiple characters from the keypad. */ + FID_KPD_RELEASE_KEYPAD /**< Function to release the grabbed keypad. */ +} kpdFuncID_t; + + +/** Each function must have its own ID. + * Extend this list if you add a new function. + */ +typedef enum { + FID_CRYPTO_MD = 0, /**< ID for message digest algorithms. */ + FID_CRYPTO_MD_INIT = 1, /**< Function to init a message digest. */ + FID_CRYPTO_MD_INIT_WITH_DATA = 2, /**< Function to init a message digest with data. */ + FID_CRYPTO_MD_UPDATE = 3, /**< Function to update a message digest. */ + FID_CRYPTO_MD_DOFINAL = 4, /**< Function to finalize a message digest. */ + + FID_CRYPTO_SIG = 5, /**< ID for signature algorithms. */ + FID_CRYPTO_SIG_INIT = 6, /**< Function to init a signature. */ + FID_CRYPTO_SIG_INIT_WITH_DATA = 7, /**< Function to init a signature with data. */ + FID_CRYPTO_SIG_UPDATE = 8, /**< Function to update a signature. */ + FID_CRYPTO_SIG_SIGN = 9, /**< Function to make a signature. */ + FID_CRYPTO_SIG_VERIFY = 10, /**< Function to verify a signature. */ + + FID_CRYPTO_RNG = 11, /**< ID for RNG algorithms. */ + FID_CRYPTO_RNG_GENERATE_DATA = 12, /**< Function to generate random data. */ + + FID_CRYPTO_CIPHER = 13, /**< ID for cipher algorithms. */ + FID_CRYPTO_CIPHER_INIT = 14, /**< Function to init a cipher. */ + FID_CRYPTO_CIPHER_INIT_WITH_DATA = 15, /**< Function to init a cipher with data. */ + FID_CRYPTO_CIPHER_UPDATE = 16, /**< Function to update a cipher. */ + FID_CRYPTO_CIPHER_DOFINAL = 17, /**< Function to finalize a cipher. */ + + FID_CRYPTO_SESSION_ABORT = 18, /**< Function to abort a crypto session. */ + + FID_CRYPTO_GENERATE_KEY_PAIR = 19, /**< Function to generate a key pair. */ + FID_CRYPTO_GENERATE_KEY_PAIR_BUFFER = 20, /**< Function to generate a key pair into a buffer. */ + + FID_SECURITY_WRAP_OBJECT = 21, /**< Function to wrap given data and create a secure object. */ + FID_SECURITY_UNWRAP_OBJECT = 22, /**< Function to unwrap given secure object and create plaintext data. */ + FID_SECURITY_GET_SUID = 23, /**< Function to acquire System on chip Unique ID. */ + FID_SECURITY_IS_DEVICE_BOUND = 24, /**< Currently not used. */ + FID_SECURITY_BIND_DEVICE = 25, /**< Currently not used. */ + + FID_SYSTEM_GET_VERSION = 26, /**< Function to get information about the underlying MobiCore version. */ + + FID_SECURITY_GET_TIME_STAMP = 27, /**< Function to get a secure time stamp. */ + + FID_SECURITY_DERIVE_KEY = 28, /**< Function to derive key. */ + + FID_CRYPTO_MD_DOFINAL_WITHOUT_CLOSE = 29, /**< Function to finalize a message digest without close. */ + FID_CRYPTO_OVERWRITE_KEY = 30, /**< Function to overwrite key. */ + FID_CRYPTO_MAC_INIT = 31, /**< Function to initialize hmac structures with key that is earlier given. */ + FID_CRYPTO_SIG_SIGN_WITHOUT_CLOSE = 32, /**< Function to finalize a sign without close. */ + FID_CRYPTO_SIG_VERIFY_WITHOUT_CLOSE = 33, /**< Function to finalize a verify without close. */ + FID_CRYPTO_CIPHER_WITHOUT_CLOSE = 34, /**< Function to finalize a cipher without close. */ + FID_SECURITY_ENDORSE = 35, /**< Function to create endorsement */ + + FID_CRYPTO_CIPHER_UPDATE_IV = 36, /**< Function to update cipher IV */ + +} cryptoFuncID_t; + + +/** Marshaled function parameters. + * structs and union of marshaling parameters via TlApi. + * + * @note The structs can NEVER be packed ! + * @note The structs can NOT used via sizeof(..) ! + */ +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of session to be aborted */ +} tlApiCrAbort_t, *tlApiCrAbort_ptr; + + +typedef struct { + tlApiKeyPair_t *keyPair; /* reference to key pair structure */ + tlApiKeyPairType_t type; /* see enum keyPairType_t */ + size_t len; /* requested byte length of keys */ + uint8_t *buffer; /* reference to buffer into which generated key components are written */ + size_t bufferLen; /* length of buffer for generated components */ +} tlApiCrGenerateKeyPair_t, *tlApiCrGenerateKeyPair_ptr; + + +typedef struct { + tlApiCrSession_t *pSessionHandle; /* reference to generated Cipher session handle */ + tlApiCipherAlg_t alg; /* see enum cipherMode_t */ + tlApiCipherMode_t mode; /* TLAPI_MODE_ENCRYPT or TLAPI_MODE_DECRYPT */ + const tlApiKey_t *key; /* key for this session */ + const uint8_t *buffer; /* reference to algorithm specific data like initial values for CBC */ + size_t bufferLen; /* length of buffer containing algorithm specific data */ +} tlApiCipherInit_t, *tlApiCipherInit_ptr; + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running Cipher session */ + const uint8_t *srcData; /* reference to input data to be encrypted/decrypted */ + size_t srcLen; /* byte length of input data to be encrypted/decrypted */ + uint8_t *destData; /* reference to result area */ + size_t *destLen; /* [in] byte length of output buffer. [out] byte length of generated output data */ +} tlApiCipherUpdate_t, *tlApiCipherUpdate_ptr; + + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running Cipher session */ + const uint8_t *srcData; /* reference to input data to be encrypted/decrypted */ + size_t srcLen; /* byte length of input data to be encrypted/decrypted */ + uint8_t *destData; /* reference to result area */ + size_t *destLen; /* [in] byte length of buffer for output data. [out] byte length of generated output */ +} tlApiCipherDoFinal_t, *tlApiCipherDoFinal_ptr; + + +typedef struct { + tlApiCrSession_t *pSessionHandle; /* reference to generated Signatures session handle */ + const tlApiKey_t *key; /* key for this session */ + tlApiSigMode_t mode; /* TLAPI_MODE_SIGN or TLAPI_MODE_VERIFY */ + tlApiSigAlg_t alg; /* see enum of algorithms */ + const uint8_t *buffer; /* reference to algorithm specific data like seed for hash */ + size_t bufferLen; /* length of buffer containing algorithm specific data */ +} tlApiSignatureInit_t, *tlApiSignatureInit_ptr; + + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running Signature session */ + const uint8_t *message; /* reference to message to be signed/verified */ + size_t messageLen; /* byte length of message */ +} tlApiSignatureUpdate_t, *tlApiSignatureUpdate_ptr; + + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running Signature session */ + const uint8_t *message; /* reference to message to be signed */ + size_t messageLen; /* byte length of message */ + uint8_t *signature; /* reference to generated signature */ + size_t *signatureLen; /* [in] byte length of signature buffer. [out] byte length of generated signature */ +} tlApiSignatureSign_t, *tlApiSignatureSign_ptr; + + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running Signature session */ + const uint8_t *message; /* reference to message to be verified */ + size_t messageLen; /* byte length of message */ + const uint8_t *signature; /* reference to signature to be verified */ + size_t signatureLen; /* byte length of signature */ + bool *validity; /* reference to verification result, TRUE if verified, otherwise FALSE */ +} tlApiSignatureVerify_t, *tlApiSignatureVerify_ptr; + +typedef struct { + tlApiCrSession_t *pSessionHandle; /* reference to generated Message Digest session handle */ + tlApiMdAlg_t alg; /* see enum mdAlg_t */ + const uint8_t *buffer; /* reference to previously calculated hash data */ + const uint8_t *lenPreHashedData; /* byte array in big endian format containing length of previously calculated hash */ +} tlApiMessageDigestInit_t, *tlApiMessageDigestInit_ptr; + + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running session Message Digest session */ + const uint8_t *message; /* reference to message to be hashed */ + size_t messageLen; /* byte length of input data to be hashed */ +} tlApiMessageDigestUpdate_t, *tlApiMessageDigestUpdate_ptr; + + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running session Message Digest session */ + const uint8_t *message; /* reference to message to be hashed */ + size_t messageLen; /* byte length of message */ + uint8_t *hash; /* reference to generated hash */ + size_t *hashLen; /* [in] byte length of hash buffer. [out] byte length of generated hash data */ +} tlApiMessageDigestDoFinal_t, *tlApiMessageDigestDoFinal_ptr; + + +typedef struct { + tlApiRngAlg_t alg; /* see enum randomDataGenerationAlg_t */ + uint8_t *randomBuffer; /* reference to generated random data */ + size_t *randomLen; /* byte length of requested random data */ +} tlApiRandomGenerateData_t, *tlApiRandomGenerateData_ptr; + + +typedef struct { + uint32_t unused; /* place holder - unused !!! */ +} tlApiGrabKeypad_t, *tlApiGrabKeypad_ptr; + + +typedef struct { + uint32_t *c; /* pointer to the rx-character */ + uint32_t timeout; /* time in milliseconds to wait */ +} tlApiGetKeypadEvent_t, *tlApiGetKeypadEvent_ptr; + + +typedef struct { + uint32_t unused; /* place holder - unused !!! */ +} tlApiReleaseKeypadGrab_t, *tlApiReleaseKeypadGrab_ptr; + + +typedef struct { + const void *src; /* Source data. */ + size_t plainLen; /* Length of header. */ + size_t encryptedLen; /* Length of payload to encrypt. */ + void *dest; /* Destination buffer (secure object). */ + size_t *destLen; /* [in] Length of the destination buffer. + [out] Length of output data. */ + mcSoContext_t context; /* Context of operation. */ + mcSoLifeTime_t lifetime; /** Secure object lifetime and flags combined. */ + const tlApiSpTrustletId_t *consumer; /* NULL or trustlet identifier for delegated wrapping. */ +} tlApiWrapObject_t, *tlApiWrapObject_ptr; + + +typedef struct { + void *src; /* Source data (secure object). */ + void *dest; /* Destination buffer (unwrapped data). */ + size_t *destLen; /* [in] Length of the destination buffer. + [out] Length of output data. */ + size_t srcLen; /* [in] Length of the source buffer. */ + uint32_t flags; /* [in] Flags for unwrap. */ +} tlApiUnwrapObject_t, *tlApiUnwrapObject_ptr; + + +typedef struct { + mcSuid_t *suid; /**< System on chip Unique ID */ +} tlApiGetSuid_t, *tlApiGetSuid_ptr; + + +typedef struct { + mcVersionInfo_t *mcVersionInfo; /**< Version of MobiCore */ +} tlApiGetMcVersion_t, *tlApiGetMcVersion_ptr; + + +typedef struct { + timestamp_t *ts; /**< Returned time stamp */ + tsSource_t source; /**< Requested timer source */ +} tlApiGetTimeStamp_t, *tlApiGetTimeStamp_ptr; + + +typedef struct { + const void *seed; /* Source seed. */ + size_t seedLen; /* Length of seed. */ + void *dest; /* Destination buffer (key). */ + size_t destLen; /* Length of the destination buffer. */ + mcSoContext_t context; /* Context of operation. */ + mcSoLifeTime_t lifetime; /** key lifetime. */ +} tlApiDeriveKey_t, *tlApiDeriveKey_ptr; + +typedef struct { + tlApiCrSession_t sessionHandle; /* handle of a running session Message Digest session */ + const uint8_t *message; /* reference to message to be hashed */ + size_t messageLen; /* byte length of message */ + uint8_t *hash; /* reference to generated hash */ + size_t *hashLen; /* [in] byte length of hash buffer. [out] byte length of generated hash data */ +} tlApiMessageDigestDoFinalWithOutClose_t, *tlApiMessageDigestDoFinalWithOutClose_ptr; + +typedef struct { + tlApiCrSession_t sessionHandle; + const tlApiKey_t *keyData; +} tlApiOverwriteKey_t, *tlApiOverwriteKey_ptr; + +typedef struct { + tlApiCrSession_t sessionHandle; + uint8_t *iv; + size_t ivLen; +} tlApiMacInit_t, *tlApiMacInit_ptr; + +typedef struct { + tlApiCrSession_t sessionHandle; + const uint8_t *iv; + size_t ivLen; +} tlApiCipherUpdateIV_t, *tlApiCipherUpdateIV_ptr; + +#define STH_PUBLIC_FILE_NAME_SIZE 20 +typedef struct S_UUID_t { + uint32_t timeLow; + uint16_t timeMid; + uint16_t timeHiAndVersion; + uint8_t clockSeqAndNode[8]; +} UUID_t; + +typedef enum { + STH_MESSAGE_TYPE_LOOK = 0, + STH_MESSAGE_TYPE_READ, + STH_MESSAGE_TYPE_WRITE, + STH_MESSAGE_TYPE_DELETE +} tlApiStorageOps_t; + +typedef struct { + uint32_t status; + uint8_t type; + uint8_t reserved0; + uint16_t flags; + uint32_t payloadLen; + UUID_t uuid; + unsigned char filename[STH_PUBLIC_FILE_NAME_SIZE]; + unsigned char payload[]; +} STH_TA_message_t; + +/*typedef struct { + storageOps_t operation; + union { + storageLook_t look; + storageRead_t read; + storageWrite_t write; + storageDelete_t del; + }payload; +} marshalingParam;*/ // merge to marshalingParam + +typedef struct { + const void *msg; /* Source message. */ + size_t msgLen; /* Length of message. */ + void *dst; /* Destination buffer (endorsement). */ + size_t *dstLen; /* Length of the destination buffer. */ + mcScope_t scope; /* Scope of the endorsement. */ +} tlApiEndorse_t; + +/** Maximum number of parameter . */ +#define MAX_MAR_LIST_LENGTH 8 /**< Maximum list of possible marshaling parameters. */ + +/** Marshaled union. */ +typedef struct { + uint32_t functionId; /**< Function identifier. */ + union { + tlApiCrAbort_t crAbort; + tlApiCrGenerateKeyPair_t crGenerateKeyPair; + tlApiCipherInit_t cipherInit; + tlApiCipherUpdate_t cipherUpdate; + tlApiCipherDoFinal_t cipherDoFinal; + tlApiSignatureInit_t signatureInit; + tlApiSignatureUpdate_t signatureUpdate; + tlApiSignatureSign_t signatureSign; + tlApiSignatureVerify_t signatureVerify; + tlApiMessageDigestInit_t messageDigestInit; + tlApiMessageDigestUpdate_t messageDigestUpdate; + tlApiMessageDigestDoFinal_t messageDigestDoFinal; + tlApiRandomGenerateData_t randomGenerateData; + tlApiGrabKeypad_t grabKeypad; + tlApiGetKeypadEvent_t getKeypadEvent; + tlApiReleaseKeypadGrab_t releaseKeypadGrab; + tlApiWrapObject_t wrapObject; + tlApiUnwrapObject_t unwrapObject; + tlApiGetSuid_t getSuid; + tlApiGetMcVersion_t getVersion; + tlApiGetTimeStamp_t getTimeStamp; + tlApiDeriveKey_t deriveKey; + tlApiOverwriteKey_t overwriteKey; + tlApiMacInit_t macInit; + tlApiEndorse_t endorse; + tlApiCipherUpdateIV_t cipherUpdateIV; + tlApiResult_t retVal; + STH_TA_message_t taMessage; + uint32_t parameter[MAX_MAR_LIST_LENGTH]; /* untyped parameter list (expands union to 8 entries) */ + } payload; +} marshalingParamCR_t, *marshalingParamCR_ptr; + +#endif // __TLAPICRYPTOMARSHAL_H__ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/McLib/TlApiStorageMarshal.h b/mobicore/common/MobiCore/inc/McLib/TlApiStorageMarshal.h new file mode 100644 index 0000000..b1848eb --- /dev/null +++ b/mobicore/common/MobiCore/inc/McLib/TlApiStorageMarshal.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + + +#ifndef __TEE_STORAGE_H__ +#define __TEE_STORAGE_H__ +#include +#include + +#include "tee_internal_api.h" +#include "TlApi/TlApi.h" + +#include "TlApiCryptoMarshal.h" +#include "TlApiImpl.h" + +#define MC_FLAG_FILE_MAY_EXIST ( 1 << 0 ) +#define MC_DRV_ID_STORAGE 0x0200 + +#define TLAPI_FNC_CR_SIGN_INIT_ID 19 +#define TLAPI_FNC_CR_SIGN_UPDATE_ID 20 +#define TLAPI_FNC_CR_SIGN_SIGN_ID 21 +#define TLAPI_FNC_CR_SIGN_VERIFY_ID 22 + + +/* ** should be put in TlApiMarshal.h ** */ +typedef struct +{ + uint32_t dataLen; + uint32_t position; + unsigned char objectID[TEE_OBJECT_ID_MAX_LEN]; + unsigned char data[0]; +}_TEE_PersistentData; + + +typedef struct +{ + uint32_t flags; + uint8_t version; + uint8_t objectIDLen; + uint16_t cryptoLen; + _TEE_PersistentData *persistent; + unsigned char crypto[0]; +}TEE_FileObject; + +typedef struct +{ + uint32_t flags; + uint8_t version; + uint8_t objectIDLen; + uint16_t cryptoLen; + _TEE_PersistentData *persistent; +}__TEE_ObjectHandle; + +typedef struct +{ + char header[5]; + unsigned char version; + uint16_t cryptoLen; + uint32_t dataLen; +}STH_plaintext; + +typedef struct { + uint8_t objectIDLen; + unsigned char reserved1[7]; + unsigned char objectID[TEE_OBJECT_ID_MAX_LEN]; + unsigned char data[]; +}STH_ciphertext; + +typedef struct { + char header[6]; + unsigned char version; + unsigned char objectIDLen; + TEE_UUID uuid; + unsigned char objectID[TEE_OBJECT_ID_MAX_LEN]; +} STH_file_name; + +#define PLAIN_TEXT_HEADER ("fname") + + +#endif // __TEE_STORAGE_H__ diff --git a/mobicore/common/MobiCore/inc/McLib/TlApiTuiMarshal.h b/mobicore/common/MobiCore/inc/McLib/TlApiTuiMarshal.h new file mode 100644 index 0000000..28c7808 --- /dev/null +++ b/mobicore/common/MobiCore/inc/McLib/TlApiTuiMarshal.h @@ -0,0 +1,64 @@ +/** @addtogroup DRIVER_TUI + * @{ + * @file drApiMarshal.h + * Marshaling types and declarations for TUI driver and trustlet. + * + * Functions for the marshaling of function ID and parameters. + * + * + */ +#ifndef __TLAPIMARSHAL_TUI_H__ +#define __TLAPIMARSHAL_TUI_H__ + +#include "TlApi/TlApiError.h" +#include "TlApi/TlApiTui.h" + +/** Invalid session id. Returned in case of an error. */ +#define DR_SID_INVALID 0xffffffff + +/** Each function must have its own ID. + * Extend this list if you add a new function. + */ +typedef enum { + FID_DR_NONE = 0, + FID_DR_OPEN_SESSION, + FID_DR_CLOSE_SESSION, + FID_DR_RESERVED0, + FID_DR_SET_IMAGE, + FID_DR_GET_SCREEN_INFO, + FID_DR_GET_TOUCH_EVENT, + FID_DR_RESERVED1, +} tuiFuncID_t; + +/** Marshaled function parameters. + * structs and union of marshaling parameters via TlApi. + * + * @note The structs can NEVER be packed ! + * @note The structs can NOT used via sizeof(..) ! + */ +typedef struct { + union{ + uint32_t *version; + uint32_t *securityLevel; + tlApiTuiImage_ptr image; + tlApiTuiScreenInfo_ptr screenInfo; + tlApiTuiTouchEvent_ptr touchEvent; + }content; + tlApiTuiCoordinates_t coordinates; + +} tuiMarshalingData_t, *tuiMarshalingData_ptr; + +/** Union of marshaling parameters. */ +/* If adding any function, add the marshaling structure here */ +typedef struct { + uint32_t functionId; /**< Function identifier. */ + union { + tuiMarshalingData_t params; + tlApiResult_t retVal; /** Return value */ + } payload; + +} tuiMarshalingParam_t, *tuiMarshalingParam_ptr; + +#endif // __TLAPIMARSHAL_TUI_H__ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/McLib/mcLibWB.h b/mobicore/common/MobiCore/inc/McLib/mcLibWB.h new file mode 100644 index 0000000..91b8cdf --- /dev/null +++ b/mobicore/common/MobiCore/inc/McLib/mcLibWB.h @@ -0,0 +1,16 @@ +/** @addtogroup MC_RTM_START + * @{ + * @file + * + * + */ + +/** Index of flags to be checked after mcWaitNotification */ +#define MCLIB_WB_INDEX_NOTIFICATION_FLAGS (0) +#define MCLIB_WB_NOTIFICATION_FLAG_CA_DEAD (1) + +/** Index of entry in which the base address of heap is stored. */ +#define MCLIB_WB_INDEX_HEAP_BASE_ADDRESS (1) + +/** Index of flags to be checked after mcWaitNotification */ +#define MCLIB_WB_INDEX_CONTEXT (2) diff --git a/mobicore/common/MobiCore/inc/McLib/mclib_size.h b/mobicore/common/MobiCore/inc/McLib/mclib_size.h new file mode 100644 index 0000000..a9fbb48 --- /dev/null +++ b/mobicore/common/MobiCore/inc/McLib/mclib_size.h @@ -0,0 +1,18 @@ +/* + * mclib_size.h + * + * Created on: Oct 22, 2013 + * Author: lukhan01 + */ + +#ifndef MCLIB_SIZE_H_ +#define MCLIB_SIZE_H_ + +// Note: this file is read by .c and .sct file, no magic allowed. +// Please modify these values manually. +#define MCLIB_PAGES 5 +#define MCLIB_SIZE 0x00005000 +#define MCLIB_BASE 0x000FA000 + + +#endif /* MCLIB_SIZE_H_ */ diff --git a/mobicore/common/MobiCore/inc/McLib/tplay_marshal.h b/mobicore/common/MobiCore/inc/McLib/tplay_marshal.h new file mode 100644 index 0000000..955aa89 --- /dev/null +++ b/mobicore/common/MobiCore/inc/McLib/tplay_marshal.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __TPLAY_MARSHAL_H__ +#define __TPLAY_MARSHAL_H__ __FILE__ + +#include "DrApi/DrApiCommon.h" +#include "TlApi/TlApiError.h" +#include "TlApi/TPlay.h" + +/** + * Driver ID + */ +#define TPLAY_DR_ID TB_DRV_ID_TPLAY + +/** + * Function id definitions + */ +#define FID_DR_OPEN_SESSION 1 +#define FID_DR_CLOSE_SESSION 2 +#define FID_DR_PROCESS_DRM_CONTENT 3 +#define FID_DR_CHECK_LINK 4 +#define FID_DR_UNKNOWN_CMD 100 /* For test purposes */ + +/** + * Secure cipher request data structure. + * This structure helps define a buffer that contains mixed encrypted and clear data. + */ +typedef struct { + uint8_t sHandle; + tlApiDrmDecryptContext_t decryptCtx; + uint8_t *input; + tlApiDrmInputSegmentDescriptor_t inputDesc; + uint32_t processMode; + uint8_t *rfu; +} tlDrmApiDrmContent_t, *tlDrmApiDrmContent_ptr; + +/** + * Link status data structure. + */ +typedef struct { + uint8_t sHandle; + tlApiDrmLink_t link; +} tlDrmApiLink_t, *tlDrmApiLink_ptr; + +/** + * Union of marshaling parameters. */ +/* If adding any function, add the marshaling structure here + */ +typedef struct { + uint32_t functionId; /* Function identifier. */ + union { + uint8_t *returned_sHandle; + uint8_t sHandle_to_close; + tlDrmApiDrmContent_t drmContent; + tlDrmApiLink_t link; + int32_t retVal; /* Return value */ + } payload; +} tplayMarshalingParam_t, *tplayMarshalingParam_ptr; + + +#endif // __TPLAY_MARSHAL_H__ + + diff --git a/mobicore/common/MobiCore/inc/Mci/mci.h b/mobicore/common/MobiCore/inc/Mci/mci.h new file mode 100644 index 0000000..b9011e5 --- /dev/null +++ b/mobicore/common/MobiCore/inc/Mci/mci.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * 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. + * + * + *

Introduction

+ * The MobiCore Control Interface (MCI) is the interface for integrating G&D MobiCore technology into the + * rich operating system running in the non-secure part of an ARM TrustZone enabled platform. + * + *

Interface overview

+ * The Structure of the MobiCore control interface is depicted in the figure below: + * @image html DoxyOverviewMci500x.png "MobiCore control interface" + * @image latex DoxyOverviewMci500x.png "MobiCore control interface" width=12cm + * + * The MCI is composed of the following interfaces: + *
    + * + *
  • MobiCore control protocol (MCP) interface.

  • + * The MCP interface is responsible for the main communicating with the MobiCore. This involves sending commands for starting + * and stopping of Trustlets as well as checking their corresponding answers. MCP information is exchanged in a + * world shared memory buffer which needs to be initially established between NWd and SWd using the FastCall interface.
    + * + *
  • Notification queue interface.

  • + * Notifications inform the MobiCore runtime environment that information is pending in a WSM buffer. + * The Trustlet Connector (TLC) and the corresponding Trustlet also utilize this buffer to + * notify each other about new data within the Trustlet Connector Interface (TCI). Therefore the TLC writes + * a notification including the session ID to the buffer. The driver informs the MobiCore + * about the availability of a notification with the use of a SIQ. On the secure side the Runtime Management + * notifies the Trustlet, according to the given session ID, about the availability of new data. + * The same mechanism is used vice versa for writing data back to the None-secure world. + * + *
  • FastCall interface.

  • + * The FastCall interface of the MobiCore system is used to transfer control from the Non-secure World (NWd) to the + * Secure World (SWd) and back. There are three mechanisms the NWd shall use to interact with the MobiCore Monitor: + * FastCall, N-SIQ and NQ-IRQ (Notification IRQ). FastCall and N-SIQ operations are used to hand over control + * to the MobiCore. Both functions make use of the SMC [ARM11] operation. + * + *
+ * + * You can find more information about the interfaces in the respective modules description. + * + *

Version history

+ * + * + * + * + * + * + * + * + * + *
DateVersionChanges
2009-06-250.1Initial Release
2009-07-010.2Major rewrite
2009-08-060.3Added documentation for FastCall helper functions
2009-09-100.4Update of constant naming. Modification of doxygen config.
2010-03-090.5Added fastCallPower() helper function for MC_FC_POWER.
2010-05-100.6Restructuring of load format header.
2011-07-190.7update to reflect current code changes.
+ * + * + * @file + * @defgroup FCI FastCall Interface + * + * @defgroup NQ Notification Queue + * + * @defgroup MCP MobiCore Control Protocol + * + */ +#ifndef MCI_H_ +#define MCI_H_ + +#include "version.h" +#include "mcifc.h" +#include "mcinq.h" +#include "mcimcp.h" + +#endif /** MCI_H_ */ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/Mci/mcifc.h b/mobicore/common/MobiCore/inc/Mci/mcifc.h new file mode 100644 index 0000000..12c34d6 --- /dev/null +++ b/mobicore/common/MobiCore/inc/Mci/mcifc.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * 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. + * + * + * @addtogroup FCI + * @{ + * @file + * FastCall declarations. + * + * Holds the functions for SIQ, YIELD and FastCall for switching to the secure world. + * + + */ +#ifndef MCIFC_H_ +#define MCIFC_H_ + +/** @name MobiCore FastCall Defines + * Defines for the two different FastCall's. + */ +/** @{ */ + +// --- global ---- +#define MC_FC_INVALID ((uint32_t) 0 ) /**< Invalid FastCall ID */ +#define MC_FC_INIT ((uint32_t)(-1)) /**< Initializing FastCall. */ +#define MC_FC_INFO ((uint32_t)(-2)) /**< Info FastCall. */ + +// following defines are currently frozen, so they will candidate for later big-change +// --- sleep modes --- +#define MC_FC_SLEEP ((uint32_t)(-3)) /**< enter power-sleep */ +#define MC_FC_AFTR ((uint32_t)(-5)) /**< enter AFTR-sleep (called from core-0) */ +// --- wake-up access --- +#define MC_FC_CORE_X_WAKEUP ((uint32_t)(-4)) /**< wakeup/boot core-x (optional core-number in r1, not "0" ) */ +#define MC_FC_C15_RESUME ((uint32_t)(-11)) /**< Write power control & diag registers */ +#define MC_FC_CMD_SAVE ((uint32_t)(-6)) /**< Save core context to CP15 table(r1 is core number) */ +#define MC_FC_CMD_SHUTDOWN ((uint32_t)(-7)) /**< Shutdown core(r1 is core number, cache flush is expected) */ +// --- L2 cache access --- +#define MC_FC_L2X0_CTRL ((uint32_t)(-21)) /**< Write to L2X0 control register */ +#define MC_FC_L2X0_SETUP1 ((uint32_t)(-22)) /**< Setup L2X0 register - part 1 */ +#define MC_FC_L2X0_SETUP2 ((uint32_t)(-23)) /**< Setup L2X0 register - part 2 */ +#define MC_FC_L2X0_INVALL ((uint32_t)(-24)) /**< Invalidate all L2 cache */ +#define MC_FC_L2X0_DEBUG ((uint32_t)(-25)) /**< Write L2X0 debug register */ +#define MC_FC_SW_RESET ((uint32_t)(-26)) /**< SW Reset if DDR has leftover content */ +// --- MEM traces --- +#define MC_FC_MEM_TRACE ((uint32_t)(-31)) /**< Enable SWd tracing via memory */ +// --- system settings --- + +#define MC_FC_STAT_COUNTER ((uint32_t)(-41)) /**< Require status counter */ +#define MC_FC_CP15_REG ((uint32_t)(-101)) /**< general CP15/cache register update */ +// --- store value in sDDRRAM --- +#define MC_FC_STORE_BINFO ((uint32_t)(-201)) /**< write a 32bit value in secure DDRRAM in incremented art (max 2kB) */ +#define MC_FC_LOAD_BINFO ((uint32_t)(-202)) /**< load a 32bit value from secure DDRRAM using an offset */ + +// Broadcom Specific Fastcalls +#define MC_FC_BCM_VC_CORE_START ((uint32_t)(-301)) /**< Set the VC Core start address*/ +#define MC_FC_MAX_ID ((uint32_t)(0xFFFF0000)) /**< Maximum allowed FastCall ID */ + +#define MC_FC_SWAP_CPU ((uint32_t)(0x84000005)) /**< Change new active Core */ +// r1 is requested status (0,1,2), on return r2 holds this status value + +/** @} */ + +/** @name MobiCore SMC Defines + * Defines the different secure monitor calls (SMC) for world switching. + * @{ */ +#define MC_SMC_N_YIELD 0x3 /**< Yield to switch from NWd to SWd. */ +#define MC_SMC_N_SIQ 0x4 /**< SIQ to switch from NWd to SWd. */ +/** @} */ + +/** @name MobiCore status + * MobiCore status information. + * @{ */ +#define MC_STATUS_NOT_INITIALIZED 0 /**< MobiCore is not yet initialized. FastCall FcInit() has to be used function to set up MobiCore.*/ +#define MC_STATUS_BAD_INIT 1 /**< Bad parameters have been passed in FcInit(). */ +#define MC_STATUS_INITIALIZED 2 /**< MobiCore did initialize properly. */ +#define MC_STATUS_HALT 3 /**< MobiCore kernel halted due to an unrecoverable exception. Further information is available extended info */ +/** @} */ + +/** @name Extended Info Identifiers + * Extended info parameters for MC_FC_INFO to obtain further information depending on MobiCore state. + * @{ */ +#define MC_EXT_INFO_ID_MCI_VERSION 0 /**< Version of the MobiCore Control Interface (MCI) */ +#define MC_EXT_INFO_ID_FLAGS 1 /**< MobiCore control flags */ +#define MC_EXT_INFO_ID_HALT_CODE 2 /**< MobiCore halt condition code */ +#define MC_EXT_INFO_ID_HALT_IP 3 /**< MobiCore halt condition instruction pointer */ +#define MC_EXT_INFO_ID_FAULT_CNT 4 /**< MobiCore fault counter */ +#define MC_EXT_INFO_ID_FAULT_CAUSE 5 /**< MobiCore last fault cause */ +#define MC_EXT_INFO_ID_FAULT_META 6 /**< MobiCore last fault meta */ +#define MC_EXT_INFO_ID_FAULT_THREAD 7 /**< MobiCore last fault threadid */ +#define MC_EXT_INFO_ID_FAULT_IP 8 /**< MobiCore last fault instruction pointer */ +#define MC_EXT_INFO_ID_FAULT_SP 9 /**< MobiCore last fault stack pointer */ +#define MC_EXT_INFO_ID_FAULT_ARCH_DFSR 10 /**< MobiCore last fault ARM arch information */ +#define MC_EXT_INFO_ID_FAULT_ARCH_ADFSR 11 /**< MobiCore last fault ARM arch information */ +#define MC_EXT_INFO_ID_FAULT_ARCH_DFAR 12 /**< MobiCore last fault ARM arch information */ +#define MC_EXT_INFO_ID_FAULT_ARCH_IFSR 13 /**< MobiCore last fault ARM arch information */ +#define MC_EXT_INFO_ID_FAULT_ARCH_AIFSR 14 /**< MobiCore last fault ARM arch information */ +#define MC_EXT_INFO_ID_FAULT_ARCH_IFAR 15 /**< MobiCore last fault ARM arch information */ +#define MC_EXT_INFO_ID_MC_CONFIGURED 16 /**< MobiCore configured by Daemon via fc_init flag */ +#define MC_EXT_INFO_ID_MC_SCHED_STATUS 17 /**< MobiCore scheduling status: idle/non-idle */ +#define MC_EXT_INFO_ID_MC_STATUS 18 /**< MobiCore runtime status: initialized, halted */ +#define MC_EXT_INFO_ID_MC_EXC_PARTNER 19 /**< MobiCore exception handler last partner */ +#define MC_EXT_INFO_ID_MC_EXC_IPCPEER 20 /**< MobiCore exception handler last peer */ +#define MC_EXT_INFO_ID_MC_EXC_IPCMSG 21 /**< MobiCore exception handler last IPC message */ +#define MC_EXT_INFO_ID_MC_EXC_IPCDATA 22 /**< MobiCore exception handler last IPC data */ + +/** @} */ + +/** @name FastCall return values + * Return values of the MobiCore FastCalls. + * @{ */ +#define MC_FC_RET_OK 0 /**< No error. Everything worked fine. */ +#define MC_FC_RET_ERR_INVALID 1 /**< FastCall was not successful. */ +#define MC_FC_RET_ERR_ALREADY_INITIALIZED 5 /**< MobiCore has already been initialized. */ +/** @} */ + +#endif /** MCIFC_H_ */ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/Mci/mcifcfunc.h b/mobicore/common/MobiCore/inc/Mci/mcifcfunc.h new file mode 100644 index 0000000..895507e --- /dev/null +++ b/mobicore/common/MobiCore/inc/Mci/mcifcfunc.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * 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. + * + * + * @addtogroup FCI + * @{ + * @file + * Declaration of FastCall helper functions. + * + * @attention Helper functions are mostly RealView (ARM CC) specific. + * + * Holds the functions for SIQ, YIELD and FastCall for switching to the secure world. + * + * + */ + +#ifndef MCIFCFUNC_H_ +#define MCIFCFUNC_H_ + +#include "mcifc.h" +/** + * Execute a secure monitor call (SMC). + * + * @param mode SMC mode affects the way SMC is handled + * + * @attention This function shall not be used directly. Use N_Siq() or Yield() instead. + */ +__smc(0) void smc(int32_t mode); + +/** + * N-SIQ switch from NWd to SWd. + * Execution will continue in the SWd. The notification queue will be drained by the MC4 and MC4 system schedules its services. + */ +inline void N_Siq(void) { smc(MC_SMC_N_SIQ); } + +/** + * Yield switch from NWd to SWd. + * Execution will continue in the SWd without scheduling MC4 services. + */ +inline void Yield(void) { smc(MC_SMC_N_YIELD); } + +/** Wrapper structure for parameter passing in registers. + * This structure is used as a "wrapper" return value for functions that + * return data in the registers r0 to r3. With the RealView compiler such + * function are declare as: _value_in_regs reg_r0_r1_r2_r3_t foo() + + */ +typedef struct { + uint32_t r0; + uint32_t r1; + uint32_t r2; + uint32_t r3; +} reg_r0_r1_r2_r3_t; + +/** Parameterized SMC for FastCalls. + * @attention This function shall not be used directly. + */ +__smc(0) __value_in_regs reg_r0_r1_r2_r3_t smcFc( + uint32_t r0, + uint32_t r1, + uint32_t r2, + uint32_t r3 +); + +/** FastCall helper function. + * @attention This function shall not be used directly. + */ +inline static __value_in_regs reg_r0_r1_r2_r3_t fastCall( + uint32_t r0, + uint32_t r1, + uint32_t r2, + uint32_t r3 +) { + return smcFc(r0,r1,r2,r3); +} + +/** + * Initialize the MobiCore. + * The FcMc4init FastCall shall be used to set up the MCI. The function passes the message buffers used in the MCI to the MC4 system. + * As long as the buffers are not set up the MC4 message passing mechanisms (notifications, MCP commands) are not available. + * NQ buffer and MCP buffer as well as length calculations are described in the "MobiCore4 Driver Interface Specification". + *
The fastCallInit() will not check the parameters for validity. Instead the MC4 will perform a check on first usage of the parameters. + * + * @image html DoxyMciBuffer.png "MCI buffer" + * @image latex DoxyMciBuffer.png "MCI buffer" width=12cm + * + * @param base Physical start address of the MCI buffer. Must be 4kB aligned. + * @param nqOffset Offset in bytes to the beginning of the NQ buffer. + * @param nqLength Length of the NQ buffer in bytes. + * @param mcpOffset Offset in bytes to the beginning of the MCP buffer. + * @param mcpLength Length of the MCP buffer in bytes + * + */ +inline static uint32_t fastCallInit( + uint8_t *base, + uint32_t nqOffset, + uint32_t nqLength, + uint32_t mcpOffset, + uint32_t mcpLength +) { + + reg_r0_r1_r2_r3_t ret; + + ret = fastCall( + MC_FC_INIT, + (uint32_t)base, + ((nqOffset << 16) | (nqLength & 0xFFFF)), + ((mcpOffset << 16) | (mcpLength & 0xFFFF)) ); + + + return ret.r1; +} + + +/** Get status information about MobiCore. + * The FcMcGetInfo FastCall provides information about the current state of the MobiCore. + * In certain states extended information is provided. + * + * @param extInfoId Extended info word to be obtained. + * @param mc4state Current state of the MobiCore. + * @param extInfo Extended information depending on state. + */ +inline static uint32_t fastCallGetInfo( + uint32_t extInfoId, + uint32_t *mc4state, + uint32_t *extInfo +) { + reg_r0_r1_r2_r3_t ret; + + ret = fastCall(MC_FC_INFO,extInfoId,0,0); + + if (MC_FC_RET_OK == ret.r1) + { + *mc4state = ret.r2; + *extInfo = ret.r3; + } + + return ret.r1; +} + +/** + * Power management. + * The power management FastCall is platform specific. + * + * @param param0 platform specific parameter. + * @param param1 platform specific parameter. + * @param param2 platform specific parameter. + */ +inline static uint32_t fastCallPower( + uint32_t param0, + uint32_t param1, + uint32_t param2 +) { + + reg_r0_r1_r2_r3_t ret; + + ret = fastCall( + MC_FC_POWER, + param0, + param1, + param2 ); + + return ret.r1; +} + +#endif /* MCIFCFUNC_H_ */ +/** + * @}*/ diff --git a/mobicore/ClientLib/include/Mci/mcimcp.h b/mobicore/common/MobiCore/inc/Mci/mcimcp.h similarity index 72% rename from mobicore/ClientLib/include/Mci/mcimcp.h rename to mobicore/common/MobiCore/inc/Mci/mcimcp.h index 34f0deb..1dc30e2 100644 --- a/mobicore/ClientLib/include/Mci/mcimcp.h +++ b/mobicore/common/MobiCore/inc/Mci/mcimcp.h @@ -1,32 +1,43 @@ /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved * * 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. - * + * 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. * - * 3. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. + * @addtogroup MCP + * @{ + * The MCP defines commands and responses which are used to control the MobiCore system. + * MCP information is exchanged in a world share memory buffer which has been established prior between NWd + * and SWd using the FastCall interface. The buffer needs to be provided by the MobiCore driver and is utilized + * to send MCP commands to the MobiCore as well as receiving responses from the MobiCore. + * The command of the normal world will be overwritten with the response from the secure side. + * + * @file + * MCP command interface definitions. + * */ #ifndef MCP_H_ @@ -36,11 +47,7 @@ #include "mcUuid.h" #include "mcLoadFormat.h" #include "mcVersionInfo.h" -#include "stdbool.h" - -#define FLAG_RESPONSE (1U << 31) /**< Flag to indicate that this is the response to a MCP command. */ -#define MCP_MAP_MAX_BUF 4 /** Maximum number of buffers that can be mapped at once */ /** MobiCore Return Code Defines. * List of the possible MobiCore return codes. @@ -75,9 +82,6 @@ typedef enum { MC_MCP_RET_ERR_SP_TL_HASH_CHECK_FAILED = 26, /**< Hash check of service provider trustlet failed. */ MC_MCP_RET_ERR_LAUNCH_TASK_FAILED = 27, /**< Activation/starting of task failed. */ MC_MCP_RET_ERR_CLOSE_TASK_FAILED = 28, /**< Closing of task not yet possible, try again later. */ - MC_MCP_RET_ERR_SERVICE_BLOCKED = 29, /**< Service is blocked and a session cannot be opened to it. */ - MC_MCP_RET_ERR_SERVICE_LOCKED = 30, /**< Service is locked and a session cannot be opened to it. */ - MC_MCP_RET_ERR_SERVICE_KILLED = 31, /**< Service was forcefully killed (due to an administrative command). */ // used for command verification MC_MCP_RET_ERR_UNKNOWN_COMMAND = 50, /**< The command is unknown. */ @@ -101,11 +105,12 @@ typedef enum { MC_MCP_CMD_CLOSE_MCP = 0x0000000A, /**< Close MCP and unmap MCI. */ MC_MCP_CMD_LOAD_TOKEN = 0x0000000B, /**< Load token for device attestation */ MC_MCP_CMD_CHECK_LOAD_TA = 0x0000000C, /**< Check that TA can be loaded */ - MC_MCP_CMD_MULTIMAP = 0x0000000D, - MC_MCP_CMD_MULTIUNMAP = 0x0000000E, } mcpCmdId_t; +#define FLAG_RESPONSE (1U << 31) /**< Flag to indicate that this is the response to a MCP command. */ + + /** Types of WSM known to the MobiCore. */ typedef uint32_t wsmType_t; @@ -114,23 +119,9 @@ typedef uint32_t wsmType_t; #define WSM_INVALID 0 /**< Invalid memory type */ #define WSM_CONTIGUOUS 1 /**< Reference to WSM points to a contiguous region of pages. */ #define WSM_L2 2 /**< Reference to WSM points to an L2 table describing the memory region to share */ -#define WSM_L1 3 /**< Reference to WSM points to an L1 table describing the memory region to share */ #define WSM_WSM_UNCACHED 0x100 /**< Bitflag indicating that WSM should be uncached */ #define WSM_L2_UNCACHED 0x100 /**< Bitflag indicating that L2 table should be uncached */ -/** Magic number used to identify if Open Command supports GP client authentication. */ -#define MC_GP_CLIENT_AUTH_MAGIC 0x47504131 /* "GPA1" */ - -/** Initialisation values flags. */ -#define MC_IV_FLAG_IRQ (1 << 0) /* Set if IRQ is present */ -#define MC_IV_FLAG_TIME (1 << 1) /* Set if GP TIME API is supported */ - -typedef struct { - uint32_t flags; /**< Flags to know what data to expect. */ - uint32_t irq; /**< IRQ number to use. */ - uint32_t timeOffset;/**< Offset from MCI base address of mcTime struct. */ - uint32_t timeLen;/**< Length of mcTime struct. */ -} initValues_t; /** Command header. * It just contains the command ID. Only values specified in mcpCmdId_t are allowed as command IDs. @@ -233,18 +224,10 @@ typedef struct { * On success, MobiCore returns the session ID which can be used for further communication. * @{ */ -/** GP client authentication data */ -typedef struct { - uint32_t mclfMagic; /**< ASCII "GPA1" if GP client authentication is supported, - "MCLF" otherwise. */ - mcIdentity_t mcIdentity; /**< GP identity information: login method and data */ -} cmdOpenData_t; - /** Open Command */ typedef struct { commandHeader_t cmdHeader; /**< Command header. */ - mcUuid_t uuid; /**< Byte array containing the service UUID. */ - uint8_t pad1[4]; /**< Padding to be 64-bit aligned */ + mcUuid_t uuid; /**< Byte array containing the service UUID. */ uint64_t adrTciBuffer; /**< Physical address of the TCI */ uint64_t adrLoadData; /**< Physical address of the data to load. */ uint32_t ofsTciBuffer; /**< Offset to the data. */ @@ -253,11 +236,7 @@ typedef struct { wsmType_t wsmTypeLoadData; /**< Type of the memory containing the data to load. */ uint32_t ofsLoadData; /**< Offset to the data. */ uint32_t lenLoadData; /**< Length of the data to load. */ - union { - cmdOpenData_t cmdOpenData; /**< Magic number and login info for GP client authentication. */ - mclfHeader_t tlHeader; /**< Service header */ - }; - uint32_t is_gpta; /**< true if looking for an SD/GP-TA */ + mclfHeader_t tlHeader; /**< Service header. */ } mcpCmdOpen_t, *mcpCmdOpen_ptr; /** Open Command Response */ @@ -270,7 +249,6 @@ typedef struct { typedef struct { commandHeader_t cmdHeader; /**< Command header. */ mcUuid_t uuid; /**< Byte array containing the service UUID. */ - uint8_t pad1[4]; /**< Padding to be 64-bit aligned */ uint64_t adrLoadData; /**< Physical address of the data to load. */ wsmType_t wsmTypeLoadData; /**< Type of the memory containing the data to load. */ uint32_t ofsLoadData; /**< Offset to the data. */ @@ -316,6 +294,8 @@ typedef struct { * Map a portion of memory to a session. * The MAP command provides a block of memory to the context of a service. * The memory then becomes world-shared memory (WSM). + * The WSM can either be normal anonymous memory from malloc() or be a + * block of page aligned, contiguous memory. * The only allowed memory type here is WSM_L2. * @{ */ @@ -327,7 +307,6 @@ typedef struct { uint32_t ofsBuffer; /**< Offset to the payload. */ uint64_t adrBuffer; /**< Physical address of the memory */ uint32_t lenBuffer; /**< Length of the buffer. */ - uint8_t pad1[4]; /**< Padding to be 64-bit aligned */ } mcpCmdMap_t, *mcpCmdMap_ptr; #define MCP_MAP_MAX 0x100000 /**< Maximum allowed length for MCP map. */ @@ -366,73 +345,6 @@ typedef struct { /** @} */// End MCPUNMAP -/** @defgroup MCPMULTIMAP MULTIMAP - * Map up to MCP_MAP_MAX_BUF portions of memory to a session. - * The MULTIMAP command provides MCP_MAP_MAX_BUF blocks of memory to the context of a service. - * The memory then becomes world-shared memory (WSM). - * The only allowed memory type here is WSM_L2. - * @{ */ - -/** NWd physical buffer description - * - * Note: Information is coming from NWd kernel. So it should not be trusted more than NWd kernel is trusted. - */ -typedef struct { - uint64_t adrBuffer; /**< Physical address, for buffer or for L2 table (1K) */ - uint32_t ofsBuffer; /**< Offset of buffer */ - uint32_t lenBuffer; /**< Length of buffer */ - wsmType_t wsmType; /**< Type of address */ - uint8_t pad1[4]; /**< Padding to be 64-bit aligned */ -} mcpBufferMap_t; - -/** Multimap Command */ -typedef struct { - commandHeader_t cmdHeader; /**< Command header. */ - uint32_t sessionId; /** Session ID */ - mcpBufferMap_t buffers[MCP_MAP_MAX_BUF]; -} mcpCmdMultimap_t, *mcpCmdMultimap_ptr; - -/** Multimap Command Response */ -typedef struct { - responseHeader_t rspHeader; /**< Response header. */ - uint64_t secureVirtAdr[MCP_MAP_MAX_BUF]; /**< Virtual address in the context of the service the WSM is mapped to, already includes a possible offset! */ -} mcpRspMultimap_t, *mcpRspMultimap_ptr; - -/** @} *///End MCPMULTIMAP - -/** @defgroup MCPMULTIUNMAP MULTIUNMAP - * Unmap up to MCP_MAP_MAX_BUF portions of world-shared memory from a session. - * The MULTIUNMAP command is used to unmap MCP_MAP_MAX_BUF previously mapped blocks of - * world shared memory from the context of a session. - * - * Attention: The memory blocks will be immediately unmapped from the specified session. - * If the service is still accessing the memory, the service will trigger a segmentation fault. - * @{ */ - -/** NWd mapped buffer description - * - * Note: Information is coming from NWd kernel. So it should not be trusted more than NWd kernel is trusted. - */ -typedef struct { - uint64_t secureVirtAdr; /**< Physical address, for buffer or for L2 table (1K) */ - uint32_t lenBuffer; /**< Length of buffer - unused */ - uint8_t pad1[4]; /**< Padding to be 64-bit aligned */ -} mcpBufferUnmap_t; - -/** Multiunmap Command */ -typedef struct { - commandHeader_t cmdHeader; /**< Command header. */ - uint32_t sessionId; /** Session ID */ - mcpBufferUnmap_t buffers[MCP_MAP_MAX_BUF]; /* For len and sva */ -} mcpCmdMultiunmap_t, *mcpCmdMultiunmap_ptr; - -/** Multiunmap Command Response */ -typedef struct { - responseHeader_t rspHeader; /**< Response header. */ -} mcpRspMultiunmap_t, *mcpRspMultiunmap_ptr; - -/** @} */// End MCPMULTIUNMAP - /** @} */// End SESSCMD /** @defgroup MCPLOADTOKEN @@ -460,7 +372,6 @@ typedef struct { /** Structure of the MCP buffer. */ typedef union { - initValues_t initValues; /**< initialization values. */ commandHeader_t cmdHeader; /**< Command header. */ responseHeader_t rspHeader; /**< Response header. */ mcpCmdOpen_t cmdOpen; /**< Load and open service. */ @@ -481,10 +392,7 @@ typedef union { mcpRspLoadToken_t rspLoadToken; mcpCmdCheckLoad_t cmdCheckLoad; /**< TA load check command. */ mcpRspCheckLoad_t rspCheckLoad; /**< Response to TA load check. */ - mcpCmdMultimap_t cmdMultimap; /**< Map a list of WSM to service context. */ - mcpRspMultimap_t rspMultimap; /**< Response to MULTIMAP command. */ - mcpCmdMultiunmap_t cmdMultiunmap; /**< Map a list of WSM to service context. */ - mcpRspMultiunmap_t rspMultiunmap; /**< Response to MULTIMAP command. */ + } mcpMessage_t, *mcpMessage_ptr; @@ -505,7 +413,7 @@ typedef struct { typedef struct { uint32_t schedule; /**< Scheduling hint: if <> MC_FLAG_SCHEDULE_IDLE, MobiCore should be scheduled by the NWd */ mcSleepMod_t sleepMode; /**< */ - uint32_t timeout; /**< Secure-world timeout: when t-base goes to sleep, its next deadline is written here */ + uint32_t RFU2; /**< Reserved for future use: Must not be interpreted */ uint32_t RFU3; /**< Reserved for future use: Must not be interpreted */ } mcFlags_t, *mcFlags_ptr; diff --git a/mobicore/ClientLib/include/Mci/mcinq.h b/mobicore/common/MobiCore/inc/Mci/mcinq.h similarity index 54% rename from mobicore/ClientLib/include/Mci/mcinq.h rename to mobicore/common/MobiCore/inc/Mci/mcinq.h index 59659d8..4036cab 100644 --- a/mobicore/ClientLib/include/Mci/mcinq.h +++ b/mobicore/common/MobiCore/inc/Mci/mcinq.h @@ -1,32 +1,48 @@ /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved * * 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. - * + * 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. + * + * + * @addtogroup NQ + * @{ + * Notifications inform the MobiCore runtime environment that information is pending in a WSM buffer. + * The Trustlet Connector (TLC) and the corresponding trustlet also utilize this buffer to notify + * each other about new data within the Trustlet Connector Interface (TCI). + * + * The buffer is set up as a queue, which means that more than one notification can be written to the buffer + * before the switch to the other world is performed. Each side therefore facilitates an incoming and an + * outgoing queue for communication with the other side. + * + * Notifications hold the session ID, which is used to reference the communication partner in the other world. + * So if, e.g., the TLC in the normal world wants to notify his trustlet about new data in the TLC buffer * - * 3. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. + * @file + * Notification queue declarations. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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 NQ_H_ @@ -40,11 +56,10 @@ /** @} */ /** \name NQ Length Defines - * Note that there is one queue for NWd->SWd and one queue for SWd->NWd + * Minimum and maximum notification queue length. * @{ */ -#define NQ_SIZE(n) (2*(sizeof(notificationQueueHeader_t) + (n)*sizeof(notification_t))) -#define MIN_NQ_LEN NQ_SIZE(MIN_NQ_ELEM) /**< Minimum size for the notification queue data structure */ -#define MAX_NQ_LEN NQ_SIZE(MAX_NQ_ELEM) /**< Maximum size for the notification queue data structure */ +#define MIN_NQ_LEN (MIN_NQ_ELEM * sizeof(notification_t)) /**< Minimum notification length (in bytes). */ +#define MAX_NQ_LEN (MAX_NQ_ELEM * sizeof(notification_t)) /**< Maximum notification length (in bytes). */ /** @} */ /** \name Session ID Defines @@ -71,8 +86,7 @@ typedef enum { ERR_SESSION_CLOSE = -2, /**< task terminated due to session end, no exit code available */ ERR_INVALID_OPERATION = -3, /**< task terminated due to invalid operation */ ERR_INVALID_SID = -4, /**< session ID is unknown */ - ERR_SID_NOT_ACTIVE = -5, /**< session is not active */ - ERR_SESSION_KILLED = -6, /**< session was force-killed (due to an administrative command). */ + ERR_SID_NOT_ACTIVE = -5 /**< session is not active */ } notificationPayload_t; /** Declaration of the notification queue header. diff --git a/mobicore/common/MobiCore/inc/Mci/version.h b/mobicore/common/MobiCore/inc/Mci/version.h new file mode 100644 index 0000000..0130941 --- /dev/null +++ b/mobicore/common/MobiCore/inc/Mci/version.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * 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 MCI_VERSION_H_ +#define MCI_VERSION_H_ + +#define MCI_VERSION_MAJOR 0 +#define MCI_VERSION_MINOR 6 + +#endif /** MCI_VERSION_H_ */ diff --git a/mobicore/tlcm/TlCm/2.0/cmp.h b/mobicore/common/MobiCore/inc/TlCm/2.0/cmp.h similarity index 97% rename from mobicore/tlcm/TlCm/2.0/cmp.h rename to mobicore/common/MobiCore/inc/TlCm/2.0/cmp.h index 45bcb7a..94fa4e2 100644 --- a/mobicore/tlcm/TlCm/2.0/cmp.h +++ b/mobicore/common/MobiCore/inc/TlCm/2.0/cmp.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP_2_0 * Content Management Protocol 2.0 Definitions. * @@ -41,6 +11,33 @@ * CMP 2.0 global definitions. * Various components need access to (sub-)structures defined and used by CMP * 2.0. These common definitions are made available through this header file. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 CMP_H_ diff --git a/mobicore/tlcm/TlCm/2.0/tlCmApi.h b/mobicore/common/MobiCore/inc/TlCm/2.0/tlCmApi.h similarity index 87% rename from mobicore/tlcm/TlCm/2.0/tlCmApi.h rename to mobicore/common/MobiCore/inc/TlCm/2.0/tlCmApi.h index df4217d..19483b6 100644 --- a/mobicore/tlcm/TlCm/2.0/tlCmApi.h +++ b/mobicore/common/MobiCore/inc/TlCm/2.0/tlCmApi.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP_2_0 * @{ * @file @@ -36,6 +6,33 @@ * The TlCm is responsible for implementing content management protocol (CMP) * 2.0 commands and generating approriate CMP 2.0 responses in the trustlet * control interface (TCI). + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 TL_CM_API_H_ diff --git a/mobicore/tlcm/TlCm/3.0/cmp.h b/mobicore/common/MobiCore/inc/TlCm/3.0/cmp.h similarity index 92% rename from mobicore/tlcm/TlCm/3.0/cmp.h rename to mobicore/common/MobiCore/inc/TlCm/3.0/cmp.h index 6abb747..ef2ba56 100644 --- a/mobicore/tlcm/TlCm/3.0/cmp.h +++ b/mobicore/common/MobiCore/inc/TlCm/3.0/cmp.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP * Content Management Protocol Definitions. * @@ -41,6 +11,33 @@ * CMP TCI global definitions. * Various components need access to (sub-)structures defined and used by CMP; * these common definitions are made available through this header file. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 CMP_H_ @@ -51,11 +48,7 @@ /** Info of the whole mapped memory with NWd. */ typedef struct { /** Address of the mapped memory. */ -#if ( __WORDSIZE == 64 ) - uint32_t addr; /**< The virtual address of the Bulk buffer regarding the address space of the Trusted Application, already includes a possible offset! */ -#else void* addr; -#endif /** Size of the mapped memory. */ uint32_t len; } cmpMapInfo_t; @@ -183,38 +176,6 @@ typedef struct { /** @} */ -/** @defgroup MC_CMP_CMD_GENERATE_BINDING_KEY_TCI \ - MC_CMP_CMD_GENERATE_BINDING_KEY_TCI - * @{ */ - -/** @defgroup MC_CMP_CMD_GENERATE_BINDING_KEY_TCI_CMD Command - * @{ */ - -/** GenBindingKey TCI command. */ -typedef struct { - /** Command header. */ - cmpCommandHeaderTci_t cmdHeader; -} cmpCmdGenBindingKeyTci_t; - -/** @} */ - -/** @defgroup MC_CMP_CMD_GENERATE_BINDING_KEY_TCI_RSP Response - * @{ */ - -/** GenAuthToken TCI response. */ -typedef struct { - /** Response header. */ - cmpResponseHeaderTci_t rspHeaderTci; - /** Offset of the mapped CMP response with NWd. */ - cmpMapOffsetInfo_t cmpRspMapOffsetInfo; - /** Offset of the mapped AuthTokenCont with NWd. */ - cmpMapOffsetInfo_t cmpAuthTokenContMapOffsetInfo; -} cmpRspGenBindingKeyTci_t; - -/** @} */ - -/** @} */ - /** @defgroup MC_CMP_CMD_BEGIN_SOC_AUTHENTICATION_TCI \ MC_CMP_CMD_BEGIN_SOC_AUTHENTICATION_TCI * @{ */ diff --git a/mobicore/tlcm/TlCm/3.0/cmpMap.h b/mobicore/common/MobiCore/inc/TlCm/3.0/cmpMap.h similarity index 97% rename from mobicore/tlcm/TlCm/3.0/cmpMap.h rename to mobicore/common/MobiCore/inc/TlCm/3.0/cmpMap.h index 56d7fff..0727407 100644 --- a/mobicore/tlcm/TlCm/3.0/cmpMap.h +++ b/mobicore/common/MobiCore/inc/TlCm/3.0/cmpMap.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP * Content Management Protocol Definitions. * @@ -41,6 +11,33 @@ * CMP mapped global definitions. * Various components need access to (sub-)structures defined and used by CMP; * these common definitions are made available through this header file. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 CMP_MAP_H_ @@ -72,14 +69,6 @@ typedef union { cmpRspGenAuthToken_t cmpRspGenAuthToken; } cmpMapGenAuthToken_t; -/** Map CMP GenBindingKey message. */ -typedef union { - /** Map CMP command. */ - cmpCmdGenBindingKey_t cmpCmdGenBindingKey; - /** Map CMP response. */ - cmpRspGenBindingKey_t cmpRspGenBindingKey; -} cmpMapGenBindingKey_t; - /** Map CMP command header. */ typedef struct { /** Command id. */ @@ -2024,10 +2013,6 @@ typedef union { cmpCmdGenAuthToken_t cmpCmdGenAuthToken; /** Backward compatible system response GenAuthToken. */ cmpRspGenAuthToken_t cmpRspGenAuthToken; - /** Backward compatible system command GenBindingKey. */ - cmpCmdGenBindingKey_t cmpCmdGenBindingKey; - /** Backward compatible system response GenBindingKey. */ - cmpRspGenBindingKey_t cmpRspGenBindingKey; /** Command header. */ cmpCommandHeaderMap_t cmdHeader; diff --git a/mobicore/tlcm/TlCm/3.0/tlCmApi.h b/mobicore/common/MobiCore/inc/TlCm/3.0/tlCmApi.h similarity index 85% rename from mobicore/tlcm/TlCm/3.0/tlCmApi.h rename to mobicore/common/MobiCore/inc/TlCm/3.0/tlCmApi.h index e04429d..9325e1c 100644 --- a/mobicore/tlcm/TlCm/3.0/tlCmApi.h +++ b/mobicore/common/MobiCore/inc/TlCm/3.0/tlCmApi.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP * @{ * @file @@ -36,6 +6,33 @@ * The TlCm is responsible for implementing content management protocol (CMP) * commands and generating approriate CMP responses in the trustlet control * interface (TCI). + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 TL_CM_API_H_ @@ -64,10 +61,6 @@ typedef union { cmpCmdGenAuthTokenTci_t cmpCmdGenAuthTokenTci; /** System response GenAuthToken. */ cmpRspGenAuthTokenTci_t cmpRspGenAuthTokenTci; - /** System command GenBindingKey. */ - cmpCmdGenBindingKeyTci_t cmpCmdGenBindingKeyTci; - /** System response GenBindingKey. */ - cmpRspGenBindingKeyTci_t cmpRspGenBindingKeyTci; /** Authentication command BeginSocAuthentication. */ cmpCmdBeginSocAuthenticationTci_t cmpCmdBeginSocAuthenticationTci; diff --git a/mobicore/tlcm/TlCm/cmpCommon.h b/mobicore/common/MobiCore/inc/TlCm/cmpCommon.h similarity index 65% rename from mobicore/tlcm/TlCm/cmpCommon.h rename to mobicore/common/MobiCore/inc/TlCm/cmpCommon.h index 23f8fcc..006a1c2 100644 --- a/mobicore/tlcm/TlCm/cmpCommon.h +++ b/mobicore/common/MobiCore/inc/TlCm/cmpCommon.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP_COMMON * Common definitions of content management protocols (CMP) supported by the * content management trustlet (TlCm). @@ -38,6 +8,33 @@ * Common CMP global definitions. * Various components need access to (sub-)structures defined and used by CMP. * These common definitions are made available through this header file. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 CMP_COMMON_H_ @@ -254,81 +251,6 @@ typedef struct { /** @} */ -/** @defgroup MC_CMP_CMD_GENERATE_BINDING_KEY MC_CMP_CMD_GENERATE_BINDING_KEY - * @{ */ - -/** Total number of bytes used for PSS signature in GENERATE BINDING KEY command. */ -#define CMP_GEN_BINDING_KEY_PSS_SIZE 256 - -/** Total number of bytes used for receipt data in GENERATE BINDING KEY response. */ -#define CMP_GEN_BINDING_RECEIPT_ENC_PART_SIZE 256 - -/** Maximum Length in bytes for the entropy input */ -#define CMP_GEN_BINDING_KEY_ENTROPY_SIZE_MAX (56) - -/** @defgroup MC_CMP_CMD_GENERATE_BINDING_KEY_CMD Command - * @{ */ - -typedef struct { - /** Command header. */ - cmpCommandHeader_t cmdHeader; - /** Key id. */ - uint32_t kid; -} cmpGenBindingKeyCmdSdata_t; - -typedef struct { - /** Signed data. */ - cmpGenBindingKeyCmdSdata_t sdata; - /** Signature. */ - uint8_t pssSignature[CMP_GEN_BINDING_KEY_PSS_SIZE]; - /** Production Station Serial Number. */ - uint64_t serialNumber; - /** Timestamp (seconds since epoch). */ - uint64_t timestamp; - /** Additional entropy length in bytes. */ - uint16_t entropyLen; - /** Additional entropy for K.SoC.Auth generation */ - uint8_t entropy[CMP_GEN_BINDING_KEY_ENTROPY_SIZE_MAX]; -} cmpCmdGenBindingKeyCmd_t; - -/** GenBindingKey command. */ -typedef struct { - /** Command. */ - cmpCmdGenBindingKeyCmd_t cmd; -} cmpCmdGenBindingKey_t; - -/** @} */ - -/** @defgroup MC_CMP_CMD_GENERATE_BINDING_KEY_RSP Response - * @{ */ - -/** Receipt Data. */ -typedef struct { - uint8_t dataPart1[CMP_GEN_BINDING_RECEIPT_ENC_PART_SIZE]; - uint8_t dataPart2[CMP_GEN_BINDING_RECEIPT_ENC_PART_SIZE]; -} receipt_t; - -typedef struct { - /** Response header. */ - cmpResponseHeader_t rspHeader; - /** Suid. */ - mcSuid_t suid; - /**Receipt data. */ - receipt_t receipt; -} cmpGenBindingKeyRsp_t; - -/** GenBindingKey response. */ -typedef struct { - /** Response. */ - cmpGenBindingKeyRsp_t rsp; - /** AuthToken container. */ - mcSoAuthTokenCont_t soAuthCont; -} cmpRspGenBindingKey_t; - -/** @} */ - -/** @} */ - #endif // CMP_COMMON_H_ /** @} */ diff --git a/mobicore/tlcm/TlCm/tlCmApiCommon.h b/mobicore/common/MobiCore/inc/TlCm/tlCmApiCommon.h similarity index 67% rename from mobicore/tlcm/TlCm/tlCmApiCommon.h rename to mobicore/common/MobiCore/inc/TlCm/tlCmApiCommon.h index b9912cb..1158c57 100644 --- a/mobicore/tlcm/TlCm/tlCmApiCommon.h +++ b/mobicore/common/MobiCore/inc/TlCm/tlCmApiCommon.h @@ -1,33 +1,3 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ /** @addtogroup CMP_COMMON * @{ * @file @@ -35,6 +5,33 @@ * * The TlCm is responsible for implementing content management protocol (CMP) * commands and generating approriate CMP responses. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 TL_CM_API_COMMON_H_ @@ -53,7 +50,6 @@ typedef enum cmpCommands_t { MC_CMP_CMD_BEGIN_SP_AUTHENTICATION = 3, MC_CMP_CMD_GENERATE_AUTH_TOKEN = 4, MC_CMP_CMD_GET_VERSION = 5, - MC_CMP_CMD_GENERATE_BINDING_KEY = 0x30, //MC_CMP_CMD_ROOT_CONT_ACTIVATE = 6, MC_CMP_CMD_ROOT_CONT_LOCK_BY_ROOT = 7, //MC_CMP_CMD_ROOT_CONT_REGISTER = 8, @@ -77,7 +73,7 @@ typedef enum cmpCommands_t { MC_CMP_CMD_TLT_CONT_UNREGISTER = 26, MC_CMP_CMD_GET_SUID = 27, MC_CMP_CMD_AUTHENTICATE_TERMINATE = 28, - MC_CMP_CMD_LAST_ = MC_CMP_CMD_GENERATE_BINDING_KEY, + MC_CMP_CMD_LAST_ = MC_CMP_CMD_AUTHENTICATE_TERMINATE, } cmpCommands_t; /** TlCm exit code: TlCm exited with error. */ diff --git a/mobicore/tlcm/TlCm/tlCmError.h b/mobicore/common/MobiCore/inc/TlCm/tlCmError.h similarity index 71% rename from mobicore/tlcm/TlCm/tlCmError.h rename to mobicore/common/MobiCore/inc/TlCm/tlCmError.h index 3896b7b..6d08dcb 100644 --- a/mobicore/tlcm/TlCm/tlCmError.h +++ b/mobicore/common/MobiCore/inc/TlCm/tlCmError.h @@ -1,39 +1,36 @@ -/* - * Copyright (c) 2013 TRUSTONIC LIMITED +/** @addtogroup CMP_COMMON + * @{ + * + * @file + * Content management trustlet (TlCm) error return code definitions. + * Definition of all possible TlCm error return codes. + * + * Copyright © Trustonic Limited 2013. + * * All rights reserved. * * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ -/** @addtogroup CMP_COMMON - * @{ - * - * @file - * Content management trustlet (TlCm) error return code definitions. - * Definition of all possible TlCm error return codes. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 TL_CM_ERROR_H_ diff --git a/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h b/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h new file mode 100644 index 0000000..dabb9c7 --- /dev/null +++ b/mobicore/common/MobiCore/inc/TlCm/tlCmUuid.h @@ -0,0 +1,42 @@ +/** @addtogroup CMP_COMMON + * @{ + * @file + * Content management trustlet (TlCm) Uuid definition. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 TL_CM_UUID_H +#define TL_CM_UUID_H + +/** Uuid of TlCm. */ +#define TL_CM_UUID { { 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } } + +#endif // TL_CM_UUID_H + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/TlCm/version.h b/mobicore/common/MobiCore/inc/TlCm/version.h new file mode 100644 index 0000000..a51c19e --- /dev/null +++ b/mobicore/common/MobiCore/inc/TlCm/version.h @@ -0,0 +1,44 @@ +/** @addtogroup CMP_COMMON + * @{ + * @file + * Content management trustlet (TlCm) version definition. + * + * Copyright © Trustonic Limited 2013. + * + * All rights reserved. + * + * 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. Neither the name of the Trustonic Limited nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 CMP_VERSION_H_ +#define CMP_VERSION_H_ + +/** Latest supported CMP major version number. */ +#define CMP_VERSION_MAJOR 3 +/** Latest supported CMP minor version number. */ +#define CMP_VERSION_MINOR 0 + +#endif // CMP_VERSION_H_ + +/** @} */ diff --git a/mobicore/ClientLib/include/mcContainer.h b/mobicore/common/MobiCore/inc/mcContainer.h similarity index 80% rename from mobicore/ClientLib/include/mcContainer.h rename to mobicore/common/MobiCore/inc/mcContainer.h index c74f8f1..c94e807 100644 --- a/mobicore/ClientLib/include/mcContainer.h +++ b/mobicore/common/MobiCore/inc/mcContainer.h @@ -1,32 +1,15 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. +/** @addtogroup MC_CONTAINER mcContainer - Containers for MobiCore Content Management. + * @ingroup MC_DATA_TYPES + * @{ * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. */ #ifndef MC_CONTAINER_H_ @@ -107,15 +90,15 @@ typedef enum { /** SOC container. */ CONT_TYPE_SOC = 0, /** Root container. */ - CONT_TYPE_ROOT = 1, + CONT_TYPE_ROOT, /** Service provider container. */ - CONT_TYPE_SP = 2, + CONT_TYPE_SP, /** Trustlet container. */ - CONT_TYPE_TLCON = 3, + CONT_TYPE_TLCON, /** Service provider data. */ - CONT_TYPE_SPDATA = 4, + CONT_TYPE_SPDATA, /** Trustlet data. */ - CONT_TYPE_TLDATA = 5 + CONT_TYPE_TLDATA } contType_t; /** SHA256 checksum. */ @@ -125,7 +108,7 @@ typedef struct { /** @defgroup MC_CONTAINER_CRYPTO_OBJECTS Container secrets. * Data that is stored encrypted within the container. - */ + * @{ */ /** SoC secret */ typedef struct { @@ -158,9 +141,11 @@ typedef union { mcUuid_t uuid; } mcCid_t; +/** @} */ + /** @defgroup MC_CONTAINER_CONTAINER_OBJECTS Container definitions. * Container type definitions. - */ + * @{ */ /** SoC Container */ typedef struct { @@ -228,6 +213,8 @@ typedef struct { mcCoDataCont_t co; } mcDataCont_t; +/** @} */ + /** Helper for finding maximum value */ #define MC_MAX(x, y) (((x)<(y))?(y):(x)) @@ -247,7 +234,7 @@ typedef struct { /** @defgroup MC_CONTAINER_SECURE_OBJECTS Containers in secure objects. * Secure objects wrapping different containers. - */ + * @{ */ /** Authentication token */ typedef struct { @@ -313,5 +300,8 @@ typedef struct { #define MC_TLBLOBLEN_MAGIC 0x7672746C +/** @} */ + #endif // MC_CONTAINER_H_ +/** @} */ diff --git a/mobicore/common/MobiCore/inc/mcDriverId.h b/mobicore/common/MobiCore/inc/mcDriverId.h new file mode 100644 index 0000000..df9aa88 --- /dev/null +++ b/mobicore/common/MobiCore/inc/mcDriverId.h @@ -0,0 +1,49 @@ +/** + * @file + * Driver ID definition. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef RTMDRVID_H_ +#define RTMDRVID_H_ + +#define MC_DRV_VENDOR_ID_SHIFT (16) +#define MC_DRV_VENDOR_ID_MASK (0xFFFF << MC_DRV_VENDOR_ID_SHIFT) +#define MC_DRV_NUMBER_MASK (0x0000FFFF) + +/** MobiCore vendor IDs. */ +typedef enum { + MC_DRV_VENDOR_ID_GD = 0 << MC_DRV_VENDOR_ID_SHIFT, +} mcDrvVendorId_t; + +/** MobiCore GD driver numbers. */ +typedef enum { + MC_DRV_NUMBER_INVALID = 0, + MC_DRV_NUMBER_CRYPTO = 1, + /** Last GD driver number reserved for pre-installed drivers. + * GD driver numbers up to this constant may not be used for loadable drivers. */ + MC_DRV_NUMBER_LAST_PRE_INSTALLED = 100, + TB_DRV_NUMBER_TUI = 0x101, + TB_DRV_NUMBER_TPLAY = 0x600, +} mcDrvNumber_t; + +/** MobiCore driver IDs for Trustlets. */ +typedef enum { + MC_DRV_ID_INVALID = MC_DRV_VENDOR_ID_GD | MC_DRV_NUMBER_INVALID, + MC_DRV_ID_CRYPTO = MC_DRV_VENDOR_ID_GD | MC_DRV_NUMBER_CRYPTO, + /** Last GD driver ID reserved for pre-installed drivers. + * GD driver IDs up to this constant may not be used for loadable drivers. */ + MC_DRV_ID_LAST_PRE_INSTALLED = MC_DRV_VENDOR_ID_GD | MC_DRV_NUMBER_LAST_PRE_INSTALLED, + TB_DRV_ID_TUI = MC_DRV_VENDOR_ID_GD | TB_DRV_NUMBER_TUI, + TB_DRV_ID_TPLAY = MC_DRV_VENDOR_ID_GD | TB_DRV_NUMBER_TPLAY, +} mcDriverId_t; + +#endif /* RTMDRVID_H_ */ diff --git a/mobicore/ClientLib/include/mcLoadFormat.h b/mobicore/common/MobiCore/inc/mcLoadFormat.h similarity index 64% rename from mobicore/ClientLib/include/mcLoadFormat.h rename to mobicore/common/MobiCore/inc/mcLoadFormat.h index bfa39d7..028dbb5 100644 --- a/mobicore/ClientLib/include/mcLoadFormat.h +++ b/mobicore/common/MobiCore/inc/mcLoadFormat.h @@ -1,32 +1,24 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. +/** + * @defgroup MCLF MobiCore Load Format + * + * @defgroup MCLF_VER MCLF Versions + * @ingroup MCLF * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * @addtogroup MCLF + * @{ * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * MobiCore Load Format declarations. * - * 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. + * Holds the definitions for the layout of MobiCore Trustlet Blob. * - * 3. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. */ #ifndef MCLOADFORMAT_H_ #define MCLOADFORMAT_H_ @@ -36,7 +28,7 @@ #include "mcDriverId.h" #define MCLF_VERSION_MAJOR 2 -#define MCLF_VERSION_MINOR 5 +#define MCLF_VERSION_MINOR 4 #define MCLF_VERSION_MINOR_CURRENT 3 #define MC_SERVICE_HEADER_MAGIC_BE ((uint32_t)('M'|('C'<<8)|('L'<<16)|('F'<<24))) /**< "MCLF" in big endian integer representation */ @@ -44,22 +36,26 @@ #define MC_SERVICE_HEADER_MAGIC_STR "MCLF" /**< "MCLF" as string */ /** @name MCLF flags */ +/*@{*/ #define MC_SERVICE_HEADER_FLAGS_PERMANENT (1U << 0) /**< Loaded service cannot be unloaded from MobiCore. */ #define MC_SERVICE_HEADER_FLAGS_NO_CONTROL_INTERFACE (1U << 1) /**< Service has no WSM control interface. */ #define MC_SERVICE_HEADER_FLAGS_DEBUGGABLE (1U << 2) /**< Service can be debugged. */ -#define MC_SERVICE_HEADER_FLAGS_EXTENDED_LAYOUT (1U << 3) /**< New-layout trusted application or trusted driver. */ +/*@}*/ +#if !defined(ADDR_T_DEFINED) +#define ADDR_T_DEFINED +typedef void* addr_t; /**< an address, can be physical or virtual */ +#endif // !defined(ADDR_T_DEFINED) /** Service type. * The service type defines the type of executable. */ typedef enum { - SERVICE_TYPE_ILLEGAL = 0, /**< Service type is invalid. */ - SERVICE_TYPE_DRIVER = 1, /**< Service is a driver. */ - SERVICE_TYPE_SP_TRUSTLET = 2, /**< Service is a Trustlet. */ - SERVICE_TYPE_SYSTEM_TRUSTLET = 3, /**< Service is a system Trustlet. */ - SERVICE_TYPE_MIDDLEWARE = 4, /**< Service is a middleware. */ - SERVICE_TYPE_LAST_ENTRY = 5, /**< marker for last entry */ + SERVICE_TYPE_ILLEGAL = 0, /**< Service type is invalid. */ + SERVICE_TYPE_DRIVER = 1, /**< Service is a driver. */ + SERVICE_TYPE_SP_TRUSTLET = 2, /**< Service is a Trustlet. */ + SERVICE_TYPE_SYSTEM_TRUSTLET = 3, /**< Service is a system Trustlet. */ +// SERVICE_TYPE_SP_TA = 4, /**< Service is a Trusted Application for t-base 300. */ } serviceType_t; /** @@ -75,7 +71,7 @@ typedef enum { * Descriptor for a memory segment. */ typedef struct { - uint32_t start; /**< Virtual start address. */ + addr_t start; /**< Virtual start address. */ uint32_t len; /**< Length of the segment in bytes. */ } segmentDescriptor_t, *segmentDescriptor_ptr; @@ -88,6 +84,8 @@ typedef struct { uint32_t version; /**< Version of the MCLF header structure. */ } mclfIntro_t, *mclfIntro_ptr; +/** @} */ + // Version 2 ///////////////////////////////////////////////////////////////////////////////////////////////////////// /** @@ -95,6 +93,7 @@ typedef struct { * @ingroup MCLF_VER * * @addtogroup MCLF_VER_V2 + * @{ */ /** @@ -121,7 +120,7 @@ typedef struct { segmentDescriptor_t text; /**< Virtual text segment. */ segmentDescriptor_t data; /**< Virtual data segment. */ uint32_t bssLen; /**< Length of the BSS segment in bytes. MUST be at least 8 byte. */ - uint32_t entry; /**< Virtual start address of service code. */ + addr_t entry; /**< Virtual start address of service code. */ uint32_t serviceVersion; /**< Version of the interface the driver exports. */ // These should be put on next MCLF update: @@ -129,6 +128,7 @@ typedef struct { // uint32_t permittedHwCf; /**< Starting 2.3: If nonzero, hw configuration which is allowed to execute binary */ } mclfHeaderV2_t, *mclfHeaderV2_ptr; +/** @} */ /** @@ -139,6 +139,7 @@ typedef struct { mcSuid_t permittedSuid; /**< Starting 2.3: If nonzero, suid which is allowed to execute binary */ uint32_t permittedHwCfg; /**< Starting 2.3: If nonzero, hw configuration which is allowed to execute binary */ } mclfHeaderV23_t, *mclfHeaderV23_ptr; +/** @} */ /** @@ -150,57 +151,10 @@ typedef struct { uint32_t attestationOffset; /**=2.5) - * - * `mcLibData` field describes McLib work buffer - * and it is used for MCLF header versions <=2.4 - * In this case the buffer is a part of TA BSS section - * - * For MCLF header versions >=2.5 `mcLibData` field is not used anymore and - * replaced by `mcLibData` field - * RTM itself determines actual address in this case and sets `mcLibData` field value - * - * `heapSize` field describes default heap parameters and - * it is used only for MCLF header versions >=2.5 - * - */ -typedef struct { - union { - segmentDescriptor_t mcLibData; /**< Segment for McLib data. - Set at compile time. - Required always. */ - heapSize_t heapSize; /**< Initial and maximum heap sizes. - Set by MobiConvert for extended-layout TAs */ - } cfg; - uint32_t mcLibBase; /**< McLib base address. - Mobicore sets at load time for trustlets / drivers. - Required always. */ -} mclfIMD_t, *mclfIMD_ptr; - - -/* - * GP TA identity. - */ -typedef struct { - uint32_t loginType; /**< GP TA login type */ - uint8_t loginData[16]; /**< GP TA login data */ -} mcIdentity_t; - /** * Version 2 MCLF text segment header. * Required to be present in MobiCore 1.2 components at address (0x1080). @@ -211,24 +165,30 @@ typedef struct { uint32_t version; /**< Version of the TextHeader structure. */ uint32_t textHeaderLen; /**< Size of this structure (fixed at compile time) */ uint32_t requiredFeat; /**< Flags to indicate features that Mobicore must understand/interprete when loading. + Initial value set at compile time. Required always. */ - uint32_t mcLibEntry; /**< Address for McLib entry. + addr_t mcLibEntry; /**< Address for McLib entry. + Mobicore sets at load time for trustlets / drivers. + Required always. */ + segmentDescriptor_t mcLibData; /**< Segment for McLib data. + Set at compile time. + Required always. */ + addr_t mcLibBase; /**< McLib base address. Mobicore sets at load time for trustlets / drivers. Required always. */ - mclfIMD_t mcIMD; /**< McLib Internal Management Data */ uint32_t tlApiVers; /**< TlApi version used when building trustlet. Value set at compile time. Required always. */ uint32_t drApiVers; /**< DrApi version used when building trustlet. Value set at compile time for drivers. 0 for trustlets. Required always. */ - uint32_t ta_properties; /**< address of _TA_Properties in the TA. */ - mcIdentity_t mcIdentity; /**< Identity of GP TA */ + addr_t ta_properties; /**< address of _TA_Properties in the TA. */ } mclfTextHeader_t, *mclfTextHeader_ptr; // Version 2 /////////////////////////////////////////////////////////////////////////////////////////////////// /** * @addtogroup MCLF + * @{ */ /** MCLF header */ @@ -248,12 +208,6 @@ typedef union { // This is only minimum size, so nothing below this makes sense. #define MCLF_BINARY_MIN_SIZE(version) (MCLF_HEADER_SIZE_V23+sizeof(mclfTextHeader_t)) -/** mclfTlHeader: layout of TA start */ -typedef struct { - mclfIntro_t intro; - uint8_t mclfHeader[0x80-sizeof(mclfIntro_t)]; - mclfTextHeader_t textHeader; -} mclfTlHeader_t; - #endif /* MCLOADFORMAT_H_ */ +/** @} */ diff --git a/mobicore/common/MobiCore/inc/mcRootid.h b/mobicore/common/MobiCore/inc/mcRootid.h new file mode 100644 index 0000000..b60bb56 --- /dev/null +++ b/mobicore/common/MobiCore/inc/mcRootid.h @@ -0,0 +1,36 @@ +/** + * @addtogroup MC_ROOTID mcRootid - Root container id. + * + * Global definition of root ID. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + * + * @ingroup MC_DATA_TYPES + * @{ + */ + +#ifndef MC_ROOTID_H_ +#define MC_ROOTID_H_ + +/** Root Identifier type. */ +typedef uint32_t mcRootid_t; + +/** Reserved root id value 1. */ +static const mcRootid_t MC_ROOTID_RESERVED1 = 0; + +/** Reserved root id value 2. */ +static const mcRootid_t MC_ROOTID_RESERVED2 = 0xFFFFFFFF; + +/** Root id for system applications. */ +static const mcRootid_t MC_ROOTID_SYSTEM = 0xFFFFFFFE; + +#endif // MC_ROOTID_H_ + +/** @} */ diff --git a/mobicore/ClientLib/include/mcSo.h b/mobicore/common/MobiCore/inc/mcSo.h similarity index 80% rename from mobicore/ClientLib/include/mcSo.h rename to mobicore/common/MobiCore/inc/mcSo.h index d33f055..848d6d4 100644 --- a/mobicore/ClientLib/include/mcSo.h +++ b/mobicore/common/MobiCore/inc/mcSo.h @@ -1,32 +1,20 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. +/** + * @defgroup MC_DATA_TYPES MobiCore generic data types + * + * @addtogroup MC_SO mcSo - Secure objects definitions. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + * + * @ingroup MC_DATA_TYPES + * @{ + * */ #ifndef MC_SO_H_ @@ -102,9 +90,6 @@ typedef struct { mcRootid_t rootid; } tlApiSpTrustletIdEx_t; -// The client identity (encoding its root ID, SPID and UUID). -typedef tlApiSpTrustletIdEx_t client_identity_t; - /** Secure object header v2.2. * A secure object header introduces a secure object. * Layout of a secure object: @@ -246,3 +231,4 @@ typedef struct { #endif // MC_SO_H_ +/** @} */ diff --git a/mobicore/common/MobiCore/inc/mcSpid.h b/mobicore/common/MobiCore/inc/mcSpid.h new file mode 100644 index 0000000..2714d1e --- /dev/null +++ b/mobicore/common/MobiCore/inc/mcSpid.h @@ -0,0 +1,38 @@ +/** + * @addtogroup MC_SPID mcSpid - service provider ID. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + * + * @ingroup MC_DATA_TYPES + * @{ + */ + +#ifndef MC_SPID_H_ +#define MC_SPID_H_ + +/** Service provider Identifier type. */ +typedef uint32_t mcSpid_t; + +/** SPID value used as free marker in root containers. */ +static const mcSpid_t MC_SPID_FREE = 0xFFFFFFFF; + +/** Reserved SPID value. */ +static const mcSpid_t MC_SPID_RESERVED = 0; + +/** SPID for system applications. */ +static const mcSpid_t MC_SPID_SYSTEM = 0xFFFFFFFE; + +/** SPID reserved for tests only */ +static const mcSpid_t MC_SPID_RESERVED_TEST = 0xFFFFFFFD; +static const mcSpid_t MC_SPID_TRUSTONIC_TEST = 0x4; + +#endif // MC_SPID_H_ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/mcSuid.h b/mobicore/common/MobiCore/inc/mcSuid.h new file mode 100644 index 0000000..a80cfc5 --- /dev/null +++ b/mobicore/common/MobiCore/inc/mcSuid.h @@ -0,0 +1,36 @@ +/** + * @addtogroup MC_SUID mcSuid - SoC unique ID. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + * + * @ingroup MC_DATA_TYPES + * @{ + */ + +#ifndef MC_SUID_H_ +#define MC_SUID_H_ + +/** Length of SUID. */ +#define MC_SUID_LEN 16 + +/** Platform specific device identifier (serial number of the chip). */ +typedef struct { + uint8_t data[MC_SUID_LEN - sizeof(uint32_t)]; +} suidData_t; + +/** Soc unique identifier type. */ +typedef struct { + uint32_t sipId; /**< Silicon Provider ID to be set during build. */ + suidData_t suidData; +} mcSuid_t; + +#endif // MC_SUID_H_ + +/** @} */ diff --git a/mobicore/common/MobiCore/inc/mcUuid.h b/mobicore/common/MobiCore/inc/mcUuid.h new file mode 100644 index 0000000..16ebb85 --- /dev/null +++ b/mobicore/common/MobiCore/inc/mcUuid.h @@ -0,0 +1,57 @@ +/** + * @addtogroup MC_UUID mcUuid - Universally Unique Identifier. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + * + * @ingroup MC_DATA_TYPES + * @{ + */ + +#ifndef MC_UUID_H_ +#define MC_UUID_H_ + +#define UUID_TYPE + +#define UUID_LENGTH 16 +/** Universally Unique Identifier (UUID) according to ISO/IEC 11578. */ +typedef struct { + uint8_t value[UUID_LENGTH]; /**< Value of the UUID. */ +} mcUuid_t, *mcUuid_ptr; + +/** UUID value used as free marker in service provider containers. */ +#define MC_UUID_FREE_DEFINE \ + { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +static const mcUuid_t MC_UUID_FREE = { + MC_UUID_FREE_DEFINE +}; + +/** Reserved UUID. */ +#define MC_UUID_RESERVED_DEFINE \ + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } + +static const mcUuid_t MC_UUID_RESERVED = { + MC_UUID_RESERVED_DEFINE +}; + +/** UUID for system applications. */ +#define MC_UUID_SYSTEM_DEFINE \ + { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE } + +static const mcUuid_t MC_UUID_SYSTEM = { + MC_UUID_SYSTEM_DEFINE +}; + +#endif // MC_UUID_H_ + +/** @} */ diff --git a/mobicore/ClientLib/include/mcVersionHelper.h b/mobicore/common/MobiCore/inc/mcVersionHelper.h similarity index 79% rename from mobicore/ClientLib/include/mcVersionHelper.h rename to mobicore/common/MobiCore/inc/mcVersionHelper.h index 7f89797..a5af69f 100644 --- a/mobicore/ClientLib/include/mcVersionHelper.h +++ b/mobicore/common/MobiCore/inc/mcVersionHelper.h @@ -1,39 +1,25 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. +/** @addtogroup MC_RTM + * @{ + * MobiCore Version Helper Macros + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. */ - -#ifndef MCVERSIONHELPER_H_ -#define MCVERSIONHELPER_H_ - #include +//lint -emacro(*,MC_CHECK_VERSION) Disable all warnings for this macro. +//lint -emacro(*,MC_MAKE_VERSION) Disable all warnings for this macro. +//lint -emacro(*,MC_GET_MAJOR_VERSION) Disable all warnings for this macro. +//lint -emacro(*,MC_GET_MINOR_VERSION) Disable all warnings for this macro. +//lint -emacro(*,MC_GET_MINOR_VERSION) Disable all warnings for this macro. +//lint -emacro(*,ASSERT_VERSION_IMPLEMENTATION) Disable all warnings for this macro. +//lint -esym(*,Actual_*) Disable all warnings for these functions. /** Create a version number given major and minor numbers. */ #define MC_MAKE_VERSION(major,minor) \ @@ -104,8 +90,7 @@ uint32_t minor = MC_GET_MINOR_VERSION(version); \ uint32_t ret = 0; \ *errmsg = msgBuf; \ - /* Check equality and superiority separately to avoid warning if minor == 0 */ \ - if ((major == majorRequired) && ((minor == minorRequired) || (minor > minorRequired))) { \ + if ((major == majorRequired) && (minor >= minorRequired)) { \ snprintf(msgBuf, sizeof(msgBuf), \ #comp " version is %u.%u", major, minor); \ ret = 1; \ @@ -140,8 +125,7 @@ uint32_t major = MC_GET_MAJOR_VERSION(version); \ uint32_t minor = MC_GET_MINOR_VERSION(version); \ *errmsg = NULL; \ - /* Check equality and superiority separately to avoid warning if minor == 0 */ \ - if ((major == majorRequired) && ((minor == minorRequired) || (minor > minorRequired))) { \ + if ((major == majorRequired) && (minor >= minorRequired)) { \ return 1; \ }; \ return 0; \ @@ -192,8 +176,7 @@ ret = 1; \ } else { \ snprintf(msgBuf, sizeof(msgBuf), \ - #comp " version error. Got: %u.%u, want <= %u.%u", major, minor, \ - (uint32_t)majorRequired, (uint32_t)minorRequired); \ + #comp " version error. Got: %u.%u, want <= %u.%u", major, minor, majorRequired, minorRequired); \ } \ msgBuf[sizeof(msgBuf) - 1] = '\0'; \ return ret; \ @@ -210,8 +193,7 @@ return 1; \ } else { \ tlDbgPrintf( \ - #comp " version error. Got: %u.%u, want <= %u.%u", major, minor, \ - (uint32_t)majorRequired, (uint32_t)minorRequired); \ + #comp " version error. Got: %u.%u, want <= %u.%u", major, minor, majorRequired, minorRequired); \ } \ return 0; \ } @@ -229,5 +211,3 @@ return 0; \ } #endif - -#endif // MCVERSIONHELPER_H_ diff --git a/mobicore/common/MobiCore/inc/mcVersionInfo.h b/mobicore/common/MobiCore/inc/mcVersionInfo.h new file mode 100644 index 0000000..f93115a --- /dev/null +++ b/mobicore/common/MobiCore/inc/mcVersionInfo.h @@ -0,0 +1,35 @@ +/** @addtogroup MC_RTM + * @{ + * MobiCore Version Information + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef MCVERSIONINFO_H_ +#define MCVERSIONINFO_H_ + +/** Length of MobiCore product ID string. */ +#define MC_PRODUCT_ID_LEN 64 + +/** Global MobiCore Version Information. + */ +typedef struct { + char productId[MC_PRODUCT_ID_LEN]; /** < Product ID of Mobicore; zero-terminated */ + uint32_t versionMci; /** < Version of Mobicore Control Interface */ + uint32_t versionSo; /** < Version of Secure Objects */ + uint32_t versionMclf; /** < Version of MobiCore Load Format */ + uint32_t versionContainer; /** < Version of MobiCore Container Format */ + uint32_t versionMcConfig; /** < Version of MobiCore Configuration Block Format */ + uint32_t versionTlApi; /** < Version of MobiCore Trustlet API Implementation */ + uint32_t versionDrApi; /** < Version of MobiCore Driver API Implementation */ + uint32_t versionCmp; /** < Version of Content Management Protocol */ +} mcVersionInfo_t; + +#endif /** MCVERSIONINFO_H_ */ diff --git a/mobicore/daemon/Android.mk b/mobicore/daemon/Android.mk new file mode 100644 index 0000000..fe884ff --- /dev/null +++ b/mobicore/daemon/Android.mk @@ -0,0 +1,115 @@ +# ============================================================================= +# +# MobiCore Android build components +# +# ============================================================================= + +LOCAL_PATH := $(call my-dir) + +# Client Library +# ============================================================================= +include $(CLEAR_VARS) +LOCAL_MODULE := libMcClient +LOCAL_MODULE_TAGS := debug eng optional +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) liblog + +LOCAL_CFLAGS := -fvisibility=hidden -fvisibility-inlines-hidden +LOCAL_CFLAGS += -include buildTag.h +LOCAL_CFLAGS += -DLOG_TAG=\"McClient\" +LOCAL_CFLAGS += -DTBASE_API_LEVEL=3 + +# Add new source files here +LOCAL_SRC_FILES += \ + ClientLib/Device.cpp \ + ClientLib/ClientLib.cpp \ + ClientLib/Session.cpp \ + Common/CMutex.cpp \ + Common/Connection.cpp \ + ClientLib/GP/tee_client_api.cpp + +LOCAL_C_INCLUDES +=\ + $(LOCAL_PATH)/Common \ + $(LOCAL_PATH)/ClientLib/public \ + $(LOCAL_PATH)/ClientLib/public/GP \ + $(LOCAL_PATH)/../common/LogWrapper \ + $(COMP_PATH_MobiCore)/inc/McLib + +LOCAL_EXPORT_C_INCLUDE_DIRS +=\ + $(COMP_PATH_MobiCore)/inc \ + $(LOCAL_PATH)/ClientLib/public + +LOCAL_CFLAGS += -DLOG_ANDROID + +include $(LOCAL_PATH)/Kernel/Android.mk + +include $(BUILD_SHARED_LIBRARY) + +# Daemon Application +# ============================================================================= +include $(CLEAR_VARS) + +LOCAL_MODULE := mcDriverDaemon +LOCAL_MODULE_TAGS := debug eng optional +LOCAL_CFLAGS += -include buildTag.h +LOCAL_CFLAGS += -DLOG_TAG=\"McDaemon\" +LOCAL_CFLAGS += -DTBASE_API_LEVEL=3 +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) libMcClient liblog + +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 \ + $(LOCAL_PATH)/../common/LogWrapper + + +# Private Registry components +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Registry/Public \ + $(LOCAL_PATH)/Registry +LOCAL_SRC_FILES += Registry/PrivateRegistry.cpp + +# Common components +include $(LOCAL_PATH)/Kernel/Android.mk + +LOCAL_CFLAGS += -DLOG_ANDROID + +include $(BUILD_EXECUTABLE) + +# Registry Shared Library +# ============================================================================= +include $(CLEAR_VARS) + +LOCAL_MODULE := libMcRegistry +LOCAL_MODULE_TAGS := debug eng optional +LOCAL_CFLAGS += -DLOG_TAG=\"McRegistry\" +LOCAL_C_INCLUDES += $(GLOBAL_INCLUDES) +LOCAL_SHARED_LIBRARIES += $(GLOBAL_LIBRARIES) liblog + +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Common \ + $(LOCAL_PATH)/Daemon/public \ + $(LOCAL_PATH)/ClientLib/public \ + $(LOCAL_PATH)/../common/LogWrapper + +# Common Source files required for building the daemon +LOCAL_SRC_FILES += Common/CMutex.cpp \ + Common/Connection.cpp \ + Common/CSemaphore.cpp \ +# Common/CThread.cpp + +#LOCAL_LDLIBS := -lthread_db + +include $(LOCAL_PATH)/Registry/Android.mk + +LOCAL_CFLAGS += -DLOG_ANDROID + +include $(BUILD_SHARED_LIBRARY) diff --git a/mobicore/daemon/Application.mk b/mobicore/daemon/Application.mk new file mode 100644 index 0000000..dda3298 --- /dev/null +++ b/mobicore/daemon/Application.mk @@ -0,0 +1,26 @@ +# ============================================================================= +# +# Main build file defining the project modules and their global variables. +# +# ============================================================================= + +# Don't remove this - mandatory +APP_PROJECT_PATH := $(abspath $(call my-dir)) + +# The only STL implementation currently working with exceptions +APP_STL := stlport_static + +# Don't optimize for better debugging +APP_OPTIM := debug + +# Application wide Cflags +GLOBAL_INCLUDES := \ + $(COMP_PATH_MobiCoreDriverMod)/Public \ + $(COMP_PATH_MobiCore)/inc \ + $(COMP_PATH_TlCm)/Public \ + $(COMP_PATH_TlCm)/Public/TlCm + +# Show all warnings +APP_CFLAGS += -Wall + +APP_PLATFORM := android-9 diff --git a/mobicore/daemon/CleanSpec.mk b/mobicore/daemon/CleanSpec.mk new file mode 100644 index 0000000..7dd6f6c --- /dev/null +++ b/mobicore/daemon/CleanSpec.mk @@ -0,0 +1,61 @@ +# Copyright (C) 2007 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# If you don't need to do a full clean build but would like to touch +# a file or delete some intermediate files, add a clean step to the end +# of the list. These steps will only be run once, if they haven't been +# run before. +# +# E.g.: +# $(call add-clean-step, touch -c external/sqlite/sqlite3.h) +# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates) +# +# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with +# files that are missing or have been moved. +# +# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory. +# Use $(OUT_DIR) to refer to the "out" directory. +# +# If you need to re-do something that's already mentioned, just copy +# the command and add it to the bottom of the list. E.g., if a change +# that you made last week required touching a file and a change you +# made today requires touching the same file, just copy the old +# touch step and add it to the end of the list. +# +# ************************************************ +# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST +# ************************************************ + +# For example: +#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates) +#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates) +#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/openssl_intermediates $(PRODUCT_OUT)/obj/EXECUTABLES/ssltest_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libssl_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libcrypto_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libssl_static_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libcrypto_static_intermediates) +#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES/*ssl*_intermediates $(PRODUCT_OUT)/obj/*/libssl_*intermediates $(PRODUCT_OUT)/obj/*/libcrypto_*intermediates) + +# ************************************************ +# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST +# ************************************************ diff --git a/mobicore/daemon/ClientLib/Android.mk b/mobicore/daemon/ClientLib/Android.mk new file mode 100644 index 0000000..8081935 --- /dev/null +++ b/mobicore/daemon/ClientLib/Android.mk @@ -0,0 +1,7 @@ +# ============================================================================= +# +# Module: libMcClient.so - Client Lib for TLC's +# +# ============================================================================= + +LOCAL_PATH := $(call my-dir) diff --git a/mobicore/daemon/ClientLib/ClientLib.cpp b/mobicore/daemon/ClientLib/ClientLib.cpp new file mode 100644 index 0000000..32b8d61 --- /dev/null +++ b/mobicore/daemon/ClientLib/ClientLib.cpp @@ -0,0 +1,1492 @@ +/** @addtogroup MCD_IMPL_LIB + * @{ + * @file + * + * +#ifndef WIN32 +#include +#include +#include "assert.h" +#endif + +#include "public/MobiCoreDriverApi.h" + +#ifndef WIN32 +#include "mc_linux.h" +#include "Connection.h" +#include "CMutex.h" +#include "Device.h" +#include "mcVersionHelper.h" + +#include "Daemon/public/MobiCoreDriverCmd.h" +#include "Daemon/public/mcVersion.h" + +#include "log.h" + +#include "Mci/mcimcp.h" + +MC_CHECK_VERSION(DAEMON, 0, 2); + +/** Notification data structure. */ +typedef struct { + uint32_t sessionId; /**< Session ID. */ + int32_t payload; /**< Additional notification information. */ +} notification_t; + +using namespace std; + +static list devices; + +// Forward declarations. +uint32_t getDaemonVersion(Connection *devCon, uint32_t *version); + +static CMutex devMutex; +//------------------------------------------------------------------------------ +Device *resolveDeviceId(uint32_t deviceId) +{ + for (list::iterator iterator = devices.begin(); + iterator != devices.end(); + ++iterator) { + Device *device = (*iterator); + + if (device->deviceId == deviceId) { + return device; + } + } + return NULL; +} + + +//------------------------------------------------------------------------------ +void addDevice(Device *device) +{ + devices.push_back(device); +} + + +//------------------------------------------------------------------------------ +bool removeDevice(uint32_t deviceId) +{ + for (list::iterator iterator = devices.begin(); + iterator != devices.end(); + ++iterator) { + Device *device = (*iterator); + + if (device->deviceId == deviceId) { + devices.erase(iterator); + delete device; + return true; + } + } + 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 has not been found"); \ + mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; \ + break; \ + } + +#define CHECK_DEVICE_CLOSED(device, deviceId) \ + if (NULL == device && MC_DEVICE_ID_DEFAULT == deviceId) \ + { \ + LOG_E("Device not open"); \ + mcResult = MC_DRV_ERR_DAEMON_DEVICE_NOT_OPEN; \ + break; \ + } else \ + CHECK_DEVICE(device); + + + +#define CHECK_NOT_NULL(X) \ + if (NULL == X) \ + { \ + LOG_E("Parameter \""#X "\" is NULL"); \ + mcResult = MC_DRV_ERR_NULL_POINTER; \ + break; \ + } + +#define CHECK_SESSION(S,SID) \ + if (NULL == S) \ + { \ + LOG_E("Session %i not found", SID); \ + mcResult = MC_DRV_ERR_UNKNOWN_SESSION; \ + break; \ + } + +//------------------------------------------------------------------------------ +// 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("sending to Daemon failed."); \ + mcResult = MC_DRV_ERR_SOCKET_WRITE; \ + break; \ + } \ +} + +#define RECV_FROM_DAEMON(CONNECTION, RSP_STRUCT) \ +{ \ + int rlen = CONNECTION->readData( \ + RSP_STRUCT, \ + sizeof(*RSP_STRUCT)); \ + if (rlen <= 0) { \ + LOG_E("reading from Daemon failed"); \ + mcResult = MC_DRV_ERR_SOCKET_READ; \ + break; \ + } \ + if (rlen != sizeof(*RSP_STRUCT) && rlen != sizeof(mcDrvResponseHeader_t)) {\ + LOG_E("wrong buffer length %i received from Daemon", rlen); \ + mcResult = MC_DRV_ERR_SOCKET_LENGTH; \ + break; \ + } \ +} +#endif /* WIN32 */ + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcOpenDevice(uint32_t deviceId) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + Connection *devCon = NULL; + + devMutex.lock(); + LOG_I("===%s(%i)===", __FUNCTION__, deviceId); + + do { + Device *device = resolveDeviceId(deviceId); + if (device != NULL) { + LOG_E("Device %d already opened", deviceId); + mcResult = MC_DRV_ERR_DEVICE_ALREADY_OPEN; + break; + } + + // Handle SIGPIPE inside write() + // If Daemon crashes and ClientLib writes to named socket, + // a sigpipe is send to ClientLib/TLC and kills it. + signal(SIGPIPE, SIG_IGN); + + // Open new connection to device + devCon = new Connection(); + if (!devCon->connect(SOCK_PATH)) { + LOG_W(" Could not connect to %s socket", SOCK_PATH); + mcResult = MC_DRV_ERR_SOCKET_CONNECT; + break; + } + + // Runtime check of Daemon version. + char *errmsg; + uint32_t version = 0; + mcResult = getDaemonVersion(devCon, &version); + if (mcResult != MC_DRV_OK) { + break; + } + if (!checkVersionOkDAEMON(version, &errmsg)) { + LOG_E("%s", errmsg); + mcResult = MC_DRV_ERR_DAEMON_VERSION; + break; + } + LOG_I(" %s", errmsg); + + // Forward device open to the daemon and read result + SEND_TO_DAEMON(devCon, MC_DRV_CMD_OPEN_DEVICE, deviceId); + + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_W(" %s(): Request at Daemon failed, respId=%x ", __FUNCTION__, mcResult); + break; + } + + // there is no payload to read + + device = new Device(deviceId, devCon); + mcResult = device->open("/dev/" MC_USER_DEVNODE); + if (mcResult != MC_DRV_OK) { + delete device; + // devCon is freed in the Device destructor + devCon = NULL; + LOG_E("Could not open device file: /dev/%s", MC_USER_DEVNODE); + break; + } + + addDevice(device); + + } while (false); + + devMutex.unlock(); + if (mcResult != MC_DRV_OK) { + if (devCon != NULL) + delete devCon; + LOG_I(" Device not opened."); + } else { + LOG_I(" Successfully opened the device."); + } + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcCloseDevice( + uint32_t deviceId +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + devMutex.lock(); + LOG_I("===%s(%i)===", __FUNCTION__, deviceId); + do { + Device *device = resolveDeviceId(deviceId); + // CHECK_DEVICE(device); + CHECK_DEVICE_CLOSED(device, deviceId); + + Connection *devCon = device->connection; + + // Check if daemon is still alive + if (!devCon->isConnectionAlive()) { + removeDevice(deviceId); + LOG_E("Daemon is dead removing device"); + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; + break; + } + + // Return if not all sessions have been closed + // TODO-2012-08-31-haenellu: improve check, if device connection is dead, this makes no more sense. + if (device->hasSessions()) { + LOG_E("Trying to close device while sessions are still pending."); + mcResult = MC_DRV_ERR_SESSION_PENDING; + break; + } + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_CLOSE_DEVICE); + + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_W(" %s(): Request at Daemon failed, respId=%d ", __FUNCTION__, mcResult); + break; + } + + removeDevice(deviceId); + + } while (false); + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcOpenSession( + mcSessionHandle_t *session, + const mcUuid_t *uuid, + uint8_t *tci, + uint32_t len +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + BulkBufferDescriptor *bulkBuf = NULL; + + do { + uint32_t handle = 0; + CHECK_NOT_NULL(session); + CHECK_NOT_NULL(uuid); + + if (len > MC_MAX_TCI_LEN) { + LOG_E("TCI length is longer than %d", MC_MAX_TCI_LEN); + mcResult = MC_DRV_ERR_TCI_TOO_BIG; + break; + } + + // Get the device associated with the given session + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); + + Connection *devCon = device->connection; + + // First assume the TCI is a contiguous buffer + // Get the physical address of the given TCI + CWsm_ptr pWsm = device->findContiguousWsm(tci); + if (pWsm == NULL) { + if (tci != NULL && len != 0) { + // Then assume it's a normal buffer that needs to be mapped + mcResult = device->mapBulkBuf(tci, len, &bulkBuf); + if (mcResult != MC_DRV_OK) { + LOG_E("Registering buffer failed. ret=%x", mcResult); + mcResult = MC_DRV_ERR_WSM_NOT_FOUND; + break; + } + handle = bulkBuf->handle; + } else if ( len != 0 ) { + LOG_E("mcOpenSession(): length is more than allocated TCI"); + mcResult = MC_DRV_ERR_TCI_GREATER_THAN_WSM; + break; + } + } else { + if (pWsm->len < len) { + LOG_E("mcOpenSession(): length is more than allocated TCI"); + mcResult = MC_DRV_ERR_TCI_GREATER_THAN_WSM; + break; + } + handle = pWsm->handle; + } + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_OPEN_SESSION, + session->deviceId, + *uuid, + (uintptr_t)(tci) & 0xFFF, + (uint32_t)handle, + len); + + // Read command response + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + // TODO-2012-09-06-haenellu: Remove this code once tests can handle it + + if (MC_DRV_ERROR_MAJOR(mcResult) != MC_DRV_ERR_MCP_ERROR) { + LOG_E("Daemon could not open session, responseId %d.", mcResult); + } else { + uint32_t mcpResult = MC_DRV_ERROR_MCP(mcResult); + LOG_E("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)) { + LOG_E("Could not connect to %s", SOCK_PATH); + delete sessionConnection; + // Here we know we couldn't connect to the Daemon. + // Maybe we should use existing connection to close Trustlet. + mcResult = MC_DRV_ERR_SOCKET_CONNECT; + break; + } + + do { + SEND_TO_DAEMON(sessionConnection, MC_DRV_CMD_NQ_CONNECT, + session->deviceId, + session->sessionId, + rspOpenSessionPayload.deviceSessionId, + rspOpenSessionPayload.sessionMagic); + + RECV_FROM_DAEMON(sessionConnection, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("CMD_NQ_CONNECT failed, respId=%d", mcResult); + break; + } + + } while (0); + if (mcResult != MC_DRV_OK) { + delete sessionConnection; + // Here we know we couldn't communicate well with the Daemon. + // Maybe we should use existing connection to close Trustlet. + break; // unlock mutex and return + } + + // there is no payload. + + // Session has been established, new session object must be created + Session *sessionObj = device->createNewSession(session->sessionId, sessionConnection); + // If the session tci was a mapped buffer then register it + if (bulkBuf) + sessionObj->addBulkBuf(bulkBuf); + + LOG_I(" Successfully opened session %d.", session->sessionId); + + } while (false); + + if (mcResult != MC_DRV_OK && bulkBuf) { + delete bulkBuf; + } + +// TODO: enable as soon as there are more error codes +// if (mcResult == MC_DRV_ERR_SOCKET_WRITE || mcResult == MC_DRV_ERR_SOCKET_READ) { +// LOG_E("Connection is dead, removing device."); +// removeDevice(session->deviceId); +// } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcOpenTrustlet( + mcSessionHandle_t *session, + mcSpid_t spid, + uint8_t *trustlet, + uint32_t tlen, + uint8_t *tci, + uint32_t len +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + BulkBufferDescriptor *bulkBuf = NULL; + + do { + uint32_t handle = 0; + CHECK_NOT_NULL(session); + CHECK_NOT_NULL(trustlet); + CHECK_NOT_NULL(tci); + + if (len > MC_MAX_TCI_LEN) { + LOG_E("TCI length is longer than %d", MC_MAX_TCI_LEN); + mcResult = MC_DRV_ERR_TCI_TOO_BIG; + break; + } + + // Get the device associated with the given session + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); + + Connection *devCon = device->connection; + + // First assume the TCI is a contiguous buffer + // Get the physical address of the given TCI + CWsm_ptr pWsm = device->findContiguousWsm(tci); + if (pWsm == NULL) { + // Then assume it's a normal buffer that needs to be mapped + mcResult = device->mapBulkBuf(tci, len, &bulkBuf); + if (mcResult != MC_DRV_OK) { + LOG_E("Registering buffer failed. ret=%x", mcResult); + mcResult = MC_DRV_ERR_WSM_NOT_FOUND;; + break; + } + handle = bulkBuf->handle; + } else { + if (pWsm->len < len) { + LOG_E("mcOpenSession(): length is more than allocated TCI"); + mcResult = MC_DRV_ERR_TCI_GREATER_THAN_WSM; + break; + } + handle = pWsm->handle; + } + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_OPEN_TRUSTLET, + session->deviceId, + spid, + (uint32_t)tlen, + (uintptr_t)(tci) & 0xFFF, + (uint32_t)handle, + len); + + // Send the full trustlet data + int ret = devCon->writeData(trustlet, tlen); + if (ret < 0) { + LOG_E("sending to Daemon failed."); + \ + mcResult = MC_DRV_ERR_SOCKET_WRITE; + \ + break; + } + + // Read command response + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + // TODO-2012-09-06-haenellu: Remove this code once tests can handle it + + if (MC_DRV_ERROR_MAJOR(mcResult) != MC_DRV_ERR_MCP_ERROR) { + LOG_E("Daemon could not open session, responseId %d.", mcResult); + } else { + uint32_t mcpResult = MC_DRV_ERROR_MCP(mcResult); + LOG_E("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)) { + LOG_E("Could not connect to %s", SOCK_PATH); + delete sessionConnection; + // Here we know we couldn't connect to the Daemon. + // Maybe we should use existing connection to close Trustlet. + mcResult = MC_DRV_ERR_SOCKET_CONNECT; + break; + } + + do { + SEND_TO_DAEMON(sessionConnection, MC_DRV_CMD_NQ_CONNECT, + session->deviceId, + session->sessionId, + rspOpenSessionPayload.deviceSessionId, + rspOpenSessionPayload.sessionMagic); + + RECV_FROM_DAEMON(sessionConnection, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("CMD_NQ_CONNECT failed, respId=%d", mcResult); + break; + } + + } while (0); + + if (mcResult != MC_DRV_OK) { + delete sessionConnection; + // Here we know we couldn't communicate well with the Daemon. + // Maybe we should use existing connection to close Trustlet. + break; // unlock mutex and return + } + + // there is no payload. + + // Session has been established, new session object must be created + Session *sessionObj = device->createNewSession(session->sessionId, sessionConnection); + // If the session tci was a mapped buffer then register it + if (bulkBuf) + sessionObj->addBulkBuf(bulkBuf); + + LOG_I(" Successfully opened session %d.", session->sessionId); + + } while (false); + + if (mcResult != MC_DRV_OK && bulkBuf) { + delete bulkBuf; + } + +// TODO: enable as soon as there are more error codes +// if (mcResult == MC_DRV_ERR_SOCKET_WRITE || mcResult == MC_DRV_ERR_SOCKET_READ) { +// LOG_E("Connection is dead, removing device."); +// removeDevice(session->deviceId); +// } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcOpenGPTA( + mcSessionHandle_t *session, + const mcUuid_t *uuid, + uint8_t *tci, + uint32_t len +) +{ + mcResult_t mcResult = MC_DRV_OK; + +#ifndef WIN32 + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + BulkBufferDescriptor *bulkBuf = NULL; + + do { + uint32_t handle = 0; + CHECK_NOT_NULL(session); + CHECK_NOT_NULL(uuid); + + if (len > MC_MAX_TCI_LEN) { + LOG_E("TCI length is longer than %d", MC_MAX_TCI_LEN); + mcResult = MC_DRV_ERR_TCI_TOO_BIG; + break; + } + + // Get the device associated with the given session + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); + + Connection *devCon = device->connection; + + // First assume the TCI is a contiguous buffer + // Get the physical address of the given TCI + CWsm_ptr pWsm = device->findContiguousWsm(tci); + if (pWsm == NULL) { + if (tci != NULL && len != 0) { + // Then assume it's a normal buffer that needs to be mapped + mcResult = device->mapBulkBuf(tci, len, &bulkBuf); + if (mcResult != MC_DRV_OK) { + LOG_E("Registering buffer failed. ret=%x", mcResult); + mcResult = MC_DRV_ERR_WSM_NOT_FOUND; + break; + } + handle = bulkBuf->handle; + } else if ( len != 0 ) { + LOG_E("mcOpenSession(): length is more than allocated TCI"); + mcResult = MC_DRV_ERR_TCI_GREATER_THAN_WSM; + break; + } + } else { + if (pWsm->len < len) { + LOG_E("mcOpenSession(): length is more than allocated TCI"); + mcResult = MC_DRV_ERR_TCI_GREATER_THAN_WSM; + break; + } + handle = pWsm->handle; + } + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_OPEN_TRUSTED_APP, + session->deviceId, + *uuid, + (uintptr_t)(tci) & 0xFFF, + (uint32_t)handle, + len); + + // Read command response + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + // TODO-2012-09-06-haenellu: Remove this code once tests can handle it + + if (MC_DRV_ERROR_MAJOR(mcResult) != MC_DRV_ERR_MCP_ERROR) { + LOG_E("Daemon could not open session, responseId %d.", mcResult); + } else { + uint32_t mcpResult = MC_DRV_ERROR_MCP(mcResult); + LOG_E("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)) { + LOG_E("Could not connect to %s", SOCK_PATH); + delete sessionConnection; + // Here we know we couldn't connect to the Daemon. + // Maybe we should use existing connection to close Trustlet. + mcResult = MC_DRV_ERR_SOCKET_CONNECT; + break; + } + + do { + SEND_TO_DAEMON(sessionConnection, MC_DRV_CMD_NQ_CONNECT, + session->deviceId, + session->sessionId, + rspOpenSessionPayload.deviceSessionId, + rspOpenSessionPayload.sessionMagic); + + RECV_FROM_DAEMON(sessionConnection, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("CMD_NQ_CONNECT failed, respId=%d", mcResult); + break; + } + + } while (0); + if (mcResult != MC_DRV_OK) { + delete sessionConnection; + // Here we know we couldn't communicate well with the Daemon. + // Maybe we should use existing connection to close Trustlet. + break; // unlock mutex and return + } + + // there is no payload. + + // Session has been established, new session object must be created + Session *sessionObj = device->createNewSession(session->sessionId, sessionConnection); + // If the session tci was a mapped buffer then register it + if (bulkBuf) + sessionObj->addBulkBuf(bulkBuf); + + LOG_I(" Successfully opened session %d.", session->sessionId); + + } while (false); + + if (mcResult != MC_DRV_OK && bulkBuf) { + delete bulkBuf; + } + +// TODO: enable as soon as there are more error codes +// if (mcResult == MC_DRV_ERR_SOCKET_WRITE || mcResult == MC_DRV_ERR_SOCKET_READ) { +// LOG_E("Connection is dead, removing device."); +// removeDevice(session->deviceId); +// } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcCloseSession(mcSessionHandle_t *session) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + LOG_I("===%s()===", __FUNCTION__); + devMutex.lock(); + do { + CHECK_NOT_NULL(session); + LOG_I(" Closing session %d.", session->sessionId); + + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); + + Connection *devCon = device->connection; + + Session *nqSession = device->resolveSessionId(session->sessionId); + + CHECK_SESSION(nqSession, session->sessionId); + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_CLOSE_SESSION, session->sessionId); + + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("CMD_CLOSE_SESSION failed, respId=%d", mcResult); + // TODO-2012-08-03-haenellu: Remove once tests can handle it. + mcResult = MC_DRV_ERR_UNKNOWN_DEVICE; + break; + } + + bool r = device->removeSession(session->sessionId); + if (!r) + { + LOG_E("removeSession failed"); + assert(0); + } + + + + } while (false); + + if (mcResult == MC_DRV_ERR_SOCKET_WRITE || mcResult == MC_DRV_ERR_SOCKET_READ) { + LOG_E("Connection is dead, removing device."); + removeDevice(session->deviceId); + } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcNotify( + mcSessionHandle_t *session +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + do { + CHECK_NOT_NULL(session); + LOG_I(" Notifying session %d.", session->sessionId); + + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); + + Connection *devCon = device->connection; + + 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); + + if (mcResult == MC_DRV_ERR_SOCKET_WRITE) { + LOG_E("Connection is dead, removing device."); + removeDevice(session->deviceId); + } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcWaitNotification( + mcSessionHandle_t *session, + int32_t timeout +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + // TODO-2012-11-02-gurel: devMutex locking and unlocking had to be commented out + // below. Otherwise, when there are multiple threads in Nwd TLC side, we endup a + // deadlock situation, e.g. one thread waits for notification and another one sends + // notification. + + //devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + do { + CHECK_NOT_NULL(session); + LOG_I(" Waiting for notification of session %d.", session->sessionId); + + Device *device = resolveDeviceId(session->deviceId); + CHECK_DEVICE(device); + + Session *nqSession = device->resolveSessionId(session->sessionId); + CHECK_SESSION(nqSession, session->sessionId); + + Connection *nqconnection = nqSession->notificationConnection; + uint32_t count = 0; + + // Read notification queue till it's empty + for (;;) { + notification_t notification; + ssize_t numRead = nqconnection->readData( + ¬ification, + sizeof(notification_t), + timeout); + //Exit on timeout in first run + //Later runs have timeout set to 0. -2 means, there is no more data. + if (count == 0 && numRead == -2 ) { + LOG_W("Timeout hit at %s", __FUNCTION__); + mcResult = MC_DRV_ERR_TIMEOUT; + break; + } + if (count == 0 && numRead == 0 ) { + LOG_E("Connection is dead, removing device."); + removeDevice(session->deviceId); + mcResult = MC_DRV_ERR_NOTIFICATION; + break; + } + // After first notification the queue will be drained, Thus we set + // no timeout for the following reads + timeout = 0; + + if (numRead != sizeof(notification_t)) { + if (count == 0) { + //failure in first read, notify it + mcResult = MC_DRV_ERR_NOTIFICATION; + LOG_E("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; + } + } + + count++; + LOG_I(" Received notification %d for session %d, payload=%d", + count, notification.sessionId, notification.payload); + + if (notification.payload != 0) { + // Session end point died -> store exit code + nqSession->setErrorInfo(notification.payload); + + mcResult = MC_DRV_INFO_NOTIFICATION; + break; + } + } // for(;;) + + } while (false); + + //devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcMallocWsm( + uint32_t deviceId, + uint32_t align __unused, + uint32_t len, + uint8_t **wsm, + uint32_t wsmFlags __unused) +{ + mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; +#ifndef WIN32 + + LOG_I("===%s(len=%i)===", __FUNCTION__, len); + + devMutex.lock(); + + do { + Device *device = resolveDeviceId(deviceId); + + // Is the device known + // CHECK_DEVICE(device); + + // Is the device opened. + CHECK_DEVICE_CLOSED(device, deviceId) + + CHECK_NOT_NULL(wsm); + + CWsm_ptr pWsm; + mcResult = device->allocateContiguousWsm(len, &pWsm); + if (mcResult != MC_DRV_OK) { + LOG_W(" Allocation of WSM failed"); + break; + } + + *wsm = (uint8_t *)pWsm->virtAddr; + mcResult = MC_DRV_OK; + + } while (false); + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcFreeWsm( + uint32_t deviceId, + uint8_t *wsm +) +{ + mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; +#ifndef WIN32 + + Device *device; + + devMutex.lock(); + + LOG_I("===%s(%p)===", __FUNCTION__, wsm); + + do { + + // Get the device associated wit the given session + device = resolveDeviceId(deviceId); + + // Is the device known + CHECK_DEVICE(device); + + // Is the device opened. + CHECK_DEVICE_CLOSED(device, deviceId) + + // find WSM object + CWsm_ptr pWsm = device->findContiguousWsm(wsm); + if (pWsm == NULL) { + LOG_E("address is unknown to mcFreeWsm"); + mcResult = MC_DRV_ERR_WSM_NOT_FOUND; + break; + } + + // Free the given virtual address + mcResult = device->freeContiguousWsm(pWsm); + if (mcResult != MC_DRV_OK) { + LOG_E("Free of virtual address failed"); + break; + } + mcResult = MC_DRV_OK; + + } while (false); + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcMap( + mcSessionHandle_t *sessionHandle, + void *buf, + uint32_t bufLen, + mcBulkMap_t *mapInfo +) +{ + mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; +#ifndef WIN32 + + static CMutex mutex; + + LOG_I("===%s()===", __FUNCTION__); + + 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); + // Is the device known + CHECK_DEVICE(device); + + // Is the device opened. + CHECK_DEVICE_CLOSED(device, sessionHandle->deviceId) + + Connection *devCon = device->connection; + + // Get session + Session *session = device->resolveSessionId(sessionHandle->sessionId); + CHECK_SESSION(session, sessionHandle->sessionId); + + 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; + mcResult = session->addBulkBuf(buf, bufLen, &bulkBuf); + if (mcResult != MC_DRV_OK) { + LOG_E("Registering buffer failed. ret=%x", mcResult); + break; + } + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_MAP_BULK_BUF, + session->sessionId, + (uint32_t)bulkBuf->handle, + (uint32_t)0, + (uintptr_t)(bulkBuf->virtAddr) & 0xFFF, + bulkBuf->len); + + // Read command response + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("CMD_MAP_BULK_BUF failed, respId=%d", mcResult); + // TODO-2012-09-06-haenellu: Remove once tests can handle it. + 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) != MC_DRV_OK) { + // Removing of bulk buffer not possible + LOG_E("Unregistering of bulk memory from Kernel Module failed"); + } + break; + } + + mcDrvRspMapBulkMemPayload_t rspMapBulkMemPayload; + RECV_FROM_DAEMON(devCon, &rspMapBulkMemPayload); + + // Set mapping info for internal structures + bulkBuf->sVirtualAddr = (void *)(uintptr_t)rspMapBulkMemPayload.secureVirtualAdr; + // Set mapping info for Trustlet + mapInfo->sVirtualAddr = bulkBuf->sVirtualAddr; + mapInfo->sVirtualLen = bufLen; + mcResult = MC_DRV_OK; + + } while (false); + +// // TODO: enable as soon as there are more error codes +// if (mcResult == MC_DRV_ERR_SOCKET_WRITE || mcResult == MC_DRV_ERR_SOCKET_READ) { +// LOG_E("Connection is dead, removing device."); +// removeDevice(sessionHandle->deviceId); +// } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcUnmap( + mcSessionHandle_t *sessionHandle, + void *buf, + mcBulkMap_t *mapInfo +) +{ + mcResult_t mcResult = MC_DRV_ERR_UNKNOWN; +#ifndef WIN32 + + static CMutex mutex; + + LOG_I("===%s()===", __FUNCTION__); + + devMutex.lock(); + + do { + CHECK_NOT_NULL(sessionHandle); + CHECK_NOT_NULL(mapInfo); + CHECK_NOT_NULL(mapInfo->sVirtualAddr); + CHECK_NOT_NULL(buf); + + // Determine device the session belongs to + Device *device = resolveDeviceId(sessionHandle->deviceId); + // Is the device known + CHECK_DEVICE(device); + + // Is the device opened. + CHECK_DEVICE_CLOSED(device, sessionHandle->deviceId) + + Connection *devCon = device->connection; + + // Get session + Session *session = device->resolveSessionId(sessionHandle->sessionId); + CHECK_SESSION(session, sessionHandle->sessionId); + + uint32_t handle = session->getBufHandle(mapInfo->sVirtualAddr, mapInfo->sVirtualLen); + if (handle == 0) { + LOG_E("Unable to find internal handle for buffer %p.", mapInfo->sVirtualAddr); + mcResult = MC_DRV_ERR_BLK_BUFF_NOT_FOUND; + break; + } + + LOG_I(" Unmapping %p(handle=%u) from session %d.", buf, handle, sessionHandle->sessionId); + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_UNMAP_BULK_BUF, + session->sessionId, + handle, + (uintptr_t)(mapInfo->sVirtualAddr), + mapInfo->sVirtualLen); + + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("Daemon reported failing of UNMAP BULK BUF command, responseId %d.", mcResult); + // TODO-2012-09-06-haenellu: Remove once tests can handle it. + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; + break; + } + + // Unregister mapped bulk buffer from Kernel Module and remove mapped + // bulk buffer from session maintenance + mcResult = session->removeBulkBuf(buf); + if (mcResult != MC_DRV_OK) { + LOG_E("Unregistering of bulk memory from Kernel Module failed."); + break; + } + + mcResult = MC_DRV_OK; + + } while (false); + + if (mcResult == MC_DRV_ERR_SOCKET_WRITE || mcResult == MC_DRV_ERR_SOCKET_READ) { + LOG_E("Connection is dead, removing device."); + removeDevice(sessionHandle->deviceId); + } + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcGetSessionErrorCode( + mcSessionHandle_t *session, + int32_t *lastErr +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + do { + CHECK_NOT_NULL(session); + CHECK_NOT_NULL(lastErr); + + // Get device + Device *device = resolveDeviceId(session->deviceId); + // Is the device known + CHECK_DEVICE(device); + + // Is the device opened. + CHECK_DEVICE_CLOSED(device, session->deviceId) + + // Get session + Session *nqsession = device->resolveSessionId(session->sessionId); + CHECK_SESSION(nqsession, session->sessionId); + + // get session error code from session + *lastErr = nqsession->getLastErr(); + + } while (false); + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcDriverCtrl( + mcDriverCtrl_t param __unused, + uint8_t *data __unused, + uint32_t len __unused +) +{ +#ifndef WIN32 + + LOG_W("mcDriverCtrl(): not implemented"); + +#endif /* WIN32 */ + return MC_DRV_ERR_NOT_IMPLEMENTED; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcGetMobiCoreVersion( + uint32_t deviceId, + mcVersionInfo_t *versionInfo +) +{ + mcResult_t mcResult = MC_DRV_OK; +#ifndef WIN32 + + devMutex.lock(); + LOG_I("===%s()===", __FUNCTION__); + + do { + Device *device = resolveDeviceId(deviceId); + + // Is the device known + CHECK_DEVICE(device); + + // Is the device opened. + CHECK_DEVICE_CLOSED(device, deviceId) + + CHECK_NOT_NULL(versionInfo); + + Connection *devCon = device->connection; + + SEND_TO_DAEMON(devCon, MC_DRV_CMD_GET_MOBICORE_VERSION); + + // Read GET MOBICORE VERSION response. + + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("MC_DRV_CMD_GET_MOBICORE_VERSION bad response, respId=%d", mcResult); + // TODO-2012-09-06-haenellu: Remove once tests can handle it. + mcResult = MC_DRV_ERR_DAEMON_UNREACHABLE; + break; + } + + // Read payload. + mcVersionInfo_t versionInfo_socket; + RECV_FROM_DAEMON(devCon, &versionInfo_socket); + + *versionInfo = versionInfo_socket; + + } while (0); + + devMutex.unlock(); + +#endif /* WIN32 */ + return mcResult; +} + +#ifndef WIN32 +//------------------------------------------------------------------------------ +// Only called by mcOpenDevice() +// Must be taken with devMutex locked. +uint32_t getDaemonVersion(Connection *devCon, uint32_t *version) +{ + assert(devCon != NULL); + assert(version != NULL); + mcResult_t mcResult = MC_DRV_OK; + uint32_t v = 0; + + LOG_I("===%s()===", __FUNCTION__); + + do { + SEND_TO_DAEMON(devCon, MC_DRV_CMD_GET_VERSION); + + RECV_FROM_DAEMON(devCon, &mcResult); + + if (mcResult != MC_DRV_OK) { + LOG_E("MC_DRV_CMD_GET_VERSION bad response, respId=%d", mcResult); + // version is still 0, we don't further analyze response here. + break; + } + + RECV_FROM_DAEMON(devCon, &v); + + } while (0); + + if (mcResult == MC_DRV_OK) { + *version = v; + } + + return mcResult; +} +#endif /* WIN32 */ + +/** @} */ diff --git a/mobicore/daemon/ClientLib/Device.cpp b/mobicore/daemon/ClientLib/Device.cpp new file mode 100644 index 0000000..2141f99 --- /dev/null +++ b/mobicore/daemon/ClientLib/Device.cpp @@ -0,0 +1,264 @@ +/** @addtogroup MCD_IMPL_LIB + * @{ + * @file + * + * Client library device management. + * + * Device and Trustlet Session management Funtions. + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include +#include + +#include "mc_linux.h" +#include "Device.h" + +#include "log.h" +#include + + +//------------------------------------------------------------------------------ +Device::Device(uint32_t deviceId, Connection *connection) +{ + this->deviceId = deviceId; + this->connection = connection; + + pMcKMod = new CMcKMod(); +} + + +//------------------------------------------------------------------------------ +Device::~Device(void) +{ + /* Delete all session objects. Usually this should not be needed as closeDevice() + * requires that all sessions have been closed before. + */ + sessionIterator_t sessionIterator = sessionList.begin(); + while (sessionIterator != sessionList.end()) { + delete (*sessionIterator); + sessionIterator = sessionList.erase(sessionIterator); + } + + // Free all allocated WSM descriptors + wsmIterator_t wsmIterator = wsmL2List.begin(); + while (wsmIterator != wsmL2List.end()) { + CWsm_ptr pWsm = *wsmIterator; + + // ignore return code + pMcKMod->free(pWsm->handle, pWsm->virtAddr, pWsm->len); + + delete (*wsmIterator); + wsmIterator = wsmL2List.erase(wsmIterator); + } + delete connection; + delete pMcKMod; +} + + +//------------------------------------------------------------------------------ +bool Device::open(const char *deviceName) +{ + return pMcKMod->open(deviceName); +} + + +//------------------------------------------------------------------------------ +void Device::close(void) +{ + pMcKMod->close(); +} + + +//------------------------------------------------------------------------------ +bool Device::hasSessions(void) +{ + return sessionList.size() > 0; +} + + +//------------------------------------------------------------------------------ +Session *Device::createNewSession(uint32_t sessionId, Connection *connection) +{ + Session *session = new Session(sessionId, pMcKMod, connection); + sessionList.push_back(session); + return session; +} + + +//------------------------------------------------------------------------------ +bool Device::removeSession(uint32_t sessionId) +{ + bool ret = false; + + sessionIterator_t interator = sessionList.begin(); + while (interator != sessionList.end()) { + if ((*interator)->sessionId == sessionId) { + delete (*interator); + interator = sessionList.erase(interator); + ret = true; + break; + } else { + interator++; + } + } + return ret; +} + + +//------------------------------------------------------------------------------ +Session *Device::resolveSessionId(uint32_t sessionId) +{ + Session *ret = NULL; + + // Get Session for sessionId + for ( sessionIterator_t interator = sessionList.begin(); + interator != sessionList.end(); + ++interator) { + if ((*interator)->sessionId == sessionId) { + ret = (*interator); + break; + } + } + return ret; +} + + +//------------------------------------------------------------------------------ +mcResult_t Device::allocateContiguousWsm(uint32_t len, CWsm **wsm) +{ + // Allocate shared memory + addr_t virtAddr; + uint32_t handle; + uint64_t physAddr; + mcResult_t ret; + + assert(wsm != NULL); + + if (!len) { + return MC_DRV_ERR_INVALID_LENGTH; + } + + ret = pMcKMod->mapWsm(len, &handle, &virtAddr, &physAddr); + if (ret) { + return ret; + } + + LOG_I(" mapped handle %d to %p, phys=%#llx ", handle, virtAddr, physAddr); + + // Register (vaddr,paddr) with device + *wsm = new CWsm(virtAddr, len, handle, physAddr); + + wsmL2List.push_back(*wsm); + + // Return pointer to the allocated memory + return MC_DRV_OK; +} + + +//------------------------------------------------------------------------------ +mcResult_t Device::freeContiguousWsm(CWsm_ptr pWsm) +{ + mcResult_t ret = MC_DRV_ERR_WSM_NOT_FOUND; + wsmIterator_t iterator; + + for (iterator = wsmL2List.begin(); iterator != wsmL2List.end(); ++iterator) { + if (pWsm == *iterator) { + ret = MC_DRV_OK; + break; + } + } + // We just looked this up using findContiguousWsm + assert(ret == MC_DRV_OK); + + LOG_I(" unmapping handle %d from %p, phys=%#llx", + pWsm->handle, pWsm->virtAddr, pWsm->physAddr); + + ret = pMcKMod->free(pWsm->handle, pWsm->virtAddr, pWsm->len); + if (ret != MC_DRV_OK) { + // developer forgot to free all references of this memory, we do not remove the reference here + return ret; + } + + iterator = wsmL2List.erase(iterator); + delete pWsm; + + return ret; +} + + +//------------------------------------------------------------------------------ +CWsm_ptr Device::findContiguousWsm(addr_t virtAddr) +{ + CWsm_ptr pWsm = NULL; + + if (virtAddr == NULL) { + return pWsm; + } + + for ( wsmIterator_t iterator = wsmL2List.begin(); + iterator != wsmL2List.end(); + ++iterator) { + CWsm_ptr pTmpWsm = *iterator; + if (virtAddr == pTmpWsm->virtAddr) { + pWsm = pTmpWsm; + break; + } + } + + return pWsm; +} + + +//------------------------------------------------------------------------------ +mcResult_t Device::mapBulkBuf(addr_t buf, uint32_t len, BulkBufferDescriptor **blkBuf) +{ + uint64_t PhysWsmL2; + uint32_t handle; + + *blkBuf = NULL; + + // Prepare the interface structure for memory registration in Kernel Module + mcResult_t ret = pMcKMod->registerWsmL2(buf, len, 0, &handle, &PhysWsmL2); + if (ret != MC_DRV_OK) { + LOG_V(" mcKMod->registerWsmL2() failed with %x", ret); + return ret; + } + + LOG_V(" addBulkBuf - Handle of L2 Table = %u", handle); + + // Create new descriptor - secure virtual virtual set to 0, unknown! + *blkBuf = new BulkBufferDescriptor(buf, 0x0, len, handle); + + return MC_DRV_OK; +} + +/** @} */ diff --git a/mobicore/daemon/ClientLib/Device.h b/mobicore/daemon/ClientLib/Device.h new file mode 100644 index 0000000..767f20e --- /dev/null +++ b/mobicore/daemon/ClientLib/Device.h @@ -0,0 +1,173 @@ +/** @addtogroup MCD_IMPL_LIB + * @{ + * @file + * + * Client library device management. + * + * Device and Trustlet Session management Functions. + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 DEVICE_H_ +#define DEVICE_H_ + +#include +#include + +#include "public/MobiCoreDriverApi.h" +#include "Session.h" +#include "CWsm.h" + + +class Device +{ + +private: + sessionList_t sessionList; /**< MobiCore Trustlet session associated with the device */ + wsmList_t wsmL2List; /**< WSM L2 Table */ + + +public: + uint32_t deviceId; /**< Device identifier */ + Connection *connection; /**< The device connection */ + CMcKMod_ptr pMcKMod; + + Device( + uint32_t deviceId, + Connection *connection + ); + + virtual ~Device( + void + ); + + /** + * Open the device. + * @param deviceName Name of the kernel modules device file. + * @return true if the device has been opened successfully + */ + bool open( + const char *deviceName + ); + + /** + * Closes the device. + */ + void close( + void + ); + + /** + * Check if the device has open sessions. + * @return true if the device has one or more open sessions. + */ + bool hasSessions( + void + ); + + /** + * Add a session to the device. + * @param sessionId session ID + * @param connection session connection + * @return Session object created + */ + Session *createNewSession( + uint32_t sessionId, + Connection *connection + ); + + /** + * Remove the specified session from the device. + * The session object will be destroyed and all resources associated with it will be freed. + * + * @param sessionId Session of the session to remove. + * @return true if a session has been found and removed. + */ + bool removeSession( + uint32_t sessionId + ); + + /** + * Get as session object for a given session ID. + * @param sessionId Identified of a previously opened session. + * @return Session object if available or NULL if no session has been found. + */ + Session *resolveSessionId( + uint32_t sessionId + ); + + /** + * Allocate a block of contiguous WSM. + * @param len The virtual address to be registered. + * @param wsm The CWsm object of the allocated memory. + * @return MC_DRV_OK if successful. + */ + mcResult_t allocateContiguousWsm( + uint32_t len, + CWsm **wsm + ); + + /** + * Unregister a vaddr from a device. + * @param vaddr The virtual address to be registered. + * @param paddr The physical address to be registered. + */ + mcResult_t freeContiguousWsm( + CWsm_ptr pWsm + ); + + /** + * Get a WSM object for a given virtual address. + * @param vaddr The virtual address which has been allocate with mcMallocWsm() in advance. + * @return the WSM object or NULL if no address has been found. + */ + CWsm_ptr findContiguousWsm( + addr_t virtAddr + ); + + /** + * Map a buffer from tlc VA to TL(Create L2 table for the buffer + * @param buf The virtual address of hte buffer + * @param len The length of the buffer + * @param blkBuf The buffer object created + * @return MC_DRV_OK if successful. + */ + mcResult_t mapBulkBuf( + addr_t buf, + uint32_t len, + BulkBufferDescriptor **blkBuf + ); + +}; + +#endif /* DEVICE_H_ */ + +/** @} */ diff --git a/mobicore/daemon/ClientLib/GP/tee_client_api.cpp b/mobicore/daemon/ClientLib/GP/tee_client_api.cpp new file mode 100644 index 0000000..bfef92a --- /dev/null +++ b/mobicore/daemon/ClientLib/GP/tee_client_api.cpp @@ -0,0 +1,835 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#undef LOG_TAG +#define LOG_TAG "GpClient" +#include "tee_client_api.h" +#include "log.h" +#include "MobiCoreDriverApi.h" +#include "Mci/mcinq.h" +#include +#include "GpTci.h" +#include +#include + +//------------------------------------------------------------------------------ +// Macros +#define _TEEC_GET_PARAM_TYPE(t, i) (((t) >> (4*i)) & 0xF) + +// Max. session number +#define _TEEC_SESSION_NUMBER 50 + +//Parameter number +#define _TEEC_PARAMETER_NUMBER 4 + + +//------------------------------------------------------------------------------ +//Local satic functions +static void _libUuidToArray( + const TEEC_UUID *uuid, + uint8_t *uuid_str); + + +static TEEC_Result _TEEC_UnwindOperation( + _TEEC_TCI *tci, + mcSessionHandle_t *handle, + TEEC_Operation *operation, + bool copyValues, + uint32_t *returnOrigin); + +static TEEC_Result _TEEC_SetupOperation( + _TEEC_TCI *tci, + mcSessionHandle_t *handle, + TEEC_Operation *operation, + uint32_t *returnOrigin); + +static TEEC_Result _TEEC_CallTA( + TEEC_Session *session, + TEEC_Operation *operation, + uint32_t *returnOrigin); + +//------------------------------------------------------------------------------ +static void _libUuidToArray( + const TEEC_UUID *uuid, + uint8_t *uuidArr) +{ + uint8_t *pIdentifierCursor = (uint8_t *)uuid; + /* offsets and syntax constants. See explanations above */ +#ifdef S_BIG_ENDIAN + uint32_t offsets = 0; +#else + uint32_t offsets = 0xF1F1DF13; +#endif + uint32_t i; + + for (i = 0; i < sizeof(TEEC_UUID); i++) { + /* Two-digit hex number */ + uint8_t number; + int32_t offset = ((int32_t)((offsets & 0xF) << 28)) >> 28; + number = pIdentifierCursor[offset]; + offsets >>= 4; + pIdentifierCursor++; + + uuidArr[i] = number; + } +} + +//------------------------------------------------------------------------------ +static TEEC_Result _TEEC_SetupOperation( + _TEEC_TCI *tci, + mcSessionHandle_t *handle, + TEEC_Operation *operation, + uint32_t *returnOrigin) +{ + uint32_t i; + _TEEC_ParameterInternal *imp; + TEEC_Parameter *ext; + mcResult_t mcRet = MC_DRV_OK; + TEEC_Result teecResult = TEEC_SUCCESS; + + //operation can be NULL + tci->operation.isCancelled = false; + if (operation != NULL) { + LOG_I(" %s()", __func__); + + tci->operation.paramTypes = operation->paramTypes; + operation->started = 1; + + //TODO: This design allows a non-NULL buffer with a size of 0 bytes to allow trivial integration with any + //implementations of the C library malloc, in which is valid to allocate a zero byte buffer and receive a non- + //NULL pointer which may not be de-referenced in return. + + + for (i = 0; i < _TEEC_PARAMETER_NUMBER; i++) { + imp = &tci->operation.params[i]; + ext = &operation->params[i]; + + switch (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i)) { + case TEEC_VALUE_OUTPUT: + break; + case TEEC_NONE: + LOG_I(" cycle %d, TEEC_NONE", i); + break; + case TEEC_VALUE_INPUT: + case TEEC_VALUE_INOUT: { + LOG_I(" cycle %d, TEEC_VALUE_IN*", i); + imp->value.a = ext->value.a; + imp->value.b = ext->value.b; + break; + } + case TEEC_MEMREF_TEMP_INPUT: + case TEEC_MEMREF_TEMP_OUTPUT: + case TEEC_MEMREF_TEMP_INOUT: { + //TODO: A Temporary Memory Reference may be null, which can be used to denote a special case for the + //parameter. Output Memory References that are null are typically used to request the required output size. + LOG_I(" cycle %d, TEEC_TEMP_IN*", i); + imp->memref.mapInfo.sVirtualLen = 0; + if ((ext->tmpref.size) && (ext->tmpref.buffer)) { + mcRet = mcMap(handle, ext->tmpref.buffer, ext->tmpref.size, &imp->memref.mapInfo); + if (mcRet != MC_DRV_OK) { + LOG_E("mcMap failed, mcRet=0x%08X", mcRet); + *returnOrigin = TEEC_ORIGIN_COMMS; + i = _TEEC_PARAMETER_NUMBER; + } + } else { + LOG_I(" cycle %d, TEEC_TEMP_IN* - zero pointer or size", i); + } + break; + } + case TEEC_MEMREF_WHOLE: { + LOG_I(" cycle %d, TEEC_MEMREF_WHOLE", i); + imp->memref.mapInfo.sVirtualLen = 0; + if (ext->memref.parent->size) { + mcRet = mcMap(handle, ext->memref.parent->buffer, ext->memref.parent->size, &imp->memref.mapInfo); + if (mcRet != MC_DRV_OK) { + LOG_E("mcMap failed, mcRet=0x%08X", mcRet); + *returnOrigin = TEEC_ORIGIN_COMMS; + i = _TEEC_PARAMETER_NUMBER; + } + } + break; + } + case TEEC_MEMREF_PARTIAL_INPUT: + case TEEC_MEMREF_PARTIAL_OUTPUT: + case TEEC_MEMREF_PARTIAL_INOUT: { + LOG_I(" cycle %d, TEEC_PARTIAL_IN*", i); + //Check data flow consistency + if ((((ext->memref.parent->flags & (TEEC_MEM_INPUT | TEEC_MEM_OUTPUT)) == TEEC_MEM_INPUT) && + (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i) == TEEC_MEMREF_PARTIAL_OUTPUT)) || + (((ext->memref.parent->flags & (TEEC_MEM_INPUT | TEEC_MEM_OUTPUT)) == TEEC_MEM_OUTPUT) && + (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i) == TEEC_MEMREF_PARTIAL_INPUT))) { + LOG_E("PARTIAL data flow inconsistency"); + *returnOrigin = TEEC_ORIGIN_API; + teecResult = TEEC_ERROR_BAD_PARAMETERS; + i = _TEEC_PARAMETER_NUMBER; + break; + } + + if (ext->memref.offset + ext->memref.size > ext->memref.parent->size) { + LOG_E("PARTIAL offset/size error"); + *returnOrigin = TEEC_ORIGIN_API; + teecResult = TEEC_ERROR_BAD_PARAMETERS; + i = _TEEC_PARAMETER_NUMBER; + break; + } + imp->memref.mapInfo.sVirtualLen = 0; + if (ext->memref.size) { + mcRet = mcMap(handle, (uint8_t *)ext->memref.parent->buffer + ext->memref.offset, ext->memref.size, &imp->memref.mapInfo); + if (mcRet != MC_DRV_OK) { + LOG_E("mcMap failed, mcRet=0x%08X", mcRet); + *returnOrigin = TEEC_ORIGIN_COMMS; + i = _TEEC_PARAMETER_NUMBER; + } + } + break; + } + default: + LOG_E("cycle %d, default", i); + *returnOrigin = TEEC_ORIGIN_API; + teecResult = TEEC_ERROR_BAD_PARAMETERS; + i = _TEEC_PARAMETER_NUMBER; + break; + } + } + + if (tci->operation.isCancelled) { + LOG_E("the operation has been cancelled in COMMS"); + *returnOrigin = TEEC_ORIGIN_COMMS; + teecResult = TEEC_ERROR_CANCEL; + } + + if ((mcRet != MC_DRV_OK) || (teecResult != TEEC_SUCCESS)) { + uint32_t retOrigIgnored; + _TEEC_UnwindOperation(tci, handle, operation, false, &retOrigIgnored); + //Zeroing out tci->operation + memset(&tci->operation, 0, sizeof(TEEC_Operation)); + if (teecResult != TEEC_SUCCESS) return teecResult; + return TEEC_ERROR_GENERIC; + } + } + + //Copy version indicator field + strcpy(tci->header, "TCIGP000"); + + // Fill in invalid values for secure world to overwrite + tci->returnStatus = 0; + tci->returnStatus = TEE_ERROR_BAD_STATE; + + // Signal completion of request writing + tci->ready = 1; + + return teecResult; +} + +//------------------------------------------------------------------------------ +static TEEC_Result _TEEC_UnwindOperation( + _TEEC_TCI *tci, + mcSessionHandle_t *handle, + TEEC_Operation *operation, + bool copyValues, + uint32_t *returnOrigin) +{ + uint32_t i; + _TEEC_ParameterInternal *imp; + TEEC_Parameter *ext; + //mcResult_t mcRet = MC_DRV_OK; + //bool doUnmap = false; + uint8_t *buffer; + + //operation can be NULL + if (operation == NULL) return TEEC_SUCCESS; + + LOG_I(" %s()", __func__); + + operation->started = 2; + + // Some sanity checks + if (tci->returnOrigin == 0 || + ((tci->returnOrigin != TEEC_ORIGIN_TRUSTED_APP) && (tci->returnStatus != TEEC_SUCCESS))) { + *returnOrigin = TEEC_ORIGIN_COMMS; + return TEEC_ERROR_COMMUNICATION; + } + *returnOrigin = tci->returnOrigin; + + //Clear sVirtualLen to unMap further + for (i = 0; i < _TEEC_PARAMETER_NUMBER; i++) { + imp = &tci->operation.params[i]; + ext = &operation->params[i]; + buffer = NULL; + + switch (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i)) { + case TEEC_VALUE_INPUT: + LOG_I(" cycle %d, TEEC_VALUE_INPUT", i); + break; + case TEEC_NONE: + LOG_I(" cycle %d, TEEC_NONE", i); + break; + case TEEC_VALUE_OUTPUT: + case TEEC_VALUE_INOUT: { + LOG_I(" cycle %d, TEEC_VALUE_OUT*", i); + if (copyValues) { + ext->value.a = imp->value.a; + ext->value.b = imp->value.b; + } + break; + } + case TEEC_MEMREF_TEMP_OUTPUT: + case TEEC_MEMREF_TEMP_INPUT: + case TEEC_MEMREF_TEMP_INOUT: { + LOG_I(" cycle %d, TEEC_TEMP*", i); + if ((copyValues) && (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i) != TEEC_MEMREF_TEMP_INPUT)) { + ext->tmpref.size = imp->memref.outputSize; + } + //doUnmap = true; + buffer = (uint8_t *)ext->tmpref.buffer; + break; + } + case TEEC_MEMREF_WHOLE: { + LOG_I(" cycle %d, TEEC_MEMREF_WHOLE", i); + if (copyValues) ext->memref.size = imp->memref.outputSize; + //doUnmap = true; + buffer = (uint8_t *)ext->memref.parent->buffer; + break; + } + + case TEEC_MEMREF_PARTIAL_OUTPUT: + case TEEC_MEMREF_PARTIAL_INOUT: + case TEEC_MEMREF_PARTIAL_INPUT: { + LOG_I(" cycle %d, TEEC_MEMREF_PARTIAL*", i); + if ((copyValues) && (_TEEC_GET_PARAM_TYPE(operation->paramTypes, i) != TEEC_MEMREF_PARTIAL_INPUT)) { + ext->memref.size = imp->memref.outputSize; + } + buffer = (uint8_t *)ext->memref.parent->buffer + ext->memref.offset; + break; + } + default: + LOG_E("cycle %d, bad parameter", i); + break; + } + + if ((buffer != NULL) && (imp->memref.mapInfo.sVirtualLen != 0)) { + // This function assumes that we cannot handle error of mcUnmap + mcUnmap(handle, buffer, &imp->memref.mapInfo); + } + } + + return tci->returnStatus; +} + +//------------------------------------------------------------------------------ +//TEEC_InitializeContext: TEEC_SUCCESS, Another error code from Table 4-2. +//MC_DRV_OK, MC_DRV_ERR_INVALID_OPERATION, MC_DRV_ERR_DAEMON_UNREACHABLE, MC_DRV_ERR_UNKNOWN_DEVICE, MC_DRV_ERR_INVALID_DEVICE_FILE +TEEC_Result TEEC_InitializeContext( + const char *name __unused, + TEEC_Context *context) +{ + LOG_I("== %s() ==============", __func__); + + if (context == NULL) return TEEC_ERROR_BAD_PARAMETERS; + context->imp.reserved = MC_DEVICE_ID_DEFAULT; + + switch (mcOpenDevice(MC_DEVICE_ID_DEFAULT)) { + case MC_DRV_OK: + return TEEC_SUCCESS; + case MC_DRV_ERR_INVALID_OPERATION: + return TEEC_ERROR_BAD_STATE; + case MC_DRV_ERR_DAEMON_UNREACHABLE: + return TEEC_ERROR_COMMUNICATION; + case MC_DRV_ERR_UNKNOWN_DEVICE: + return TEEC_ERROR_BAD_PARAMETERS; + case MC_DRV_ERR_INVALID_DEVICE_FILE: + return TEEC_ERROR_COMMUNICATION; + } + + return TEEC_ERROR_GENERIC; +} + +//------------------------------------------------------------------------------ +//mcCloseDevice: MC_DRV_OK, MC_DRV_ERR_UNKNOWN_DEVICE, MC_DRV_ERR_SESSION_PENDING, MC_DRV_ERR_DAEMON_UNREACHABLE +//TEEC_FinalizeContext: void + +//TODO: The implementation of this function MUST NOT be able to fail: after this function returns the Client +//Application must be able to consider that the Context has been closed. + +void TEEC_FinalizeContext(TEEC_Context *context) +{ + mcResult_t mcRet; + + LOG_I("== %s() ==============", __func__); + + //The parameter context MUST point to an initialized TEE Context. + //Just realized: The function implementation MUST do nothing if context is NULL. + if (context == NULL) { + LOG_E("context is NULL"); + return; + } + + //The implementation of this function MUST NOT be able to fail: after this function returns the Client + //Application must be able to consider that the Context has been closed. + mcRet = mcCloseDevice(context->imp.reserved); + if (mcRet != MC_DRV_OK) { + LOG_E("mcCloseDevice failed (%08x)", mcRet); + /* continue even in case of error */; + } +} + +//------------------------------------------------------------------------------ +static TEEC_Result _TEEC_CallTA( + TEEC_Session *session, + TEEC_Operation *operation, + uint32_t *returnOrigin) +{ + mcResult_t mcRet; + TEEC_Result teecRes; + TEEC_Result teecError = TEEC_SUCCESS; + + LOG_I(" %s()", __func__); + + // Phase 1: start the operation and wait for the result + teecRes = _TEEC_SetupOperation((_TEEC_TCI *)session->imp.tci, &session->imp.handle, operation, returnOrigin); + if (teecRes != TEEC_SUCCESS ) { + LOG_E("_TEEC_SetupOperation failed (%08x)", teecRes); + return teecRes; + } + + // Signal the Trusted App + mcRet = mcNotify(&session->imp.handle); + if (MC_DRV_OK != mcRet) { + LOG_E("Notify failed (%08x)", mcRet); + teecError = TEEC_ERROR_COMMUNICATION; + goto end; + } + + // ------------------------------------------------------------- + // Wait for the Trusted App response + mcRet = mcWaitNotification(&session->imp.handle, MC_INFINITE_TIMEOUT); + if (mcRet != MC_DRV_OK) { + LOG_E("mcWaitNotification failed (%08x)", mcRet); + teecError = TEEC_ERROR_COMMUNICATION; + if (mcRet == MC_DRV_INFO_NOTIFICATION) { + int32_t lastErr; + mcGetSessionErrorCode(&session->imp.handle, &lastErr); + LOG_E("mcGetSessionErrorCode returned %d", lastErr); + if (lastErr == TA_EXIT_CODE_FINISHED) { + // We may get here if the TA_OpenSessionEntryPoint returns an error and TA goes fast through DestroyEntryPoint and exits the TA. + teecError = TEEC_SUCCESS; + } else if (lastErr != ERR_INVALID_SID && lastErr != ERR_SID_NOT_ACTIVE) { + LOG_E("Target is DEAD"); + + *returnOrigin = TEEC_ORIGIN_TEE; + teecError = TEE_ERROR_TARGET_DEAD; + } + } + } + // Phase 2: Return values and cleanup +end: + // unmap memory and copy values if no error + teecRes = _TEEC_UnwindOperation((_TEEC_TCI *)session->imp.tci, &session->imp.handle, operation, + (teecError == TEEC_SUCCESS), returnOrigin); + if (teecRes != TEEC_SUCCESS ) { + LOG_E("_TEEC_UnwindOperation (%08x)", teecRes); + /* continue even in case of error */; + } + + // Cleanup + if (teecError != TEEC_SUCCESS) { + // Previous interactions failed, either TA is dead or communication error + mcRet = mcCloseSession(&session->imp.handle); + if (mcRet != MC_DRV_OK) { + LOG_E("mcCloseSession failed (%08x)", mcRet); + /* continue even in case of error */; + } + session->imp.active = false; + if (teecError == TEEC_ERROR_COMMUNICATION) { + *returnOrigin = TEEC_ORIGIN_COMMS; + } + munmap(session->imp.tci, sysconf(_SC_PAGESIZE)); + session->imp.tci = NULL; + } + return teecError; +} + +//------------------------------------------------------------------------------ +__MC_CLIENT_LIB_API mcResult_t mcOpenGPTA( + mcSessionHandle_t *session, + const mcUuid_t *uuid, + uint8_t *tci, + uint32_t len +); +//------------------------------------------------------------------------------ +//TEEC_OpenSession: if the returnOrigin is different from TEEC_ORIGIN_TRUSTED_APP, an error code from Table 4-2 +// If the returnOrigin is equal to TEEC_ORIGIN_TRUSTED_APP, a return code defined by the +//protocol between the Client Application and the Trusted Application. +TEEC_Result TEEC_OpenSession ( + TEEC_Context *context, + TEEC_Session *session, + const TEEC_UUID *destination, + uint32_t connectionMethod, + void *connectionData __unused, + TEEC_Operation *operation, + uint32_t *returnOrigin) +{ + mcResult_t mcRet; + TEEC_Result teecRes; + uint32_t returnOrigin_local; + mcUuid_t tauuid; + + LOG_I("== %s() ==============", __func__); + // ------------------------------------------------------------- + //The parameter context MUST point to an initialized TEE Context. + if (context == NULL) { + LOG_E("context is NULL"); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_API; + return TEEC_ERROR_BAD_PARAMETERS; + } + + if (session == NULL) { + LOG_E("session is NULL"); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_API; + return TEEC_ERROR_BAD_PARAMETERS; + } + + if (connectionMethod != TEEC_LOGIN_PUBLIC) { + //JACKET: Client authorization is not supported. The connectionMethod parameter + //must be TEEC LOGIN PUBLIC, otherwise return TEEC ERROR NOT IMPLEMENTED. + LOG_E("connectionMethod != TEEC_LOGIN_PUBLIC"); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_API; + return TEEC_ERROR_NOT_IMPLEMENTED; + } + + // ------------------------------------------------------------- + session->imp.active = false; + + _libUuidToArray((TEEC_UUID *)destination, (uint8_t *)tauuid.value); + + if (operation) operation->imp.session = &session->imp; + + //Allocate a 4kB page with mmap, zero it out, and set session->imp.tci to its address. + session->imp.tci = NULL; + void *bulkBuf = (void *)mmap(0, sysconf(_SC_PAGESIZE), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (bulkBuf == MAP_FAILED) { + LOG_E("mmap filed on tci buffer allocation"); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_API; + return TEEC_ERROR_OUT_OF_MEMORY; + } + + session->imp.tci = bulkBuf; + memset(session->imp.tci, 0, sysconf(_SC_PAGESIZE)); + + pthread_mutex_init(&session->imp.mutex_tci, NULL); + pthread_mutex_lock(&session->imp.mutex_tci); + + //Fill the TCI buffer session.tci with the destination UUID. + memcpy(&(((_TEEC_TCI *)session->imp.tci)->destination), destination, sizeof(TEEC_UUID)); + // ------------------------------------------------------------- + memset(&session->imp.handle, 0, sizeof(mcSessionHandle_t)); + session->imp.handle.deviceId = context->imp.reserved ; // The device ID (default device is used) + mcRet = mcOpenGPTA( + &session->imp.handle, + &tauuid, + (uint8_t *)session->imp.tci, + sizeof(_TEEC_TCI)); + if (mcRet != MC_DRV_OK) { + LOG_E("mcOpenTrustlet failed (%08x)", mcRet); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_COMMS; + if (mcRet == MC_DRV_ERR_TRUSTED_APPLICATION_NOT_FOUND) { + teecRes = TEEC_ERROR_ITEM_NOT_FOUND; + } else { + //TODO: Improve the error codes + teecRes = TEEC_ERROR_GENERIC; + } + goto error; + } + + session->imp.active = true; + + // Let TA go through entry points + LOG_I(" let TA go through entry points"); + ((_TEEC_TCI *)session->imp.tci)->operation.type = _TA_OPERATION_OPEN_SESSION; + teecRes = _TEEC_CallTA(session, operation, &returnOrigin_local); + + // Check for error on communication level + if (teecRes != TEEC_SUCCESS ) { + LOG_E("_TEEC_CallTA failed(%08x)", teecRes); + // Nothing to do here because _TEEC_CallTA closes broken sessions + if (returnOrigin != NULL) *returnOrigin = returnOrigin_local; + goto error; + } + LOG_I(" no errors in com layer"); + + // Check for error from TA + if (returnOrigin != NULL) *returnOrigin = ((_TEEC_TCI *)session->imp.tci)->returnOrigin; + teecRes = ((_TEEC_TCI *)session->imp.tci)->returnStatus; + if (teecRes != TEEC_SUCCESS ) { + LOG_E("TA OpenSession EP failed(%08x)", teecRes); + goto error; + } + + LOG_I(" %s() = TEEC_SUCCESS ", __func__); + pthread_mutex_unlock(&session->imp.mutex_tci); + + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_TRUSTED_APP; + return TEEC_SUCCESS; + + // ------------------------------------------------------------- +error: + if (session->imp.active) { + // After notifying us, TA went to Destry EP, so close session now + mcRet = mcCloseSession(&session->imp.handle); + if (mcRet != MC_DRV_OK) { + LOG_E("mcCloseSession failed (%08x)", mcRet); + /* continue even in case of error */; + } + session->imp.active = false; + } + + pthread_mutex_unlock(&session->imp.mutex_tci); + pthread_mutex_destroy(&session->imp.mutex_tci); + if (session->imp.tci) { + munmap(session->imp.tci, sysconf(_SC_PAGESIZE)); + session->imp.tci = NULL; + } + + LOG_I(" %s() = 0x%x", __func__, teecRes); + return teecRes; +} + +//------------------------------------------------------------------------------ +TEEC_Result TEEC_InvokeCommand( + TEEC_Session *session, + uint32_t commandID, + TEEC_Operation *operation, + uint32_t *returnOrigin) +{ + TEEC_Result teecRes; + uint32_t returnOrigin_local; + + LOG_I("== %s() ==============", __func__); + + // ------------------------------------------------------------- + if (session == NULL) { + LOG_E("session is NULL"); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_API; + return TEEC_ERROR_BAD_PARAMETERS; + } + + if (!session->imp.active) { + LOG_E("session is inactive"); + if (returnOrigin != NULL) *returnOrigin = TEEC_ORIGIN_API; + return TEEC_ERROR_BAD_STATE; + } + // ------------------------------------------------------------- + if (operation) operation->imp.session = &session->imp; + + pthread_mutex_lock(&session->imp.mutex_tci); + + // Call TA + ((_TEEC_TCI *)session->imp.tci)->operation.commandId = commandID; + ((_TEEC_TCI *)session->imp.tci)->operation.type = _TA_OPERATION_INVOKE_COMMAND; + teecRes = _TEEC_CallTA(session, operation, &returnOrigin_local); + if (teecRes != TEEC_SUCCESS ) { + LOG_E("_TEEC_CallTA failed(%08x)", teecRes); + if (returnOrigin != NULL) *returnOrigin = returnOrigin_local; + } else { + if (returnOrigin != NULL) *returnOrigin = ((_TEEC_TCI *)session->imp.tci)->returnOrigin; + teecRes = ((_TEEC_TCI *)session->imp.tci)->returnStatus; + } + + pthread_mutex_unlock(&session->imp.mutex_tci); + LOG_I(" %s() = 0x%x", __func__, teecRes); + return teecRes; +} + +//------------------------------------------------------------------------------ +void TEEC_CloseSession(TEEC_Session *session) +{ + mcResult_t mcRet; + TEEC_Result teecRes = TEEC_SUCCESS; + uint32_t returnOrigin; + + LOG_I("== %s() ==============", __func__); + + // ------------------------------------------------------------- + //The Implementation MUST do nothing if the session parameter is NULL. + if (session == NULL) { + LOG_E("session is NULL"); + return; + } + + // ------------------------------------------------------------- + if (session->imp.active) { + // Let TA go through CloseSession and Destroy entry points + LOG_I(" let TA go through close entry points"); + pthread_mutex_lock(&session->imp.mutex_tci); + ((_TEEC_TCI *)session->imp.tci)->operation.type = _TA_OPERATION_CLOSE_SESSION; + teecRes = _TEEC_CallTA(session, NULL, &returnOrigin); + if (teecRes != TEEC_SUCCESS ) { + /* continue even in case of error */; + LOG_E("_TEEC_CallTA failed(%08x)", teecRes); + } + + if (session->imp.active) { + // Close Session + mcRet = mcCloseSession(&session->imp.handle); + if (mcRet != MC_DRV_OK) { + LOG_E("mcCloseSession failed (%08x)", mcRet); + /* ignore error and also there shouldn't be one */ + } + } + pthread_mutex_unlock(&session->imp.mutex_tci); + } + + pthread_mutex_destroy(&session->imp.mutex_tci); + if (session->imp.tci) { + munmap(session->imp.tci, sysconf(_SC_PAGESIZE)); + session->imp.tci = NULL; + } + session->imp.active = false; + + LOG_I(" %s() = 0x%x", __func__, teecRes); +} + +//------------------------------------------------------------------------------ +TEEC_Result TEEC_RegisterSharedMemory( + TEEC_Context *context, + TEEC_SharedMemory *sharedMem) +{ + LOG_I("== %s() ==============", __func__); + + //The parameter context MUST point to an initialized TEE Context. + if (context == NULL) { + LOG_E("context is NULL"); + return TEEC_ERROR_BAD_PARAMETERS; + } + //The parameter sharedMem MUST point to the Shared Memory structure defining + //the memory region to register. + if (sharedMem == NULL) { + LOG_E("sharedMem is NULL"); + return TEEC_ERROR_BAD_PARAMETERS; + } + //The buffer field MUST point to the memory region to be shared, and MUST not be NULL. + if (sharedMem->buffer == NULL) { + LOG_E("sharedMem->buffer is NULL"); + return TEEC_ERROR_BAD_PARAMETERS; + } + + sharedMem->imp.implementation_allocated = false; + return TEEC_SUCCESS; +} + +//------------------------------------------------------------------------------ +TEEC_Result TEEC_AllocateSharedMemory( + TEEC_Context *context, + TEEC_SharedMemory *sharedMem) +{ + //No connection to "context"? + LOG_I("== %s() ==============", __func__); + + //The parameter context MUST point to an initialized TEE Context. + if (context == NULL) { + LOG_E("context is NULL"); + return TEEC_ERROR_BAD_PARAMETERS; + } + //The parameter sharedMem MUST point to the Shared Memory structure defining + //the memory region to register. + if (sharedMem == NULL) { + LOG_E("sharedMem is NULL"); + return TEEC_ERROR_BAD_PARAMETERS; + } + + sharedMem->buffer = malloc(sharedMem->size); + if (sharedMem->buffer == NULL) { + LOG_E("malloc failed"); + return TEEC_ERROR_OUT_OF_MEMORY; + } + sharedMem->imp.implementation_allocated = true; + + return TEEC_SUCCESS; +} + +//------------------------------------------------------------------------------ +void TEEC_ReleaseSharedMemory ( + TEEC_SharedMemory *sharedMem) +{ + //No connection to "context"? + LOG_I("== %s() ==============", __func__); + + //The Implementation MUST do nothing if the sharedMem parameter is NULL + if (sharedMem == NULL) { + LOG_E("sharedMem is NULL"); + return; + } + + //For a memory buffer allocated using TEEC_AllocateSharedMemory the Implementation + //MUST free the underlying memory + if (sharedMem->imp.implementation_allocated) { + if (sharedMem->buffer) { + free(sharedMem->buffer); + sharedMem->buffer = NULL; + sharedMem->size = 0; + } + } + + //TODO: Attempting to release Shared Memory which is used by a pending operation. + +} + +//------------------------------------------------------------------------------ +void TEEC_RequestCancellation( + TEEC_Operation *operation) +{ + LOG_I("== %s() ==============", __func__); + + while (operation->started == 0); + + LOG_I("while(operation->started ==0) passed"); + + if (operation->started > 1) { + LOG_I("The operation has finished"); + return; + } + + TEEC_Session_IMP *session = operation->imp.session; + operation->started = 2; + + if (!session->active) { + LOG_I("Corresponding session is not active"); + return; + } + ((_TEEC_TCI *)session->tci)->operation.isCancelled = true; + + // Step 4.3: signal the Trustlet + mcResult_t mcRet = mcNotify(&session->handle); + if (MC_DRV_OK != mcRet) { + LOG_E("Notify failed (%08x)", mcRet); + } +} + +//------------------------------------------------------------------------------ diff --git a/mobicore/daemon/ClientLib/Session.cpp b/mobicore/daemon/ClientLib/Session.cpp new file mode 100644 index 0000000..3f8dc77 --- /dev/null +++ b/mobicore/daemon/ClientLib/Session.cpp @@ -0,0 +1,208 @@ +/** @addtogroup MCD_IMPL_LIB + * @{ + * @file + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include +#include + +#include "mc_linux.h" + +#include "Session.h" + +#include "log.h" +#include + + +//------------------------------------------------------------------------------ +Session::Session( + uint32_t sessionId, + CMcKMod *mcKMod, + Connection *connection) +{ + this->sessionId = sessionId; + this->mcKMod = mcKMod; + this->notificationConnection = connection; + + sessionInfo.lastErr = SESSION_ERR_NO; + sessionInfo.state = SESSION_STATE_INITIAL; +} + + +//------------------------------------------------------------------------------ +Session::~Session(void) +{ + BulkBufferDescriptor *pBlkBufDescr; + + // Unmap still mapped buffers + for ( bulkBufferDescrIterator_t iterator = bulkBufferDescriptors.begin(); + iterator != bulkBufferDescriptors.end(); + ++iterator) { + pBlkBufDescr = *iterator; + + LOG_I("removeBulkBuf - handle= %d", + pBlkBufDescr->handle); + + // ignore any error, as we cannot do anything in this case. + int ret = mcKMod->unregisterWsmL2(pBlkBufDescr->handle); + if (ret != 0) { + LOG_E("removeBulkBuf(): mcKModUnregisterWsmL2 failed: %d", ret); + } + + //iterator = bulkBufferDescriptors.erase(iterator); + delete(pBlkBufDescr); + } + + // Finally delete notification connection + delete notificationConnection; + + unlock(); +} + + +//------------------------------------------------------------------------------ +void Session::setErrorInfo( + int32_t err +) +{ + sessionInfo.lastErr = err; +} + + +//------------------------------------------------------------------------------ +int32_t Session::getLastErr( + void +) +{ + return sessionInfo.lastErr; +} + + +//------------------------------------------------------------------------------ +mcResult_t Session::addBulkBuf(addr_t buf, uint32_t len, BulkBufferDescriptor **blkBuf) +{ + uint64_t pPhysWsmL2; + uint32_t handle; + + assert(blkBuf != NULL); + + // Search bulk buffer descriptors for existing vAddr + // At the moment a virtual address can only be added one time + for ( bulkBufferDescrIterator_t iterator = bulkBufferDescriptors.begin(); + iterator != bulkBufferDescriptors.end(); + ++iterator) { + if ((*iterator)->virtAddr == buf) { + LOG_E("Cannot map a buffer to multiple locations in one Trustlet."); + return MC_DRV_ERR_BUFFER_ALREADY_MAPPED; + } + } + + // Prepare the interface structure for memory registration in Kernel Module + mcResult_t ret = mcKMod->registerWsmL2(buf, len, 0, &handle, &pPhysWsmL2); + + if (ret != MC_DRV_OK) { + LOG_V(" mcKMod->registerWsmL2() failed with %x", ret); + return ret; + } + + LOG_V(" addBulkBuf - Handle of L2 Table = %u", handle); + + // Create new descriptor - secure virtual virtual set to 0, unknown! + *blkBuf = new BulkBufferDescriptor(buf, 0x0, len, handle); + + // Add to vector of descriptors + bulkBufferDescriptors.push_back(*blkBuf); + + return MC_DRV_OK; +} + +//------------------------------------------------------------------------------ +void Session::addBulkBuf(BulkBufferDescriptor *blkBuf) +{ + if (blkBuf) + // Add to vector of descriptors + bulkBufferDescriptors.push_back(blkBuf); +} + +//------------------------------------------------------------------------------ +uint32_t Session::getBufHandle(addr_t sVirtAddr, uint32_t sVirtualLen) +{ + LOG_V("getBufHandle(): Secure Virtual Address = 0x%X", (unsigned int) sVirtAddr); + + // Search and remove bulk buffer descriptor + for ( bulkBufferDescrIterator_t iterator = bulkBufferDescriptors.begin(); + iterator != bulkBufferDescriptors.end(); + ++iterator ) { + if (((*iterator)->sVirtualAddr == sVirtAddr) && ((*iterator)->len == sVirtualLen)) { + return (*iterator)->handle; + } + } + return 0; +} + +//------------------------------------------------------------------------------ +mcResult_t Session::removeBulkBuf(addr_t virtAddr) +{ + BulkBufferDescriptor *pBlkBufDescr = NULL; + + LOG_V("removeBulkBuf(): Virtual Address = 0x%X", (unsigned int) virtAddr); + + // Search and remove bulk buffer descriptor + for ( bulkBufferDescrIterator_t iterator = bulkBufferDescriptors.begin(); + iterator != bulkBufferDescriptors.end(); + ++iterator + ) { + + if ((*iterator)->virtAddr == virtAddr) { + pBlkBufDescr = *iterator; + iterator = bulkBufferDescriptors.erase(iterator); + break; + } + } + + if (pBlkBufDescr == NULL) { + LOG_E("%p not registered in session %d.", virtAddr, sessionId); + return MC_DRV_ERR_BLK_BUFF_NOT_FOUND; + } + LOG_V("removeBulkBuf():handle=%u", pBlkBufDescr->handle); + + // ignore any error, as we cannot do anything + mcResult_t ret = mcKMod->unregisterWsmL2(pBlkBufDescr->handle); + if (ret != MC_DRV_OK) { + LOG_E("mcKMod->unregisterWsmL2 failed: %x", ret); + return ret; + } + + delete (pBlkBufDescr); + + return MC_DRV_OK; +} + +/** @} */ diff --git a/mobicore/daemon/ClientLib/Session.h b/mobicore/daemon/ClientLib/Session.h new file mode 100644 index 0000000..5fc1e94 --- /dev/null +++ b/mobicore/daemon/ClientLib/Session.h @@ -0,0 +1,187 @@ +/** @addtogroup MCD_IMPL_LIB + * @{ + * @file + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 SESSION_H_ +#define SESSION_H_ + +#include +#include + +#include "mc_linux.h" +#include "Connection.h" +#include "CMcKMod.h" +#include "CMutex.h" + + +class BulkBufferDescriptor +{ +public: + addr_t virtAddr; /**< The virtual address of the Bulk buffer*/ + addr_t sVirtualAddr; /**< The secure virtual address of the Bulk buffer*/ + uint32_t len; /**< Length of the Bulk buffer*/ + uint32_t handle; + + BulkBufferDescriptor( + addr_t virtAddr, + addr_t sVirtAddr, + uint32_t len, + uint32_t handle + ) : + virtAddr(virtAddr), + sVirtualAddr(sVirtAddr), + len(len), + handle(handle) + {}; + +}; + +typedef std::list bulkBufferDescrList_t; +typedef bulkBufferDescrList_t::iterator bulkBufferDescrIterator_t; + + +/** Session states. + * At the moment not used !!. + */ +typedef enum { + SESSION_STATE_INITIAL, + SESSION_STATE_OPEN, + SESSION_STATE_TRUSTLET_DEAD +} sessionState_t; + +#define SESSION_ERR_NO 0 /**< No session error */ + +/** Session information structure. + * The information structure is used to hold the state of the session, which will limit further actions for the session. + * Also the last error code will be stored till it's read. + */ +typedef struct { + sessionState_t state; /**< Session state */ + int32_t lastErr; /**< Last error of session */ +} sessionInformation_t; + + +class Session +{ +private: + 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, MC_DRV_ERR_BUFFER_ALREADY_MAPPED is returned. + * + * @param buf The virtual address of bulk buffer. + * @param len Length of bulk buffer. + * @param blkBuf pointer of the actual Bulk buffer descriptor with all address information. + * + * @return MC_DRV_OK on success + * @return MC_DRV_ERR_BUFFER_ALREADY_MAPPED + */ + mcResult_t addBulkBuf(addr_t buf, uint32_t len, BulkBufferDescriptor **blkBuf); + + /** + * Just register the buffer previously created to the session + * + * @attention The virtual address can only be added one time. If the virtual address already exist, MC_DRV_ERR_BUFFER_ALREADY_MAPPED is returned. + * + * @param blkBuf pointer of the actual Bulk buffer descriptor with all address information. + * + */ + void addBulkBuf(BulkBufferDescriptor *blkBuf); + + /** + * 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. + */ + mcResult_t removeBulkBuf(addr_t buf); + + /** + * Return the Kmod handle of the bulk buff + * + * @param buf The secure virtual address of the bulk buffer. + * + * @return the Handle or 0 for failure + */ + uint32_t getBufHandle(addr_t sVirtAddr, uint32_t sVirtualLen); + + /** + * 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 sessionList_t; +typedef sessionList_t::iterator sessionIterator_t; + +#endif /* SESSION_H_ */ + +/** @} */ diff --git a/mobicore/ClientLib/include/GP/tee_client_api.h b/mobicore/daemon/ClientLib/public/GP/tee_client_api.h similarity index 75% rename from mobicore/ClientLib/include/GP/tee_client_api.h rename to mobicore/daemon/ClientLib/public/GP/tee_client_api.h index df3dcb5..c6f2090 100644 --- a/mobicore/ClientLib/include/GP/tee_client_api.h +++ b/mobicore/daemon/ClientLib/public/GP/tee_client_api.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -36,18 +36,19 @@ #ifndef __TEE_CLIENT_API_H__ #define __TEE_CLIENT_API_H__ -#include "tee_client_types.h" -#include "tee_client_error.h" +#include "tee_type.h" +#include "tee_error.h" #if TBASE_API_LEVEL >= 3 -#include "tee_client_api_imp.h" -#if (!defined(TEEC_EXPORT)) && defined(__cplusplus) +#if (!defined(TEEC_EXPORT)) && __cplusplus #define TEEC_EXPORT extern "C" #else #define TEEC_EXPORT #endif // __cplusplus + + /* The header tee_client_api_imp.h must define implementation-dependent types, constants and macros. @@ -68,6 +69,9 @@ typedef struct { uint32_t b; } TEEC_Value; + +#include "tee_client_api_imp.h" + /* Type definitions */ typedef struct TEEC_Context { TEEC_Context_IMP imp; @@ -111,34 +115,32 @@ typedef struct TEEC_Operation { } TEEC_Operation; -#define TEEC_ORIGIN_API 0x00000001 -#define TEEC_ORIGIN_COMMS 0x00000002 -#define TEEC_ORIGIN_TEE 0x00000003 -#define TEEC_ORIGIN_TRUSTED_APP 0x00000004 - -#define TEEC_MEM_INPUT 0x00000001 -#define TEEC_MEM_OUTPUT 0x00000002 - -#define TEEC_NONE 0x0 -#define TEEC_VALUE_INPUT 0x1 -#define TEEC_VALUE_OUTPUT 0x2 -#define TEEC_VALUE_INOUT 0x3 -#define TEEC_MEMREF_TEMP_INPUT 0x5 -#define TEEC_MEMREF_TEMP_OUTPUT 0x6 -#define TEEC_MEMREF_TEMP_INOUT 0x7 -#define TEEC_MEMREF_WHOLE 0xC -#define TEEC_MEMREF_PARTIAL_INPUT 0xD -#define TEEC_MEMREF_PARTIAL_OUTPUT 0xE -#define TEEC_MEMREF_PARTIAL_INOUT 0xF - -#define TEEC_LOGIN_PUBLIC 0x00000000 -#define TEEC_LOGIN_USER 0x00000001 -#define TEEC_LOGIN_GROUP 0x00000002 -#define TEEC_LOGIN_APPLICATION 0x00000004 -#define TEEC_LOGIN_USER_APPLICATION 0x00000005 -#define TEEC_LOGIN_GROUP_APPLICATION 0x00000006 - -#define TEEC_TIMEOUT_INFINITE 0xFFFFFFFF +#define TEEC_ORIGIN_API 0x00000001 +#define TEEC_ORIGIN_COMMS 0x00000002 +#define TEEC_ORIGIN_TEE 0x00000003 +#define TEEC_ORIGIN_TRUSTED_APP 0x00000004 + +#define TEEC_MEM_INPUT 0x00000001 +#define TEEC_MEM_OUTPUT 0x00000002 + +#define TEEC_NONE 0x0 +#define TEEC_VALUE_INPUT 0x1 +#define TEEC_VALUE_OUTPUT 0x2 +#define TEEC_VALUE_INOUT 0x3 +#define TEEC_MEMREF_TEMP_INPUT 0x5 +#define TEEC_MEMREF_TEMP_OUTPUT 0x6 +#define TEEC_MEMREF_TEMP_INOUT 0x7 +#define TEEC_MEMREF_WHOLE 0xC +#define TEEC_MEMREF_PARTIAL_INPUT 0xD +#define TEEC_MEMREF_PARTIAL_OUTPUT 0xE +#define TEEC_MEMREF_PARTIAL_INOUT 0xF + +#define TEEC_LOGIN_PUBLIC 0x00000000 +#define TEEC_LOGIN_USER 0x00000001 +#define TEEC_LOGIN_GROUP 0x00000002 +#define TEEC_LOGIN_APPLICATION 0x00000004 +#define TEEC_LOGIN_USER_APPLICATION 0x00000005 +#define TEEC_LOGIN_GROUP_APPLICATION 0x00000006 #pragma GCC visibility push(default) @@ -165,7 +167,7 @@ TEEC_EXPORT TEEC_Result TEEC_OpenSession ( TEEC_Session *session, const TEEC_UUID *destination, uint32_t connectionMethod, - const void *connectionData, + void *connectionData, TEEC_Operation *operation, uint32_t *returnOrigin); diff --git a/mobicore/ClientLib/include/GP/tee_client_api_imp.h b/mobicore/daemon/ClientLib/public/GP/tee_client_api_imp.h similarity index 79% rename from mobicore/ClientLib/include/GP/tee_client_api_imp.h rename to mobicore/daemon/ClientLib/public/GP/tee_client_api_imp.h index 163d810..75c01fe 100644 --- a/mobicore/ClientLib/include/GP/tee_client_api_imp.h +++ b/mobicore/daemon/ClientLib/public/GP/tee_client_api_imp.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -41,27 +41,34 @@ #include -#define TEEC_MEM_INOUT (TEEC_MEM_INPUT | TEEC_MEM_OUTPUT) +#include "tee_type.h" +#include "tee_error.h" +#include "MobiCoreDriverApi.h" + typedef struct { - uint32_t reserved; -} TEEC_Context_IMP; + uint32_t reserved; +} +TEEC_Context_IMP; + typedef struct { - uint32_t sessionId; - TEEC_Context_IMP context; - void *tci; - bool active; - pthread_mutex_t mutex_tci; //mutex to serialize CA requests -} TEEC_Session_IMP; + mcSessionHandle_t handle; + void *tci; + bool active; + pthread_mutex_t mutex_tci; //mutex to serialize CA requests +} +TEEC_Session_IMP; typedef struct { - bool implementation_allocated; -} TEEC_SharedMemory_IMP; + bool implementation_allocated; +} +TEEC_SharedMemory_IMP; typedef struct { - TEEC_Session_IMP *session; -} TEEC_Operation_IMP; + TEEC_Session_IMP *session; +} +TEEC_Operation_IMP; /* There is no natural, compile-time limit on the shared memory, but a specific implementation may introduce a limit (in particular on TrustZone) */ @@ -70,6 +77,6 @@ typedef struct { #define TEEC_PARAM_TYPES(entry0Type, entry1Type, entry2Type, entry3Type) \ ((entry0Type) | ((entry1Type) << 4) | ((entry2Type) << 8) | ((entry3Type) << 12)) -#endif /* TBASE_API_LEVEL >= 3 */ +#endif /* TBASE_API_LEVEL */ #endif /* __TEE_CLIENT_API_IMP_H__ */ diff --git a/mobicore/daemon/ClientLib/public/GP/tee_error.h b/mobicore/daemon/ClientLib/public/GP/tee_error.h new file mode 100644 index 0000000..fbae687 --- /dev/null +++ b/mobicore/daemon/ClientLib/public/GP/tee_error.h @@ -0,0 +1,177 @@ +/** + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __TEE_ERROR_H__ +#define __TEE_ERROR_H__ + +#define TEE_SUCCESS ((TEE_Result)0x00000000) +#define TEEC_SUCCESS TEE_SUCCESS + +#define TEE_ERROR_CORRUPT_OBJECT ((TEE_Result)0xF0100001) +#define TEE_ERROR_CORRUPT_OBJECT_2 ((TEE_Result)0xF0100002) + +/** + * Generic error code : Generic error + **/ +#define TEE_ERROR_GENERIC ((TEE_Result)0xFFFF0000) +#define TEEC_ERROR_GENERIC TEE_ERROR_GENERIC + +/** + * Generic error code : The underlying security system denies the access to the + * object + **/ +#define TEE_ERROR_ACCESS_DENIED ((TEE_Result)0xFFFF0001) +#define TEEC_ERROR_ACCESS_DENIED TEE_ERROR_ACCESS_DENIED + +/** + * Generic error code : The pending operation is cancelled. + **/ +#define TEE_ERROR_CANCEL ((TEE_Result)0xFFFF0002) +#define TEEC_ERROR_CANCEL TEE_ERROR_CANCEL + +/** + * Generic error code : The underlying system detects a conflict + **/ +#define TEE_ERROR_ACCESS_CONFLICT ((TEE_Result)0xFFFF0003) +#define TEEC_ERROR_ACCESS_CONFLICT TEE_ERROR_ACCESS_CONFLICT + +/** + * Generic error code : Too much data for the operation or some data remain + * unprocessed by the operation. + **/ +#define TEE_ERROR_EXCESS_DATA ((TEE_Result)0xFFFF0004) +#define TEEC_ERROR_EXCESS_DATA TEE_ERROR_EXCESS_DATA + +/** + * Generic error code : Error of data format + **/ +#define TEE_ERROR_BAD_FORMAT ((TEE_Result)0xFFFF0005) +#define TEEC_ERROR_BAD_FORMAT TEE_ERROR_BAD_FORMAT + +/** + * Generic error code : The specified parameters are invalid + **/ +#define TEE_ERROR_BAD_PARAMETERS ((TEE_Result)0xFFFF0006) +#define TEEC_ERROR_BAD_PARAMETERS TEE_ERROR_BAD_PARAMETERS + + +/** + * Generic error code : Illegal state for the operation. + **/ +#define TEE_ERROR_BAD_STATE ((TEE_Result)0xFFFF0007) +#define TEEC_ERROR_BAD_STATE TEE_ERROR_BAD_STATE + +/** + * Generic error code : The item is not found + **/ +#define TEE_ERROR_ITEM_NOT_FOUND ((TEE_Result)0xFFFF0008) +#define TEEC_ERROR_ITEM_NOT_FOUND TEE_ERROR_ITEM_NOT_FOUND + +/** + * Generic error code : The specified operation is not implemented + **/ +#define TEE_ERROR_NOT_IMPLEMENTED ((TEE_Result)0xFFFF0009) +#define TEEC_ERROR_NOT_IMPLEMENTED TEE_ERROR_NOT_IMPLEMENTED + +/** + * Generic error code : The specified operation is not supported + **/ +#define TEE_ERROR_NOT_SUPPORTED ((TEE_Result)0xFFFF000A) +#define TEEC_ERROR_NOT_SUPPORTED TEE_ERROR_NOT_SUPPORTED + +/** + * Generic error code : Insufficient data is available for the operation. + **/ +#define TEE_ERROR_NO_DATA ((TEE_Result)0xFFFF000B) +#define TEEC_ERROR_NO_DATA TEE_ERROR_NO_DATA + +/** + * Generic error code : Not enough memory to perform the operation + **/ +#define TEE_ERROR_OUT_OF_MEMORY ((TEE_Result)0xFFFF000C) +#define TEEC_ERROR_OUT_OF_MEMORY TEE_ERROR_OUT_OF_MEMORY + +/** + * Generic error code : The service is currently unable to handle the request; + * try later + **/ +#define TEE_ERROR_BUSY ((TEE_Result)0xFFFF000D) +#define TEEC_ERROR_BUSY TEE_ERROR_BUSY + +/** + * Generic communication error + **/ +#define TEE_ERROR_COMMUNICATION ((TEE_Result)0xFFFF000E) +#define TEEC_ERROR_COMMUNICATION TEE_ERROR_COMMUNICATION + +/** + * Generic error code : security violation + **/ +#define TEE_ERROR_SECURITY ((TEE_Result)0xFFFF000F) +#define TEEC_ERROR_SECURITY TEE_ERROR_SECURITY + +/** + * Generic error code : the buffer is too short + **/ +#define TEE_ERROR_SHORT_BUFFER ((TEE_Result)0xFFFF0010) +#define TEEC_ERROR_SHORT_BUFFER TEE_ERROR_SHORT_BUFFER + +/** + * Generic error code : The pending operation is cancelled. + */ +#define TEE_ERROR_EXTERNAL_CANCEL ((TEE_Result)0xFFFF0011) + +/** + * Generic error code : the operation is not terminated + **/ +#define TEE_PENDING ((TEE_Result)0xFFFF2000) + +/** + * Generic error code : A timeout occurred + **/ +#define TEE_ERROR_TIMEOUT ((TEE_Result)0xFFFF3001) + +/** + * Generic error code : Overflow + **/ +#define TEE_ERROR_OVERFLOW ((TEE_Result)0xFFFF300F) + +/** + * Error of communication: The target of the connection is dead + **/ +#define TEE_ERROR_TARGET_DEAD ((TEE_Result)0xFFFF3024) +#define TEEC_ERROR_TARGET_DEAD TEE_ERROR_TARGET_DEAD + +/*------------------------------------------------------------------------------ + Storage Error Codes +------------------------------------------------------------------------------*/ + +/** File system error code: not enough space to complete the operation. */ +#define TEE_ERROR_STORAGE_NO_SPACE ((TEE_Result)0xFFFF3041) + +/*------------------------------------------------------------------------------ + Crypto error codes +------------------------------------------------------------------------------*/ + +#define TEE_ERROR_MAC_INVALID ((TEE_Result)0xFFFF3071) + +#define TEE_ERROR_SIGNATURE_INVALID ((TEE_Result)0xFFFF3072) + +/*------------------------------------------------------------------------------ + Date error codes +------------------------------------------------------------------------------*/ + +#define TEE_ERROR_TIME_NOT_SET ((TEE_Result)0xFFFF5000) + +#define TEE_ERROR_TIME_NEEDS_RESET ((TEE_Result)0xFFFF5001) + +#endif /* __TEE_ERROR_H__ */ + diff --git a/mobicore/daemon/ClientLib/public/GP/tee_internal_api_impl.h b/mobicore/daemon/ClientLib/public/GP/tee_internal_api_impl.h new file mode 100644 index 0000000..9acd363 --- /dev/null +++ b/mobicore/daemon/ClientLib/public/GP/tee_internal_api_impl.h @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +#ifndef __TEE_INTERNAL_API_IMPL_H__ +#define __TEE_INTERNAL_API_IMPL_H__ + +#if TBASE_API_LEVEL >= 3 + +/*------------------------------------------------------------------------------ + Constants +------------------------------------------------------------------------------*/ +// Property type constants +#define TEE_PROPERTY_TYPE_NONE 0 +#define TEE_PROPERTY_TYPE_BOOLEAN 1 +#define TEE_PROPERTY_TYPE_UINT32 2 +#define TEE_PROPERTY_TYPE_BINARY 3 +#define TEE_PROPERTY_TYPE_STRING 4 +#define TEE_PROPERTY_TYPE_UUID 5 + +// Predefined offsets to properties +#define TEE_PROPERTY_GPUUID_VALUE_OFFSET 20 +#define TEE_PROPERTY_DATASIZE_VALUE_OFFSET 152 +#define TEE_PROPERTY_STACKSIZE_VALUE_OFFSET 180 + +#endif /* TBASE_API_LEVEL */ + +#endif /* __TEE_INTERNAL_API_IMPL_H__ */ diff --git a/mobicore/daemon/ClientLib/public/GP/tee_type.h b/mobicore/daemon/ClientLib/public/GP/tee_type.h new file mode 100644 index 0000000..8cf5898 --- /dev/null +++ b/mobicore/daemon/ClientLib/public/GP/tee_type.h @@ -0,0 +1,143 @@ +/** + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * Definition of the machine-specific integer types + **/ +#ifndef __TEE_TYPE_H__ +#define __TEE_TYPE_H__ + +/* C99 integer types */ +#if (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) &&(!defined(ANDROID)) + +#include + +/* Figure out if a 64-bit integer types is available */ +#if \ + defined(_MSC_VER) || \ + defined(__SYMBIAN32__) || \ + defined(_WIN32_WCE) || \ + (defined(ULLONG_MAX) && ULLONG_MAX == 0xFFFFFFFFFFFFFFFFULL) || \ + (defined(ULONG_LONG_MAX) && ULONG_LONG_MAX == 0xFFFFFFFFFFFFFFFFULL) +typedef unsigned long long uint64_t; +typedef long long int64_t; +#else +#define __S_TYPE_INT64_UNDEFINED +#endif + +#if UINT_MAX == 0xFFFFFFFF +typedef unsigned int uint32_t; +typedef int int32_t; +#elif ULONG_MAX == 0xFFFFFFFF +typedef unsigned long uint32_t; +typedef long int32_t; +#else +#error This compiler is not supported. +#endif + +#if USHRT_MAX == 0xFFFF +typedef unsigned short uint16_t; +typedef short int16_t; +#else +#error This compiler is not supported. +#endif + +#if UCHAR_MAX == 0xFF +typedef unsigned char uint8_t; +typedef signed char int8_t; +#else +#error This compiler is not supported. +#endif + +#if !defined(__cplusplus) +typedef unsigned char bool; +#define false ( (bool)0 ) +#define true ( (bool)1 ) +#endif + +#else /* !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L */ + +#include +#include + +#endif /* !(!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) */ + +#include + +#ifndef NULL +# ifdef __cplusplus +# define NULL 0 +# else +# define NULL ((void *)0) +# endif +#endif + +#define IN +#define OUT + +/* + * Definition of other common types + */ + +// to delete when all completed +typedef uint32_t TEE_Result; +typedef TEE_Result TEEC_Result; + +typedef uint32_t TEE_HANDLE; + +/** Definition of an UUID (from RFC 4122 http://www.ietf.org/rfc/rfc4122.txt) */ +typedef struct TEE_UUID { + uint32_t timeLow; + uint16_t timeMid; + uint16_t timeHiAndVersion; + uint8_t clockSeqAndNode[8]; +} TEE_UUID; +typedef TEE_UUID TEEC_UUID; + +/** Type definition for a TEE Identity */ +typedef struct TEE_Identity { + uint32_t login; + TEE_UUID uuid; +} TEE_Identity; + +typedef struct __TEE_PropSetHandle { + unsigned char reserved; +} __TEE_PropSetHandle; + +typedef struct __TEE_PropSetHandle* TEE_PropSetHandle; + +/* Property Sets Pseudo Handles */ +#define TEE_PROPSET_CURRENT_TA (TEE_PropSetHandle)0xFFFFFFFF +#define TEE_PROPSET_CURRENT_CLIENT (TEE_PropSetHandle)0xFFFFFFFE +#define TEE_PROPSET_TEE_IMPLEMENTATION (TEE_PropSetHandle)0xFFFFFFFD + + +/* DLL Import/Export directives */ + +#if defined(WIN32) || defined(__ARMCC_VERSION) || defined(__WINSCW__) || defined(_WIN32_WCE) +# define S_DLL_EXPORT __declspec(dllexport) +# define S_DLL_IMPORT __declspec(dllimport) +# define S_NO_RETURN __declspec(noreturn) +#elif defined(__GNUC__) +# define S_DLL_EXPORT __attribute__ ((visibility ("default"))) +# define S_DLL_IMPORT __attribute__ ((visibility ("default"))) +# define S_NO_RETURN __attribute__ ((noreturn)) +#else +# define S_DLL_EXPORT +# define S_DLL_IMPORT +# define S_NO_RETURN +#endif + +#if defined(_MSC_VER) +#define __func__ __FUNCTION__ +#endif + +#endif /* __TEE_TYPE_H__ */ diff --git a/mobicore/ClientLib/include/uuid_attestation.h b/mobicore/daemon/ClientLib/public/GP/uuid_attestation.h similarity index 50% rename from mobicore/ClientLib/include/uuid_attestation.h rename to mobicore/daemon/ClientLib/public/GP/uuid_attestation.h index 4230572..dd48fc2 100644 --- a/mobicore/ClientLib/include/uuid_attestation.h +++ b/mobicore/daemon/ClientLib/public/GP/uuid_attestation.h @@ -1,40 +1,18 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. +/** + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. */ #ifndef __TEE_UUID_ATTESTATION_H__ #define __TEE_UUID_ATTESTATION_H__ -#ifndef __TEE_CLIENT_TYPES_H__ #include "tee_type.h" -#endif // Sizes of the fields of attestation structure #define AT_MAGIC_SIZE 8 @@ -64,7 +42,7 @@ const char TAG[AT_TAG_SIZE]="Trusted Application"; // Public key structure typedef struct uuid_public_key { - uint32_t type; // TEE_TYPE_RSA_PUBLIC_KEY: 0xA0000030 + uint32_t type; // TEE TYPE RSA KEYPAIR: 0xa0000030 uint16_t modulus_bytes; // Length of the modulus in bytes uint16_t exponent_bytes; // Length of the exponent in bytes uint8_t data[]; // Key material diff --git a/mobicore/ClientLib/include/MobiCoreDriverApi.h b/mobicore/daemon/ClientLib/public/MobiCoreDriverApi.h similarity index 89% rename from mobicore/ClientLib/include/MobiCoreDriverApi.h rename to mobicore/daemon/ClientLib/public/MobiCoreDriverApi.h index 8439f24..425f5e5 100644 --- a/mobicore/ClientLib/include/MobiCoreDriverApi.h +++ b/mobicore/daemon/ClientLib/public/MobiCoreDriverApi.h @@ -1,37 +1,49 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED - * All rights reserved. +/** + * @defgroup MCD_API MobiCore Driver API + * @addtogroup MCD_API + * @{ * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * @if DOXYGEN_MCDRV_API + * @mainpage MobiCore Driver API. + * @endif * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * MobiCore Driver API. * + * The MobiCore (MC) Driver API provides access functions to the t-base trusted execution environment and the contained Trusted Applications. + * + * @image html DoxyOverviewDrvApi500x.png + * @image latex DoxyOverviewDrvApi500x.png "t-base Overview" width=12cm + */ +/* + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. + * 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 MCDRIVER_H_ #define MCDRIVER_H_ -#if (!defined(__MC_CLIENT_LIB_API)) && defined(__cplusplus) +#if (!defined(__MC_CLIENT_LIB_API)) && __cplusplus #define __MC_CLIENT_LIB_API extern "C" #else #define __MC_CLIENT_LIB_API @@ -113,8 +125,8 @@ typedef uint32_t mcResult_t; #define MC_DRV_ERR_TCI_TOO_BIG MC_DRV_ERR_INVALID_PARAMETER /**< Requested TCI length is too high. */ #define MC_DRV_ERR_WSM_NOT_FOUND MC_DRV_ERR_INVALID_PARAMETER /**< Requested TCI was not allocated with mallocWsm(). */ #define MC_DRV_ERR_TCI_GREATER_THAN_WSM MC_DRV_ERR_INVALID_PARAMETER /**< Requested TCI length is bigger than allocated WSM. */ -#define MC_DRV_ERR_TRUSTLET_NOT_FOUND MC_DRV_ERR_INVALID_DEVICE_FILE /** < Trustlet could not be found. */ -#define MC_DRV_ERR_TRUSTED_APPLICATION_NOT_FOUND MC_DRV_ERR_TRUSTLET_NOT_FOUND /** < Trusted Application could not be found. */ +#define MC_DRV_ERR_TRUSTLET_NOT_FOUND MC_DRV_ERR_INVALID_DEVICE_FILE /** < Trustlet could not be found in mcRegistry. */ +#define MC_DRV_ERR_TRUSTED_APPLICATION_NOT_FOUND MC_DRV_ERR_TRUSTLET_NOT_FOUND /** < Trusted Application could not be found in mcRegistry. */ #define MC_DRV_ERR_DAEMON_KMOD_ERROR MC_DRV_ERR_DAEMON_UNREACHABLE /**< Daemon cannot use Kernel module as expected. */ #define MC_DRV_ERR_DAEMON_MCI_ERROR MC_DRV_ERR_DAEMON_UNREACHABLE /**< Daemon cannot use MCI as expected. */ #define MC_DRV_ERR_MCP_ERROR MC_DRV_ERR_DAEMON_UNREACHABLE /**< MobiCore Control Protocol error. See MC_DRV_ERROR_MCP(). */ @@ -129,29 +141,20 @@ typedef uint32_t mcResult_t; #if TBASE_API_LEVEL >= 3 // Installation errors +#define MC_DRV_ERR_TA_HEADER_ERROR 0x00000021 /**< TA blob header is incorrect. */ #define MC_DRV_ERR_TA_ATTESTATION_ERROR 0x00000022 /**< TA blob attestation is incorrect. */ #endif /* TBASE_API_LEVEL */ -#define MC_DRV_ERR_INTERRUPTED_BY_SIGNAL 0x00000023 /**< Interrupted system call. */ +#define MAKE_MC_DRV_MCP_ERROR(mcpCode) (MC_DRV_ERR_MCP_ERROR | ((mcpCode&0x000FFFFF)<<8)) +#define MAKE_MC_DRV_KMOD_WITH_ERRNO(theErrno) (MC_DRV_ERR_KERNEL_MODULE| (((theErrno)&0x0000FFFF)<<16)) -#if TBASE_API_LEVEL >= 5 /** - * Do we call these RESERVED_1, _2 etc? (as this file is public, or do we wash it?) + * Driver control command. */ -#define MC_DRV_ERR_SERVICE_BLOCKED 0x00000024 /**< Service is blocked and opensession is thus not allowed. */ -#define MC_DRV_ERR_SERVICE_LOCKED 0x00000025 /**< Service is locked and opensession is thus not allowed. */ -#define MC_DRV_ERR_SERVICE_KILLED 0x00000026 /**< Service was killed by the TEE (due to an administrative command). */ -#define MC_DRV_ERR_NO_FREE_INSTANCES 0x00000027 /**< All permitted instances to the service are used */ - -#endif /* TBASE_API_LEVEL >= 5 */ - -#if TBASE_API_LEVEL >= 3 -// Installation errors -#define MC_DRV_ERR_TA_HEADER_ERROR 0x00000028 /**< TA blob header is incorrect. */ -#endif /* TBASE_API_LEVEL */ +typedef enum { + MC_CTRL_DUMMY = 1 /**< Dummy. */ +} mcDriverCtrl_t; -#define MAKE_MC_DRV_MCP_ERROR(mcpCode) (MC_DRV_ERR_MCP_ERROR | ((mcpCode&0x000FFFFF)<<8)) -#define MAKE_MC_DRV_KMOD_WITH_ERRNO(theErrno) (MC_DRV_ERR_KERNEL_MODULE| (((theErrno)&0x0000FFFF)<<16)) /** Structure of Session Handle, includes the Session ID and the Device ID the Session belongs to. * The session handle will be used for session-based t-base communication. @@ -167,21 +170,14 @@ typedef struct { * In order to use the memory within a Trusted Application the Client Application has to inform the Trusted Application with * the content of this structure via the TCI. */ - typedef struct { -#if ( __WORDSIZE == 64 ) - uint32_t sVirtualAddr; /**< The virtual address of the Bulk buffer regarding the address space of the Trusted Application, already includes a possible offset! */ -#else - void *sVirtualAddr; -#endif + void *sVirtualAddr; /**< The virtual address of the Bulk buffer regarding the address space of the Trusted Application, already includes a possible offset! */ uint32_t sVirtualLen; /**< Length of the mapped Bulk buffer */ } mcBulkMap_t; - #define MC_DEVICE_ID_DEFAULT 0 /**< The default device ID */ #define MC_INFINITE_TIMEOUT ((int32_t)(-1)) /**< Wait infinite for a response of the MC. */ -#define MC_INFINITE_TIMEOUT_INTERRUPTIBLE ((int32_t)(-2)) /**< Wait infinite for a response of the MC, exit on signal. */ #define MC_NO_TIMEOUT 0 /**< Do not wait for a response of the MC. */ #define MC_MAX_TCI_LEN 0x100000 /**< TCI/DCI must not exceed 1MiB */ @@ -203,6 +199,8 @@ typedef struct { * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon occur. * @return MC_DRV_ERR_UNKNOWN_DEVICE when deviceId is unknown. * @return MC_DRV_ERR_INVALID_DEVICE_FILE if kernel module under /dev/mobicore cannot be opened + * + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcOpenDevice( uint32_t deviceId @@ -220,7 +218,7 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenDevice( * @return MC_DRV_ERR_SESSION_PENDING when a session is still open. * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon occur. * - * Uses a mutex. + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcCloseDevice( uint32_t deviceId @@ -242,6 +240,8 @@ __MC_CLIENT_LIB_API mcResult_t mcCloseDevice( * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon socket occur. * @return MC_DRV_ERR_UNKNOWN_DEVICE when daemon returns an error. * @return MC_DRV_ERR_TRUSTED_APPLICATION_NOT_FOUND when Trusted Application or driver cannot be loaded. + * + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( mcSessionHandle_t *session, @@ -268,6 +268,8 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenSession( * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon socket occur. * @return MC_DRV_ERR_UNKNOWN_DEVICE when daemon returns an error. * @return MC_DRV_ERR_TRUSTED_APPLICATION_NOT_FOUND when Trusted Application cannot be loaded. + * + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcOpenTrustlet( mcSessionHandle_t *session, @@ -293,6 +295,8 @@ __MC_CLIENT_LIB_API mcResult_t mcOpenTrustlet( * @return MC_DRV_ERR_UNKNOWN_DEVICE when device id of session is invalid. * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon occur. * @return MC_DRV_ERR_INVALID_DEVICE_FILE when daemon cannot open trustlet file. + * + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcCloseSession( mcSessionHandle_t *session @@ -326,7 +330,7 @@ __MC_CLIENT_LIB_API mcResult_t mcNotify( * Caller has to trust the other side to send a notification to wake him up again. * * @param [in] session The session the notification should correspond to. - * @param [in] timeout Time in milliseconds to wait (MC_NO_TIMEOUT : direct return, > 0 : milliseconds, MC_INFINITE_TIMEOUT : wait indefinitely, MC_INFINITE_TIMEOUT_INTERRUPTIBLE : wait indefinitely except if signal received) + * @param [in] timeout Time in milliseconds to wait (MC_NO_TIMEOUT : direct return, > 0 : milliseconds, MC_INFINITE_TIMEOUT : wait infinitely) * * @return MC_DRV_OK if notification is available. * @return MC_DRV_ERR_TIMEOUT if no notification arrived in time. @@ -360,7 +364,7 @@ __MC_CLIENT_LIB_API mcResult_t mcWaitNotification( * @return MC_DRV_ERR_UNKNOWN_DEVICE when device id is invalid. * @return MC_DRV_ERR_NO_FREE_MEMORY if no more contiguous memory is available in this size or for this process. * - * Uses a mutex. + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcMallocWsm( uint32_t deviceId, @@ -384,7 +388,7 @@ __MC_CLIENT_LIB_API mcResult_t mcMallocWsm( * @return MC_DRV_ERR_UNKNOWN_DEVICE when device id is invalid. * @return MC_DRV_ERR_FREE_MEMORY_FAILED on failures. * - * Uses a mutex. + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcFreeWsm( uint32_t deviceId, @@ -412,6 +416,8 @@ __MC_CLIENT_LIB_API mcResult_t mcFreeWsm( * @return MC_DRV_ERR_UNKNOWN_DEVICE when device id of session is invalid. * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon occur. * @return MC_DRV_ERR_BULK_MAPPING when buf is already uses as bulk buffer or when registering the buffer failed. + * + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcMap( mcSessionHandle_t *session, @@ -439,6 +445,8 @@ __MC_CLIENT_LIB_API mcResult_t mcMap( * @return MC_DRV_ERR_UNKNOWN_DEVICE when device id of session is invalid. * @return MC_DRV_ERR_DAEMON_UNREACHABLE when problems with daemon occur. * @return MC_DRV_ERR_BULK_UNMAPPING when buf was not registered earlier or when unregistering failed. + * + * Uses a Mutex. */ __MC_CLIENT_LIB_API mcResult_t mcUnmap( mcSessionHandle_t *session, @@ -446,6 +454,26 @@ __MC_CLIENT_LIB_API mcResult_t mcUnmap( mcBulkMap_t *mapInfo ); + +/** + * @attention: Not implemented. + * Execute driver specific command. + * mcDriverCtrl() can be used to execute driver specific commands. + * Besides the control command MC_CTRL_GET_VERSION commands are implementation specific. + * Please refer to the corresponding specification of the driver manufacturer. + * + * @param [in] param Command ID of the command to be executed. + * @param [in, out] data Command data and response depending on command. + * @param [in] len Length of the data block. + * + * @return MC_DRV_ERR_NOT_IMPLEMENTED. + */ +__MC_CLIENT_LIB_API mcResult_t mcDriverCtrl( + mcDriverCtrl_t param, + uint8_t *data, + uint32_t len +); + /** * Get additional error information of the last error that occurred on a session. * After the request the stored error code will be deleted. @@ -484,3 +512,4 @@ __MC_CLIENT_LIB_API mcResult_t mcGetMobiCoreVersion( #endif #endif /** MCDRIVER_H_ */ +/** @} */ diff --git a/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.def b/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.def new file mode 100644 index 0000000..8a086d2 --- /dev/null +++ b/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.def @@ -0,0 +1,25 @@ +; ------------------------------------------------------------------------ +; Copyright (c) 2013 TRUSTONIC LIMITED +; All rights reserved +; +; The present software is the confidential and proprietary information of +; TRUSTONIC LIMITED. You shall not disclose the present software and shall +; use it only in accordance with the terms of the license agreement you +; entered into with TRUSTONIC LIMITED. This software may be subject to +; export or import laws in certain countries. +; ------------------------------------------------------------------------ +EXPORTS + mcOpenDevice + mcCloseDevice + mcOpenSession + mcOpenTrustlet + mcCloseSession + mcNotify + mcWaitNotification + mcMallocWsm + mcFreeWsm + mcMap + mcUnmap + mcGetSessionErrorCode + mcGetMobiCoreVersion + diff --git a/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.sln b/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.sln new file mode 100644 index 0000000..f1320ae --- /dev/null +++ b/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Express 2012 for Windows Desktop +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "t-base_client_api", "t-base_client_api.vcxproj", "{AA0349EE-7BCF-4CFF-ABB0-62EC1810DE67}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AA0349EE-7BCF-4CFF-ABB0-62EC1810DE67}.Release|Win32.ActiveCfg = Release|Win32 + {AA0349EE-7BCF-4CFF-ABB0-62EC1810DE67}.Release|Win32.Build.0 = Release|Win32 + {AA0349EE-7BCF-4CFF-ABB0-62EC1810DE67}.Release|x64.ActiveCfg = Release|x64 + {AA0349EE-7BCF-4CFF-ABB0-62EC1810DE67}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.vcxproj b/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.vcxproj new file mode 100644 index 0000000..af992c7 --- /dev/null +++ b/mobicore/daemon/ClientLib/public/Windows/t-base_client_api.vcxproj @@ -0,0 +1,109 @@ + + + + + Release + Win32 + + + Release + x64 + + + + + + + {AA0349EE-7BCF-4CFF-ABB0-62EC1810DE67} + t-base_client_api + + + + DynamicLibrary + + + v110 + + + DynamicLibrary + + v110 + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + ..\..\..\..\Out\Bin\Windows\$(Platform)\Release\ + ..\..\..\..\Out\_build\Windows\$(Platform)\Release\ + + + + ..\..\..\..\Out\Bin\Windows\$(Platform)\Release\ + ..\..\..\..\Out\_build\Windows\$(Platform)\Release\ + + + + ..\Common;$(COMP_PATH_TlSdk)\Public\MobiCore\inc;%(AdditionalIncludeDirectories) + WIN32 + + + + + + + + + + + + + + + + + + + + + $(TargetName).def + + + + + ..\Common;$(COMP_PATH_TlSdk)\Public\MobiCore\inc;%(AdditionalIncludeDirectories) + WIN32 + + + + + + + + + + + + + + + + + + + + + $(TargetName).def + + + + + + \ No newline at end of file diff --git a/mobicore/daemon/Common/Android.mk b/mobicore/daemon/Common/Android.mk new file mode 100644 index 0000000..55747b7 --- /dev/null +++ b/mobicore/daemon/Common/Android.mk @@ -0,0 +1,31 @@ +# ============================================================================= +# +# Module: libCommon.a - classes shared by various modules +# +# ============================================================================= + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := Common + +# Add new source files here +#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) + +# Enable logging +# LOCAL_SHARED_LIBRARIES += liblog +# +# LOCAL_CFLAGS += -DLOG_ANDROID +# +# LOCAL_C_INCLUDES += $(LOCAL_PATH)/../common/LogWrapper + +include $(BUILD_STATIC_LIBRARY) diff --git a/mobicore/Daemon/src/CThread.cpp b/mobicore/daemon/Common/CMutex.cpp similarity index 65% rename from mobicore/Daemon/src/CThread.cpp rename to mobicore/daemon/Common/CMutex.cpp index 9fe47de..dc9e24f 100644 --- a/mobicore/Daemon/src/CThread.cpp +++ b/mobicore/daemon/Common/CMutex.cpp @@ -1,5 +1,10 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Mutex implementation (pthread wrapper). + * + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -28,53 +33,54 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * Thread implementation (pthread abstraction). - */ +#include "CMutex.h" +#include "log.h" -#include - -#include - -#include "CThread.h" //------------------------------------------------------------------------------ -static void* thread_startup(void *arg) { - reinterpret_cast(arg)->run(); - return NULL; +CMutex::CMutex( + void +) +{ + pthread_mutex_init(&m_mutex, NULL); + pthread_cond_init(&m_cond, NULL); } -//------------------------------------------------------------------------------ -void CThread::terminate() { - m_terminate = true; -} //------------------------------------------------------------------------------ -bool CThread::shouldTerminate() { - return m_terminate; +CMutex::~CMutex( + void +) +{ + pthread_mutex_destroy(&m_mutex); + pthread_cond_destroy(&m_cond); } -//------------------------------------------------------------------------------ -void CThread::start(const char* name) { - int ret; - ret = pthread_create(&m_thread, NULL, thread_startup, this); - if (0 != ret) - LOG_E("pthread_create failed with error code %d", ret); - ret = pthread_setname_np(m_thread, name); - if (0 != ret) - LOG_E("pthread_setname_np failed with error code %d %s", ret, name); +//------------------------------------------------------------------------------ +int32_t CMutex::lock( + void +) +{ + return pthread_mutex_lock(&m_mutex); } + //------------------------------------------------------------------------------ -void CThread::join() { - int ret; - ret = pthread_join(m_thread, NULL); - if (0 != ret) - LOG_E("pthread_join failed with error code %d", ret); +int32_t CMutex::trylock( + void +) +{ + return pthread_mutex_trylock(&m_mutex); } + //------------------------------------------------------------------------------ -int CThread::kill(int sig) { - return pthread_kill(m_thread, sig); +int32_t CMutex::unlock( + void +) +{ + return pthread_mutex_unlock(&m_mutex); } + +/** @} */ diff --git a/mobicore/daemon/Common/CMutex.h b/mobicore/daemon/Common/CMutex.h new file mode 100644 index 0000000..22beacb --- /dev/null +++ b/mobicore/daemon/Common/CMutex.h @@ -0,0 +1,67 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Mutex implementation (pthread wrapper). + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 CMUTEX_H_ +#define CMUTEX_H_ + +#include +#include "pthread.h" + + +class CMutex +{ + +public: + + CMutex(void); + + ~CMutex(void); + + int32_t lock(void); + + int32_t trylock(void); + + int32_t unlock(void); + +private: + + pthread_mutex_t m_mutex; + pthread_cond_t m_cond; + +}; + +#endif /* CMUTEX_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Common/CSemaphore.cpp b/mobicore/daemon/Common/CSemaphore.cpp new file mode 100644 index 0000000..efa06c4 --- /dev/null +++ b/mobicore/daemon/Common/CSemaphore.cpp @@ -0,0 +1,116 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Semaphore implementation (pthread wrapper). + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include +#include +#include "CSemaphore.h" +#include + +//------------------------------------------------------------------------------ +CSemaphore::CSemaphore(int size) : m_waiters_count(0), m_count(size) +{ + pthread_mutex_init(&m_mutex, NULL); + pthread_cond_init(&m_cond, NULL); +} + + +//------------------------------------------------------------------------------ +CSemaphore::~CSemaphore() +{ + pthread_mutex_destroy(&m_mutex); + pthread_cond_destroy(&m_cond); +} + + +//------------------------------------------------------------------------------ +void CSemaphore::wait() +{ + pthread_mutex_lock(&m_mutex); + m_waiters_count ++; + while ( m_count == 0 ) + pthread_cond_wait(&m_cond, &m_mutex); + m_waiters_count --; + m_count --; + pthread_mutex_unlock(&m_mutex); +} + +//------------------------------------------------------------------------------ +bool CSemaphore::wait(int sec) +{ + int rc = 0; + struct timespec tm; + if (sec < 0) + sec = LONG_MAX; + clock_gettime(CLOCK_REALTIME, &tm); + tm.tv_sec += sec; + + pthread_mutex_lock(&m_mutex); + m_waiters_count ++; + if ( m_count == 0 ) { + rc = pthread_cond_timedwait(&m_cond, &m_mutex, &tm); + } + m_waiters_count --; + // Decrement only if waiting actually succeeded, otherwise we + // just timed out + if (!rc) + m_count --; + pthread_mutex_unlock(&m_mutex); + return (rc == 0); +} + + +//------------------------------------------------------------------------------ +bool CSemaphore::wouldWait() +{ + bool ret = false; + pthread_mutex_lock(&m_mutex); + if ( m_count == 0 ) + ret = true; + pthread_mutex_unlock(&m_mutex); + return ret; +} + + +//------------------------------------------------------------------------------ +void CSemaphore::signal() +{ + pthread_mutex_lock(&m_mutex); + if ( m_waiters_count > 0 ) + pthread_cond_signal(&m_cond); + m_count ++; + pthread_mutex_unlock(&m_mutex); +} + +/** @} */ diff --git a/mobicore/daemon/Common/CSemaphore.h b/mobicore/daemon/Common/CSemaphore.h new file mode 100644 index 0000000..fa08b70 --- /dev/null +++ b/mobicore/daemon/Common/CSemaphore.h @@ -0,0 +1,74 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Semaphore implementation (pthread wrapper). + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 CSEMAPHORE_H_ +#define CSEMAPHORE_H_ + +#include "pthread.h" + +/** + * Could inherit from CMutex, or use CMutex internally. + * Semaphore is a mutex with a counter. Constructor and destructor + * code is the same. + */ + +class CSemaphore +{ + +public: + + CSemaphore(int size = 0); + + ~CSemaphore(void); + + void wait(void); + bool wait(int sec); + + bool wouldWait(void); + + void signal(void); + +private: + + pthread_mutex_t m_mutex; + pthread_cond_t m_cond; + int m_waiters_count; + int m_count; + +}; + +#endif /*CSEMAPHORE_H_*/ + +/** @} */ diff --git a/mobicore/daemon/Common/CThread.cpp b/mobicore/daemon/Common/CThread.cpp new file mode 100644 index 0000000..ffccfbd --- /dev/null +++ b/mobicore/daemon/Common/CThread.cpp @@ -0,0 +1,166 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Thread implementation (pthread abstraction). + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include "CThread.h" + +#include "log.h" + + +//------------------------------------------------------------------------------ +CThread::CThread(void) : + m_terminate(false), m_isExiting(false) +{ + m_sem = new CSemaphore(); + m_thread=0; +} + +//------------------------------------------------------------------------------ +CThread::~CThread( + void +) +{ + delete m_sem; +} + + +//------------------------------------------------------------------------------ +void CThread::terminate( + void +) +{ + m_terminate = true; +} + + +//------------------------------------------------------------------------------ +bool CThread::isExiting( + void +) +{ + return m_isExiting; +} + + +//------------------------------------------------------------------------------ +void CThread::setExiting( + void +) +{ + m_isExiting = true; +} + + +//------------------------------------------------------------------------------ +void CThread::exit( + int32_t exitcode +) +{ + setExiting(); + pthread_exit((void *)(uintptr_t)exitcode); +} + + +//------------------------------------------------------------------------------ +bool CThread::shouldTerminate( + void +) +{ + return m_terminate; +} + + +//------------------------------------------------------------------------------ +void CThread::start( + void +) +{ + int ret; + ret = pthread_create(&m_thread, NULL, CThreadStartup, this); + if (0 != ret) + LOG_E("pthread_create failed with error code %d", ret); +} + +//------------------------------------------------------------------------------ +void CThread::start( + const char* name +) +{ + start(); + int ret = pthread_setname_np(m_thread, name); + if (0 != ret) + LOG_E("pthread_setname_np failed with error code %d %s", ret, name); +} + +//------------------------------------------------------------------------------ +void CThread::join( + void +) +{ + int ret; + ret = pthread_join(m_thread, NULL); + if (0 != ret) + LOG_E("pthread_join failed with error code %d", ret); +} + + +//------------------------------------------------------------------------------ +void CThread::sleep( + void +) +{ + m_sem->wait(); +} + + +//------------------------------------------------------------------------------ +void CThread::wakeup( + void +) +{ + m_sem->signal(); +} + + +//------------------------------------------------------------------------------ +void *CThreadStartup( + void *_tgtObject +) +{ + CThread *tgtObject = (CThread *) _tgtObject; + tgtObject->run(); + return NULL; +} + +/** @} */ diff --git a/mobicore/Daemon/src/CThread.h b/mobicore/daemon/Common/CThread.h similarity index 71% rename from mobicore/Daemon/src/CThread.h rename to mobicore/daemon/Common/CThread.h index 07028ed..ad2e4e7 100644 --- a/mobicore/Daemon/src/CThread.h +++ b/mobicore/daemon/Common/CThread.h @@ -1,5 +1,10 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Thread implementation (pthread abstraction). + * + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,24 +36,57 @@ #ifndef CTHREAD_H_ #define CTHREAD_H_ -#include +#include +#include "CSemaphore.h" +#include "pthread.h" + +using namespace std; + + +class CThread +{ -class CThread { public: - // m_thread value does not matter, only initialised for code checkers - CThread(): m_terminate(false), m_thread(pthread_self()) {} - virtual ~CThread() {} - virtual void run() = 0; + + CThread(void); + + virtual ~CThread(void); + + virtual void run(void) = 0; + + void start(void); + void start(const char* name); - void join(); - void terminate(); - int kill(int sig); + + void join(void); + + void sleep(void); + + void wakeup(void); + + void terminate(void); + + bool isExiting(void); + + void setExiting(void); + protected: - bool shouldTerminate(); + + bool shouldTerminate(void); + + void exit(int32_t exitcode); + private: - bool m_terminate; + + CSemaphore *m_sem; pthread_t m_thread; + bool m_terminate; + bool m_isExiting; + }; +extern "C" void *CThreadStartup(void *); + #endif /*CTHREAD_H_*/ +/** @} */ diff --git a/mobicore/daemon/Common/CWsm.h b/mobicore/daemon/Common/CWsm.h new file mode 100644 index 0000000..e43c058 --- /dev/null +++ b/mobicore/daemon/Common/CWsm.h @@ -0,0 +1,71 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * World shared memory definitions. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 CWSM_H_ +#define CWSM_H_ + +#include +#include +#include "McTypes.h" + + +class CWsm +{ +public: + addr_t virtAddr; + uint32_t len; + uint32_t handle; + uint64_t physAddr; + + CWsm(addr_t virtAddr, + uint32_t len, + uint32_t handle, + // this may be unknown, so is can be omitted. + uint64_t physAddr = 0) : + virtAddr(virtAddr), + len(len), + handle(handle), + physAddr(physAddr) + { }; + +}; + +typedef CWsm *CWsm_ptr; +typedef std::list wsmList_t; +typedef wsmList_t::iterator wsmIterator_t; + +#endif /* CWSM_H_ */ + +/** @} */ diff --git a/mobicore/Daemon/src/Connection.cpp b/mobicore/daemon/Common/Connection.cpp similarity index 52% rename from mobicore/Daemon/src/Connection.cpp rename to mobicore/daemon/Common/Connection.cpp index 8977617..48bcd07 100644 --- a/mobicore/Daemon/src/Connection.cpp +++ b/mobicore/daemon/Common/Connection.cpp @@ -1,5 +1,10 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection data. + * + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -28,76 +33,82 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * Connection data. - */ -#include #include #include #include #include -#include -#include -#include #include "Connection.h" +#include +#include +#include + +//#define LOG_VERBOSE +#include "log.h" + //------------------------------------------------------------------------------ -Connection::Connection(void): - m_socket(-1) +Connection::Connection(void) { + connectionData = NULL; + // Set invalid socketDescriptor + socketDescriptor = -1; + + detached = false; + + remote.sun_family = AF_UNIX; + memset(remote.sun_path, 0, sizeof(remote.sun_path)); } + //------------------------------------------------------------------------------ -Connection::Connection(int socketDescriptor): - m_socket(socketDescriptor) +Connection::Connection(int socketDescriptor, sockaddr_un *remote) { + assert(NULL != remote); assert(-1 != socketDescriptor); + + this->socketDescriptor = socketDescriptor; + this->remote = *remote; + connectionData = NULL; } + //------------------------------------------------------------------------------ Connection::~Connection(void) { - LOG_D("closing Connection... fd=%i", m_socket); - if (m_socket != -1) { - int ret = ::close(m_socket); - if(ret) + LOG_V(" closing Connection... fd=%i", socketDescriptor); + if (socketDescriptor != -1) { + int ret = close(socketDescriptor); + if(ret) { LOG_ERRNO("close"); + } } - LOG_D(" Socket connection closed."); + LOG_I(" Socket connection closed."); } + //------------------------------------------------------------------------------ bool Connection::connect(const char *dest) { - if (m_socket >= 0) { - LOG_E("Already connected"); - return false; - } + int32_t len; - struct sockaddr_un sockaddr; /**< Remote address */ - memset(&sockaddr, 0, sizeof(sockaddr)); - sockaddr.sun_family = AF_UNIX; - if (sizeof(sockaddr.sun_path) - 1 < strlen(dest)) { + assert(NULL != dest); + if (sizeof(remote.sun_path) - 1 < strlen(dest)) { LOG_E("Invalid destination socket %s", dest); return false; } - - LOG_D("Connecting to %s socket", dest); - sockaddr.sun_family = AF_UNIX; - memset(sockaddr.sun_path, 0, sizeof(sockaddr.sun_path)); - strncpy(sockaddr.sun_path, dest, strlen(dest)); - - m_socket = ::socket(AF_UNIX, SOCK_STREAM, 0); - if (m_socket < 0) { + LOG_I(" Connecting to %s socket", dest); + remote.sun_family = AF_UNIX; + memset(remote.sun_path, 0, sizeof(remote.sun_path)); + strncpy(remote.sun_path, dest, strlen(dest)); + if ((socketDescriptor = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { LOG_ERRNO("Can't open stream socket."); return false; } - - socklen_t len = static_cast(strlen(sockaddr.sun_path) + sizeof(sockaddr.sun_family)); + len = strlen(remote.sun_path) + sizeof(remote.sun_family); // The Daemon socket is in the Abstract Domain(LINUX ONLY!) - sockaddr.sun_path[0] = 0; - if (::connect(m_socket, reinterpret_cast(&sockaddr), len) < 0) { + remote.sun_path[0] = 0; + if (::connect(socketDescriptor, (struct sockaddr *) &remote, len) < 0) { LOG_ERRNO("connect()"); return false; } @@ -105,67 +116,24 @@ bool Connection::connect(const char *dest) return true; } + //------------------------------------------------------------------------------ -ssize_t Connection::readData(void *buffer, uint32_t len, int32_t timeout) +size_t Connection::readData(void *buffer, uint32_t len) { - ssize_t ret = 0; - struct timeval tv; - struct timeval *ptv = NULL; - fd_set readfds; - - if (timeout >= 0) { - // Calculate timeout value - tv.tv_sec = timeout / 1000; - tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000; - ptv = &tv; - } - - FD_ZERO(&readfds); - FD_SET(m_socket, &readfds); - ret = select(m_socket + 1, &readfds, NULL, NULL, ptv); - - // check for read error - if (ret == -1) { - LOG_ERRNO("select"); - return -1; - } - - // Handle case of no descriptor ready - if (ret == 0) { - LOG_W("Timeout during select() / No more notifications."); - return -2; - } - - // one or more descriptors are ready - - // finally check if fd has been selected -> must socketDescriptor - if (!FD_ISSET(m_socket, &readfds)) { - LOG_ERRNO("no fd is set, select"); - return ret; - } - - ret = recv(m_socket, buffer, len, MSG_DONTWAIT); - if (ret == 0) - LOG_D(" readData(): peer orderly closed connection."); - - return ret; + return readData(buffer, len, -1); } -ssize_t Connection::readMsg(const iovec *iov, uint32_t nr_seg, int32_t timeout) + +//------------------------------------------------------------------------------ +size_t Connection::readData(void *buffer, uint32_t len, int32_t timeout) { - ssize_t ret = -1; - struct msghdr msg; + size_t ret = 0; struct timeval tv; struct timeval *ptv = NULL; fd_set readfds; - memset(&msg, 0, sizeof(msg)); - msg.msg_name = NULL; - msg.msg_namelen = 0; - msg.msg_iov = const_cast(iov); - msg.msg_iovlen = nr_seg; - msg.msg_control = NULL; - msg.msg_controllen = 0; + assert(NULL != buffer); + assert(socketDescriptor != -1); if (timeout >= 0) { // Calculate timeout value @@ -175,92 +143,65 @@ ssize_t Connection::readMsg(const iovec *iov, uint32_t nr_seg, int32_t timeout) } FD_ZERO(&readfds); - FD_SET(m_socket, &readfds); - ret = select(m_socket + 1, &readfds, NULL, NULL, ptv); + FD_SET(socketDescriptor, &readfds); + ret = select(socketDescriptor + 1, &readfds, NULL, NULL, ptv); // check for read error - if (ret == -1) { + if ((int)ret == -1) { LOG_ERRNO("select"); return -1; } // Handle case of no descriptor ready if (ret == 0) { - LOG_W("Timeout during select() / No more notifications."); + LOG_W(" Timeout during select() / No more notifications."); return -2; } // one or more descriptors are ready // finally check if fd has been selected -> must socketDescriptor - if (!FD_ISSET(m_socket, &readfds)) { + if (!FD_ISSET(socketDescriptor, &readfds)) { LOG_ERRNO("no fd is set, select"); return ret; } - ret = recvmsg(m_socket, &msg, MSG_DONTWAIT); - if (ret == 0) - LOG_D("readData(): peer orderly closed connection."); + ret = recv(socketDescriptor, buffer, len, MSG_DONTWAIT); + if (ret == 0) { + LOG_V(" readData(): peer orderly closed connection."); + } return ret; } //------------------------------------------------------------------------------ -ssize_t Connection::writeData(const void *buffer, uint32_t len) -{ - const char *cbuf = static_cast(buffer); - uint32_t left = len; - while (left) { - ssize_t wlen = ::send(m_socket, cbuf, left, 0); - if (wlen < 0) { - LOG_ERRNO("writeData"); - return -1; - } - if (wlen == 0) { - LOG_E("Client closed the connection"); - return -1; - } - left -= wlen; - cbuf += wlen; - } - return len; -} - -ssize_t Connection::writeMsg(const iovec *iov, uint32_t nr_seg) +size_t Connection::writeData(void *buffer, uint32_t len) { - ssize_t ret = -1, len; - struct msghdr msg; - - memset(&msg, 0, sizeof(msg)); - msg.msg_name = NULL; - msg.msg_namelen = 0; - msg.msg_iov = const_cast(iov); - msg.msg_iovlen = nr_seg; - msg.msg_control = NULL; - msg.msg_controllen = 0; - - for( len = 0; nr_seg > 0; nr_seg--, iov++) - len += iov->iov_len; + assert(buffer != NULL); + assert(socketDescriptor != -1); - ret = sendmsg(m_socket, &msg, 0); + size_t ret = send(socketDescriptor, buffer, len, 0); if (ret != len) { - LOG_E("%s: could not send all data, ret=%zd, errno: %d (%s)", - __FUNCTION__, ret, errno, strerror(errno)); + LOG_ERRNO("could not send all data, because send"); + LOG_E("ret = %d", ret); ret = -1; } return ret; } + //------------------------------------------------------------------------------ int Connection::waitData(int32_t timeout) { - int ret; + size_t ret; struct timeval tv; struct timeval *ptv = NULL; fd_set readfds; + assert(socketDescriptor != -1); + if (timeout >= 0) { // Calculate timeout value tv.tv_sec = timeout / 1000; @@ -269,11 +210,11 @@ int Connection::waitData(int32_t timeout) } FD_ZERO(&readfds); - FD_SET(m_socket, &readfds); - ret = select(m_socket + 1, &readfds, NULL, NULL, ptv); + FD_SET(socketDescriptor, &readfds); + ret = select(socketDescriptor + 1, &readfds, NULL, NULL, ptv); // check for read error - if (ret == -1) { + if ((int)ret == -1) { LOG_ERRNO("select"); return ret; } else if (ret == 0) { @@ -287,9 +228,10 @@ int Connection::waitData(int32_t timeout) //------------------------------------------------------------------------------ bool Connection::isConnectionAlive(void) { + assert(socketDescriptor != -1); int retval; struct pollfd ufds[1]; - ufds[0].fd = m_socket; + ufds[0].fd = socketDescriptor; ufds[0].events = POLLRDHUP; retval = poll(ufds, 1, 10); @@ -299,3 +241,23 @@ bool Connection::isConnectionAlive(void) } return true; } + +//------------------------------------------------------------------------------ +bool Connection::getPeerCredentials(struct ucred &cr) +{ + struct ucred cred; + socklen_t len = sizeof (cred); + assert(socketDescriptor != -1); + int ret = getsockopt(socketDescriptor, SOL_SOCKET, SO_PEERCRED, &cred, + &len); + if (ret != 0) { + LOG_ERRNO("getsockopt"); + return false; + } + if (len == sizeof(cred)) { + cr = cred; + return true; + } + return false; +} +/** @} */ diff --git a/mobicore/Daemon/src/Connection.h b/mobicore/daemon/Common/Connection.h similarity index 65% rename from mobicore/Daemon/src/Connection.h rename to mobicore/daemon/Common/Connection.h index 3503052..89bc585 100644 --- a/mobicore/Daemon/src/Connection.h +++ b/mobicore/daemon/Common/Connection.h @@ -1,5 +1,10 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection data. + * + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,15 +36,29 @@ #ifndef CONNECTION_H_ #define CONNECTION_H_ -#include // iovec +#include +#include + +#include + +#include +#include +#include + class Connection { public: + struct sockaddr_un remote; /**< Remote address */ + int32_t socketDescriptor; /**< Local socket descriptor */ + void *connectionData; /**< reference to data related with the connection */ + bool detached; /**< Connection state */ + Connection(void); - Connection(int socketDescriptor); - ~Connection(void); + Connection(int socketDescriptor, sockaddr_un *remote); + + virtual ~Connection(void); /** * Connect to destination. @@ -47,7 +66,7 @@ public: * @param Destination pointer. * @return true on success. */ - bool connect(const char *dest); + virtual bool connect(const char *dest); /** * Read bytes from the connection. @@ -59,8 +78,17 @@ public: * @return -1 if select() failed (returned -1) * @return -2 if no data available, i.e. timeout */ - ssize_t readData(void *buffer, uint32_t len, int32_t timeout = -1); - ssize_t readMsg(const iovec *iov, uint32_t nr_seg, int32_t timeout = -1); + virtual size_t readData(void *buffer, uint32_t len, int32_t timeout); + + /** + * Read bytes from the connection. + * + * @param buffer Pointer to destination buffer. + * @param len Number of bytes to read. + * @return Number of bytes read. + */ + virtual size_t readData(void *buffer, uint32_t len); + /** * Write bytes to the connection. * @@ -69,8 +97,7 @@ public: * @return Number of bytes written. * @return -1 if written bytes not equal to len. */ - ssize_t writeData(const void *buffer, uint32_t len); - ssize_t writeMsg(const iovec *iov, uint32_t nr_seg); + virtual size_t writeData(void *buffer, uint32_t len); /** * Wait for data to be available. @@ -79,23 +106,28 @@ public: * @return 0 if data is available * @return error code if otherwise */ - int waitData(int32_t timeout); + virtual int waitData(int32_t timeout); /* * Checks if the socket is still connected to the daemon * * @return true if connection is still alive. */ - bool isConnectionAlive(void); + virtual bool isConnectionAlive(void); - int socket() const - { - return m_socket; - } + /* + * Retrieve the peer's credentials(uid, pid, gid) + * + * @return true if connection peers could be retrieved + */ + virtual bool getPeerCredentials(struct ucred &cr); -private: - int m_socket; /**< Local socket descriptor */ }; +typedef std::list connectionList_t; +typedef connectionList_t::iterator connectionIterator_t; + + #endif /* CONNECTION_H_ */ +/** @} */ diff --git a/mobicore/TuiService/src/com/trustonic/tuiapi/TUI_EventData.java b/mobicore/daemon/Common/McTypes.h similarity index 89% rename from mobicore/TuiService/src/com/trustonic/tuiapi/TUI_EventData.java rename to mobicore/daemon/Common/McTypes.h index 3351484..6e8989e 100644 --- a/mobicore/TuiService/src/com/trustonic/tuiapi/TUI_EventData.java +++ b/mobicore/daemon/Common/McTypes.h @@ -1,4 +1,9 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * MobiCore types redefinition. + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -28,13 +33,11 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#ifndef MCTYPES_H_ +#define MCTYPES_H_ -package com.trustonic.tuiapi; - -public class TUI_EventData { +typedef void *addr_t; - public TUI_EventData() { - // TODO Auto-generated constructor stub - } +#endif /* MCTYPES_H_ */ -} +/** @} */ diff --git a/mobicore/daemon/Common/NetlinkConnection.cpp b/mobicore/daemon/Common/NetlinkConnection.cpp new file mode 100644 index 0000000..54aabd6 --- /dev/null +++ b/mobicore/daemon/Common/NetlinkConnection.cpp @@ -0,0 +1,295 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection data. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "NetlinkConnection.h" + +#include "log.h" + + +uint64_t hashConnection( + pid_t pid, + uint32_t seq +) +{ + return (((uint64_t)seq) << 32) | (uint64_t)pid; +} + + +//------------------------------------------------------------------------------ +NetlinkConnection::NetlinkConnection( + void +) : Connection(), + dataLeft(0), + manager(NULL) +{ + detached = false; + dataMsg = NULL; + dataStart = NULL; + dataLen = 0; + + + selfPid = getpid(); + peerPid = 0; + sequenceMagic = 0; + hash = hashConnection(peerPid, sequenceMagic); +} + + +//------------------------------------------------------------------------------ +NetlinkConnection::NetlinkConnection( + NetlinkConnectionManager *manager, + int socketDescriptor, + uint32_t pid, + uint32_t seq +): Connection(), + dataLeft(0), + manager(manager) +{ + detached = false; + dataMsg = NULL; + dataStart = NULL; + dataLen = 0; + + this->socketDescriptor = socketDescriptor; + selfPid = getpid(); + peerPid = pid; + sequenceMagic = seq; + hash = hashConnection(pid, seq); +} + + +//------------------------------------------------------------------------------ +NetlinkConnection::~NetlinkConnection( + void +) +{ + LOG_I("%s: destroy connection for PID 0x%X", __FUNCTION__, peerPid); + socketDescriptor = -1; + free(dataMsg); + + if (manager) { + manager->removeConnection(hash); + } +} + + +//------------------------------------------------------------------------------ +bool NetlinkConnection::connect( + const char *dest __unused +) +{ + struct sockaddr_nl addr; + bool ret = false; + + assert(NULL != dest); + + 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)", + __FUNCTION__, errno, strerror(errno)); + break; + } + memset(&addr, 0, sizeof(addr)); + addr.nl_family = AF_NETLINK; + addr.nl_pid = selfPid; /* self pid */ + 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)", __FUNCTION__, errno, strerror(errno)); + close(socketDescriptor); + + // Set invalid socketDescriptor + socketDescriptor = -1; + break; + } + ret = true; + + + } while (false); + + return ret; +} + + +//------------------------------------------------------------------------------ +void NetlinkConnection::handleMessage( + struct nlmsghdr *nlh +) +{ + dataMutex.lock(); + /* Takeover the buffer */ + dataMsg = nlh; + dataLen = NLMSG_PAYLOAD(dataMsg, 0); + dataStart = static_cast(NLMSG_DATA(dataMsg)); + dataMutex.unlock(); + dataLeft.signal(); +} + +//------------------------------------------------------------------------------ +size_t NetlinkConnection::readData( + void *buffer, + uint32_t len +) +{ + return readData(buffer, len, -1); +} + + +//------------------------------------------------------------------------------ +size_t NetlinkConnection::readData( + void *buffer, + uint32_t len, + int32_t timeout +) +{ + size_t ret = -1; + assert(NULL != buffer); + + if (!dataLeft.wait(timeout)) { + return -2; + } + dataMutex.lock(); + // No data left?? Could we get this far? + if (dataLen <= 0) { + dataMutex.unlock(); + return -2; + } + + //LOG_I("%s: reading connection data %u, connection data left %u", + // __FUNCTION__, len, dataLen); + + assert(dataStart != NULL); + + // trying to read more than the left data + if (len > dataLen) { + ret = dataLen; + memcpy(buffer, dataStart, dataLen); + dataLen = 0; + } else { + ret = len; + memcpy(buffer, dataStart, len); + dataLen -= len; + dataStart += len; + } + + if (dataLen == 0) { + dataStart = NULL; + free(dataMsg); + dataMsg = NULL; + } else { + // Still some data left + dataLeft.signal(); + } + dataMutex.unlock(); + + //LOG_I("%s: read %u", __FUNCTION__, ret); + return ret; +} + +//------------------------------------------------------------------------------ +size_t NetlinkConnection::writeData( + void *buffer, + uint32_t len +) +{ + size_t ret; + struct sockaddr_nl dest_addr; + struct nlmsghdr *nlh = NULL; + struct iovec iov; + struct msghdr msg; + + assert(NULL != buffer); + assert(-1 != socketDescriptor); + + //LOG_I("%s: send data %u to PID %u", __FUNCTION__, len, sequenceMagic); + + memset(&dest_addr, 0, sizeof(dest_addr)); + memset(&msg, 0, sizeof(msghdr)); + dest_addr.nl_family = AF_NETLINK; + dest_addr.nl_pid = peerPid; + dest_addr.nl_groups = 0; /* unicast */ + + nlh = (struct nlmsghdr *)malloc( + NLMSG_SPACE(len)); + if (nlh == NULL) { + LOG_E("Allocation failure"); + return -1; + } + + /* Fill the netlink message header */ + nlh->nlmsg_len = NLMSG_SPACE(len); + nlh->nlmsg_pid = selfPid; + nlh->nlmsg_flags = NLM_F_REQUEST; + nlh->nlmsg_seq = sequenceMagic; + + /* Fill in the netlink message payload */ + memcpy(NLMSG_DATA(nlh), buffer, len); + + iov.iov_base = (void *)nlh; + iov.iov_len = nlh->nlmsg_len; + msg.msg_name = (void *)&dest_addr; + msg.msg_namelen = sizeof(dest_addr); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = NULL; + msg.msg_controllen = 0; + + ret = sendmsg(socketDescriptor, &msg, 0); + if (ret != NLMSG_SPACE(len)) { + LOG_E( "%s: could no send all data, ret=%d, errno: %d(%s)", + __FUNCTION__, ret, errno, strerror(errno)); + ret = -1; + } else { + /* The whole message sent also includes the header, so make sure to + * return only the number of payload data sent, not everything */ + ret = len; + } + + free(nlh); + + return ret; +} + +/** @} */ diff --git a/mobicore/daemon/Common/NetlinkConnection.h b/mobicore/daemon/Common/NetlinkConnection.h new file mode 100644 index 0000000..5be3f30 --- /dev/null +++ b/mobicore/daemon/Common/NetlinkConnection.h @@ -0,0 +1,223 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection data. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 NETLINKCONNECTION_H_ +#define NETLINKCONNECTION_H_ + +#include +#include +#include +#include + +#include +#include +#include + +#include "Connection.h" +#include "CMutex.h" +#include "CSemaphore.h" + +/** PID(address) of MC daemon. */ +#define MC_DAEMON_PID 0xFFFFFFFF +/** Maximum Netlink payload size + * TODO: figure out the best value for this */ +#define MAX_PAYLOAD 1024 + +#define MC_DAEMON_NETLINK 17 + + +class NetlinkConnection; + +/** + * Hash function for unique ID of a connection. + * + * @param pid Connection PID + * @param seq Connection sequenceMagic + * + * @return Unique identifier of the connection + */ +uint64_t hashConnection(pid_t pid, uint32_t seq); + +/** Netlink connection manager interface. + * This inteface has to be implemented by the handling server + * to ensure connection will be removed from accounting when destroied. */ +class NetlinkConnectionManager +{ +public: + virtual ~NetlinkConnectionManager() {}; + /** + * Retreive connection based on a unique hash. + * Search the peer connections hashmap for a hash and return + * the associated Connection object + * + * @param hash The hash to search + * @return The NetlinkConnection object if found or NULL if not found + */ + virtual NetlinkConnection *findConnection( + uint64_t hash + ) = 0; + + /** + * Insert a connection in connection lisst + * Insert a new connection in the peer connections list. If there + * is already such a connection + * it will be overriden! + * + * @param hash The hash to use + * @param connection The connection object to insert + */ + virtual void insertConnection( + uint64_t hash, + NetlinkConnection *connection + ) = 0; + + /** + * Remove a connection from the peer connections + * Remove the connection associated with seq from the peer list. + * This doesn't actually free the connection object! + * If the hash is invalid nothing happens. + * + * @param hash The hash hash use + */ + virtual void removeConnection( + uint64_t hash + ) = 0; +}; + +class NetlinkConnection: public Connection +{ +public: + pid_t selfPid; /**< Which PID to use to identify when writing data */ + pid_t peerPid; /**< Destination PID for sending data */ + uint32_t sequenceMagic; /**< Random? magic to match requests/answers */ + uint64_t hash; /**< Unique connection ID, see hashConnection */ + + NetlinkConnection( + void + ); + + /** + * Connection main constructor + * + * @param manager Connection manager pointer. + * @param socketDescriptor Socket descriptor to use for writing + * @param pid Connection PID + * @param seq Connection sequence magic number + */ + NetlinkConnection( + NetlinkConnectionManager *manager, + int socketDescriptor, + uint32_t pid, + uint32_t seq + ); + + virtual ~NetlinkConnection( + void + ); + + /** + * Connect to destination. + * + * @param Destination pointer. + * @return true on success. + */ + virtual bool connect( + const char *dest + ); + + /** + * Read bytes from the connection(compatiblity method). + * + * @param buffer Pointer to destination buffer. + * @param len Number of bytes to read. + * @param timeout Timeout in milliseconds(ignored) + * @return Number of bytes read. + * @return -1 if select() failed (returned -1) + * @return -2 if no data available, i.e. timeout + */ + virtual size_t readData( + void *buffer, + uint32_t len, + int32_t timeout + ); + + /** + * Read bytes from the connection. + * + * @param buffer Pointer to destination buffer. + * @param len Number of bytes to read. + * @return Number of bytes read. + */ + virtual size_t readData( + void *buffer, + uint32_t len + ); + + /** + * Write bytes to the connection. + * + * @param buffer Pointer to source buffer. + * @param len Number of bytes to read. + * @return Number of bytes written. + */ + virtual size_t writeData( + void *buffer, + uint32_t len + ); + + /** + * Set the internal data connection. + * This method is called by the + * + * @param nlh Netlink structure pointing to data. + */ + void handleMessage( + struct nlmsghdr *nlh + ); + +private: + CMutex dataMutex; + CSemaphore dataLeft; + struct nlmsghdr *dataMsg; /**< Last message received */ + uint32_t dataLen; /**< How much connection data is left */ + uint8_t *dataStart; /**< Start pointer of remaining data */ + NetlinkConnectionManager *manager; /**< Netlink connection manager(eg. NetlinkServer) */ +}; + +typedef std::map connectionMap_t; + +#endif /* NETLINKCONNECTION_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Android.mk b/mobicore/daemon/Daemon/Android.mk new file mode 100644 index 0000000..e9873bd --- /dev/null +++ b/mobicore/daemon/Daemon/Android.mk @@ -0,0 +1,19 @@ +# ============================================================================= +# +# Module: mcDriverDaemon +# +# ============================================================================= + +# Add new source files here +LOCAL_SRC_FILES += Daemon/MobiCoreDriverDaemon.cpp + +# Includes required for the Daemon +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Daemon/public + +# Ignore non-reproducible date/time expansions +LOCAL_CFLAGS += -Wno-date-time + +# Internal components +include $(LOCAL_PATH)/Daemon/Device/Android.mk +include $(LOCAL_PATH)/Daemon/Server/Android.mk +include $(LOCAL_PATH)/Daemon/FSD/Android.mk diff --git a/mobicore/daemon/Daemon/Device/Android.mk b/mobicore/daemon/Daemon/Device/Android.mk new file mode 100644 index 0000000..6a22222 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/Android.mk @@ -0,0 +1,25 @@ +# ============================================================================= +# +# MC driver device files +# +# ============================================================================= + +# This is not a separate module. +# Only for inclusion by other modules. +# All paths are relative to APP_PROJECT_PATH + +DEVICE_PATH := Daemon/Device +include $(LOCAL_PATH)/$(DEVICE_PATH)/Platforms/Android.mk + +# Add new folders with header files here +# 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 += $(DEVICE_PATH)/DeviceIrqHandler.cpp \ + $(DEVICE_PATH)/DeviceScheduler.cpp \ + $(DEVICE_PATH)/TAExitHandler.cpp \ + $(DEVICE_PATH)/MobiCoreDevice.cpp \ + $(DEVICE_PATH)/NotificationQueue.cpp \ + $(DEVICE_PATH)/TrustletSession.cpp diff --git a/mobicore/TuiService/src/com/trustonic/tuiapi/TUI_EventType.java b/mobicore/daemon/Daemon/Device/DeviceIrqHandler.cpp similarity index 84% rename from mobicore/TuiService/src/com/trustonic/tuiapi/TUI_EventType.java rename to mobicore/daemon/Daemon/Device/DeviceIrqHandler.cpp index a10b1b1..877e2da 100644 --- a/mobicore/TuiService/src/com/trustonic/tuiapi/TUI_EventType.java +++ b/mobicore/daemon/Daemon/Device/DeviceIrqHandler.cpp @@ -1,4 +1,8 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -29,19 +33,16 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package com.trustonic.tuiapi; - -public class TUI_EventType { +#include "DeviceIrqHandler.h" +#include "log.h" - private int is; - public static int TUI_UNKNOW_EVENT = 0; - public static int TUI_CANCEL_EVENT = 1; - - public TUI_EventType(int type) { - this.is = type; - } - - public int is(){ - return this.is; - } +//------------------------------------------------------------------------------ +void DeviceIrqHandler::run( + void +) +{ + handleIrq(); + this->exit(-1); } + +/** @} */ diff --git a/mobicore/tlcm/TlCm/version.h b/mobicore/daemon/Daemon/Device/DeviceIrqHandler.h similarity index 83% rename from mobicore/tlcm/TlCm/version.h rename to mobicore/daemon/Daemon/Device/DeviceIrqHandler.h index c91b71c..449e2af 100644 --- a/mobicore/tlcm/TlCm/version.h +++ b/mobicore/daemon/Daemon/Device/DeviceIrqHandler.h @@ -1,4 +1,9 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * IRQ handler thread. + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -28,20 +33,23 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** @addtogroup CMP_COMMON - * @{ - * @file - * Content management trustlet (TlCm) version definition. - */ -#ifndef CMP_VERSION_H_ -#define CMP_VERSION_H_ +#ifndef DEVICEIRQHANDLER_H_ +#define DEVICEIRQHANDLER_H_ + +#include "CThread.h" + + +class DeviceIrqHandler: public CThread +{ + +public: + + virtual void handleIrq() = 0; -/** Latest supported CMP major version number. */ -#define CMP_VERSION_MAJOR 3 -/** Latest supported CMP minor version number. */ -#define CMP_VERSION_MINOR 0 + void run(); +}; -#endif // CMP_VERSION_H_ +#endif /* DEVICEIRQHANDLER_H_ */ /** @} */ diff --git a/mobicore/tlcm/TlCm/tlCmUuid.h b/mobicore/daemon/Daemon/Device/DeviceScheduler.cpp similarity index 86% rename from mobicore/tlcm/TlCm/tlCmUuid.h rename to mobicore/daemon/Daemon/Device/DeviceScheduler.cpp index c433756..1481c3c 100644 --- a/mobicore/tlcm/TlCm/tlCmUuid.h +++ b/mobicore/daemon/Daemon/Device/DeviceScheduler.cpp @@ -1,4 +1,8 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -28,18 +32,17 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** @addtogroup CMP_COMMON - * @{ - * @file - * Content management trustlet (TlCm) Uuid definition. - */ -#ifndef TL_CM_UUID_H -#define TL_CM_UUID_H +#include "DeviceScheduler.h" -/** Uuid of TlCm. */ -#define TL_CM_UUID { { 7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } } -#endif // TL_CM_UUID_H +//------------------------------------------------------------------------------ +void DeviceScheduler::run( + void +) +{ + schedule(); + exit(-1); +} /** @} */ diff --git a/mobicore/daemon/Daemon/Device/DeviceScheduler.h b/mobicore/daemon/Daemon/Device/DeviceScheduler.h new file mode 100644 index 0000000..3b818bf --- /dev/null +++ b/mobicore/daemon/Daemon/Device/DeviceScheduler.h @@ -0,0 +1,56 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * Scheduler thread + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 DEVICESCHEDULER_H_ +#define DEVICESCHEDULER_H_ + +#include "CThread.h" + + +class DeviceScheduler: public CThread +{ + +public: + + virtual void schedule() = 0; + + void run(); + +}; + +#endif /* DEVICESCHEDULER_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp b/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp new file mode 100644 index 0000000..009e2f4 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/MobiCoreDevice.cpp @@ -0,0 +1,931 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + */ + +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ + +#include +#include +#include +#include "McTypes.h" + +#include "DeviceScheduler.h" +#include "DeviceIrqHandler.h" +#include "ExcDevice.h" +#include "Connection.h" +#include "TrustletSession.h" + +#include "MobiCoreDevice.h" +#include "Mci/mci.h" +#include "mcLoadFormat.h" + + +#include "log.h" +#include "public/MobiCoreDevice.h" + + + +//------------------------------------------------------------------------------ +MobiCoreDevice::MobiCoreDevice() +{ + nq = NULL; + mcFlags = NULL; + mcVersionInfo = NULL; + mcFault = false; + mciReused = false; + mcpMessage = NULL; +} + +//------------------------------------------------------------------------------ +MobiCoreDevice::~MobiCoreDevice() +{ + mciReused = false; + mcFault = false; + delete mcVersionInfo; + mcVersionInfo = NULL; + mcFlags = NULL; + nq = NULL; +} + +//------------------------------------------------------------------------------ +TrustletSession *MobiCoreDevice::getTrustletSession( + uint32_t sessionId +) { + for (trustletSessionIterator_t iterator = trustletSessions.begin(); + iterator != trustletSessions.end(); + ++iterator) + { + TrustletSession *session = *iterator; + if (session->sessionId == sessionId) { + return session; + } + } + return NULL; +} + + +//------------------------------------------------------------------------------ +Connection *MobiCoreDevice::getSessionConnection( + uint32_t sessionId, + notification_t *notification +) { + Connection *con = NULL; + + TrustletSession *session = getTrustletSession(sessionId); + if (session != NULL) + { + con = session->notificationConnection; + if (con == NULL) + { + session->queueNotification(notification); + } + } + + return con; +} + + +//------------------------------------------------------------------------------ +TrustletSession* MobiCoreDevice::findSession( + Connection *deviceConnection, + uint32_t sessionId +) { + TrustletSession *session = getTrustletSession(sessionId); + if (session == NULL) + { + LOG_E("no session found with id=%d", sessionId); + } + else + { + // check is connection own this session + if (session->deviceConnection != deviceConnection) + { + LOG_E("connection does not own session id=%d", sessionId); + session = NULL; + } + } + return session; +} + + +//------------------------------------------------------------------------------ +bool MobiCoreDevice::open( + Connection *connection +) { + // Link this device to the connection + connection->connectionData = this; + return true; +} + +//------------------------------------------------------------------------------ +// send a close session message. Used in three cases: +// 1) during init to tell SWd to invalidate this session, if it is still open +// from a prev Daemon instance +// 2) normal session close +// 3) close all session when Daemon terminates +mcResult_t MobiCoreDevice::sendSessionCloseCmd( + uint32_t sessionId +) { + // Write MCP close message to buffer + mcpMessage->cmdClose.cmdHeader.cmdId = MC_MCP_CMD_CLOSE_SESSION; + mcpMessage->cmdClose.sessionId = sessionId; + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for CLOSE_SESSION, code %d.", mcRet); + return mcRet; + } + + // Check if the command response ID is correct + if ((MC_MCP_CMD_CLOSE_SESSION | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) { + LOG_E("invalid MCP response for CLOSE_SESSION"); + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + // Read MC answer from MCP buffer + mcRet = mcpMessage->rspOpen.rspHeader.result; + + return mcRet; +} + +//------------------------------------------------------------------------------ +// internal API to close a session +mcResult_t MobiCoreDevice::closeSessionInternal( + TrustletSession *session +) { + LOG_I("closing session with id=%d", session->sessionId); + + mcResult_t mcRet = sendSessionCloseCmd(session->sessionId); + if (mcRet != MC_MCP_RET_OK) { + LOG_E("sendSessionCloseCmd error %d", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + +// // clean session WSM +// LOG_I("unlocking session buffers!"); +// CWsm_ptr pWsm = session->popBulkBuff(); +// while (pWsm) +// { +// unlockWsmL2(pWsm->handle); +// delete pWsm; +// pWsm = session->popBulkBuff(); +// } + + return MC_DRV_OK; +} + +//------------------------------------------------------------------------------ +/** + * Close device. + * + * Removes all sessions to a connection. Though, clientLib rejects the closeDevice() + * command if still sessions connected to the device, this is needed to clean up all + * sessions if client dies. + */ +void MobiCoreDevice::close( + Connection *connection +) { + // static mutex is the the same for each thread. So this serializes + // multiple connections failing at the same time. + static CMutex mutex; + // Enter critical section + mutex.lock(); + + // 1. Iterate through device session to find connection + // 2. Decide what to do with open Trustlet sessions + // 3. Remove & delete deviceSession from vector + + // iterating over the list in reverse order, as the LIFO approach may + // avoid some quirks. The assumption is that a driver is opened before a + // TA, so we want to terminate the TA first and then the driver. This may + // make this a bit easier for everbody. + + trustletSessionList_t::reverse_iterator revIt = trustletSessions.rbegin(); + while (revIt != trustletSessions.rend()) + { + TrustletSession *session = *revIt; + + // wiredness of reverse iterators + // * is is incremented to get the next lowe element + // * to delete something from the list, we need the "normal" iterator. + // This is simpy "one off" the current revIt. So we can savely use + // the increment below in both cases. + revIt++; + + if (session->deviceConnection == connection) + { + // close session, log any error but ignore it. + //mcResult_t mcRet = closeSessionInternal(session); + mcResult_t mcRet = closeSession(connection, session->sessionId); + if (mcRet != MC_MCP_RET_OK) { + LOG_I("device closeSession failed with %d", mcRet); + } + + // removing an element from the list it tricky. Convert the revIt + // to a "normal" iterator. Remember here that the revIt is one off, + // but we have done an increment above, so we are fine here. So + // after we have the normal iterator, ude it to delete and then + // convert the returned iterator back to a reverse iterator, which + // we will use for the loop. + //trustletSessionIterator_t it = revIt.base(); + //it = trustletSessions.erase(it); // delete + //revIt = trustletSessionList_t::reverse_iterator(it); + + // free object + //delete session; + } + } + + // Leave critical section + mutex.unlock(); + + // After the trustlet is done make sure to tell the driver to cleanup + // all the orphaned drivers + cleanupWsmL2(); + + + + connection->connectionData = NULL; + + // Leave critical section + mutex.unlock(); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDevice::start(void) +{ + LOG_I("Starting DeviceIrqHandler..."); + // Start the irq handling thread + DeviceIrqHandler::start("DevIrqHandler"); + + if (schedulerAvailable()) + { + LOG_I("Starting DeviceScheduler..."); + // Start the scheduling handling thread + DeviceScheduler::start(); + } + else + { + LOG_I("No DeviceScheduler available."); + } + + LOG_I("Starting TAExitHandler..."); + TAExitHandler::start("TAExitHandler"); + + if (mciReused) + { + // remove all pending sessions. 20 is as good a any other number, we- + // actually should ass a MCP message that tells SWd to invalidate all- + // session that are there besides the MSH session. + for (int sessionId = 2; sessionId<20; sessionId++) { + LOG_I("invalidating session %d",sessionId); + mcResult_t mcRet = sendSessionCloseCmd(sessionId); + if (mcRet != MC_MCP_RET_OK) { + LOG_I("sendSessionCloseCmd error %d", mcRet); + } + } + } + + return; +} + + +//------------------------------------------------------------------------------ +void MobiCoreDevice::signalMcpNotification(void) +{ + mcpSessionNotification.signal(); +} + + +//------------------------------------------------------------------------------ +bool MobiCoreDevice::waitMcpNotification(void) +{ + int counter = 5; // retry 5 times + while (1) + { + // In case of fault just return, nothing to do here + if (mcFault) + { + return false; + } + // Wait 10 seconds for notification + if ( mcpSessionNotification.wait(10) ) + { + break; // seem we got one. + } + // No MCP answer received and mobicore halted, dump mobicore status + // then throw exception + LOG_I("No MCP answer received in 2 seconds."); + if (getMobicoreStatus() == MC_STATUS_HALT) + { + dumpMobicoreStatus(); + mcFault = true; + return false; + } + + counter--; + if (counter < 1) + { + mcFault = true; + return false; + } + } // while(1) + + // Check healthiness state of the device + if (DeviceIrqHandler::isExiting()) { + LOG_I("waitMcpNotification(): IrqHandler thread died! Joining"); + DeviceIrqHandler::join(); + LOG_I("waitMcpNotification(): Joined"); + LOG_E("IrqHandler thread died!"); + return false; + } + + if (DeviceScheduler::isExiting()) { + LOG_I("waitMcpNotification(): Scheduler thread died! Joining"); + DeviceScheduler::join(); + LOG_I("waitMcpNotification(): Joined"); + LOG_E("Scheduler thread died!"); + return false; + } + + if (TAExitHandler::isExiting()) { + LOG_I("waitMcpNotification(): TAExitHandler thread died! Joining"); + TAExitHandler::join(); + LOG_I("waitMcpNotification(): Joined"); + LOG_E("TAExitHandler thread died!"); + return false; + } + return true; +} + + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDevice::mshNotifyAndWait() +{ + // Notify MC about the availability of a new command inside the MCP buffer + notify(SID_MCP); + + // Wait till response from MSH is available + if (!waitMcpNotification()) + { + LOG_E("waiting for MCP notification failed"); + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + return MC_DRV_OK; +} + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDevice::openSession( + Connection *deviceConnection, + loadDataOpenSession_ptr pLoadDataOpenSession, + uint32_t tciHandle, + uint32_t tciLen, + uint32_t tciOffset, + mcDrvRspOpenSessionPayload_ptr pRspOpenSessionPayload) +{ + do { + uint64_t tci = 0; + uint32_t len = 0; + + if (tciHandle != 0 && tciLen != 0) { + // Check if we have a cont WSM or normal one + if (findContiguousWsm(tciHandle, + deviceConnection->socketDescriptor, &tci, &len)) { + mcpMessage->cmdOpen.wsmTypeTci = WSM_CONTIGUOUS; + mcpMessage->cmdOpen.adrTciBuffer = tci; + mcpMessage->cmdOpen.ofsTciBuffer = 0; + } else if ((tci = findWsmL2(tciHandle, deviceConnection->socketDescriptor))) { + // We don't actually care about the len as the L2 table mapping is done + // // and the TL will segfault if it's trying to access non-allocated memory + len = tciLen; + mcpMessage->cmdOpen.wsmTypeTci = WSM_L2; + mcpMessage->cmdOpen.adrTciBuffer = tci; + mcpMessage->cmdOpen.ofsTciBuffer = tciOffset; + } else { + LOG_E("Failed to find contiguous WSM %u", tciHandle); + return MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND; + } + + if (!lockWsmL2(tciHandle)) { + LOG_E("Failed to lock contiguous WSM %u", tciHandle); + return MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND; + } + } else if (tciHandle == 0 && tciLen == 0) { + mcpMessage->cmdOpen.wsmTypeTci = WSM_INVALID; + mcpMessage->cmdOpen.adrTciBuffer = (uint32_t)(tci); + mcpMessage->cmdOpen.ofsTciBuffer = tciOffset; + } + + if ((tciHandle != 0 && tciLen == 0) || tciLen > len) { + LOG_E("Invalid TCI len from client - %u, tciHandle %d, Wsm len found %u", + tciLen, tciHandle, len); + return MC_DRV_ERR_TCI_GREATER_THAN_WSM; + } + + // Write MCP open message to buffer + mcpMessage->cmdOpen.cmdHeader.cmdId = MC_MCP_CMD_OPEN_SESSION; + mcpMessage->cmdOpen.uuid = pLoadDataOpenSession->tlHeader->mclfHeaderV2.uuid; + mcpMessage->cmdOpen.lenTciBuffer = tciLen; + LOG_I(" Using phys=%#llx, len=%d as TCI buffer", (uint64_t)tci, tciLen); + + // check if load data is provided + mcpMessage->cmdOpen.wsmTypeLoadData = WSM_L2; + mcpMessage->cmdOpen.adrLoadData = pLoadDataOpenSession->baseAddr; + mcpMessage->cmdOpen.ofsLoadData = pLoadDataOpenSession->offs; + mcpMessage->cmdOpen.lenLoadData = pLoadDataOpenSession->len; + memcpy(&mcpMessage->cmdOpen.tlHeader, pLoadDataOpenSession->tlHeader, sizeof(*pLoadDataOpenSession->tlHeader)); + + // Clear the notifications queue. We asume the race condition we have + // seen in openSession never happens elsewhere + notifications = std::queue(); + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for OPEN_SESSION, code %d.", mcRet); + // Here Mobicore can be considered dead. + if ((tciHandle != 0) && (tciLen != 0)) + { + unlockWsmL2(tciHandle); + } + return mcRet; + } + + // Check if the command response ID is correct + if ((MC_MCP_CMD_OPEN_SESSION | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) { + LOG_E("CMD_OPEN_SESSION got invalid MCP command response(0x%X)", mcpMessage->rspHeader.rspId); + // Something is messing with our MCI memory, we cannot know if the Trustlet was loaded. + // Had in been loaded, we are loosing track of it here. + if (tciHandle != 0 && tciLen != 0) { + unlockWsmL2(tciHandle); + } + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + mcRet = mcpMessage->rspOpen.rspHeader.result; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("MCP OPEN returned code %d.", mcRet); + if (tciHandle != 0 && tciLen != 0) { + unlockWsmL2(tciHandle); + } + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + + LOG_I(" After MCP OPEN, we have %d queued notifications", + notifications.size()); + // Read MC answer from MCP buffer + TrustletSession *trustletSession = new TrustletSession( + deviceConnection, + mcpMessage->rspOpen.sessionId); + + pRspOpenSessionPayload->sessionId = trustletSession->sessionId; + pRspOpenSessionPayload->deviceSessionId = (uintptr_t)trustletSession; + pRspOpenSessionPayload->sessionMagic = trustletSession->sessionMagic; + + trustletSession->gp_level=((mclfHeaderV24_ptr)&pLoadDataOpenSession->tlHeader->mclfHeaderV2)->gp_level; + LOG_I(" Trusted App has gp_level %d",trustletSession->gp_level); + trustletSession->sessionState = TrustletSession::TS_TA_RUNNING; + + trustletSessions.push_back(trustletSession); + + if (tciHandle != 0 && tciLen != 0) { + trustletSession->addBulkBuff(new CWsm((void *)(uintptr_t)pLoadDataOpenSession->offs, pLoadDataOpenSession->len, tciHandle, 0)); + } + + // We have some queued notifications and we need to send them to them + // trustlet session + while (!notifications.empty()) { + trustletSession->queueNotification(¬ifications.front()); + notifications.pop(); + } + + } while (0); + return MC_DRV_OK; +} + +mcResult_t MobiCoreDevice::checkLoad( + loadDataOpenSession_ptr pLoadDataOpenSession, + mcDrvRspOpenSessionPayload_ptr pRspOpenSessionPayload __unused) +{ + do { + // Write MCP open message to buffer + mcpMessage->cmdCheckLoad.cmdHeader.cmdId = MC_MCP_CMD_CHECK_LOAD_TA; + mcpMessage->cmdCheckLoad.uuid = pLoadDataOpenSession->tlHeader->mclfHeaderV2.uuid; + + // check if load data is provided + mcpMessage->cmdCheckLoad.wsmTypeLoadData = WSM_L2; + mcpMessage->cmdCheckLoad.adrLoadData = pLoadDataOpenSession->baseAddr; + mcpMessage->cmdCheckLoad.ofsLoadData = pLoadDataOpenSession->offs; + mcpMessage->cmdCheckLoad.lenLoadData = pLoadDataOpenSession->len; + memcpy(&mcpMessage->cmdCheckLoad.tlHeader, pLoadDataOpenSession->tlHeader, sizeof(*pLoadDataOpenSession->tlHeader)); + + // Clear the notifications queue. We asume the race condition we have + // seen in openSession never happens elsewhere + notifications = std::queue(); + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for CHECK_LOAD_TA, code %d.", mcRet); + // Here Mobicore can be considered dead. + return mcRet; + } + + // Check if the command response ID is correct + if ((MC_MCP_CMD_CHECK_LOAD_TA | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) { + LOG_E("CMD_OPEN_SESSION got invalid MCP command response(0x%X)", mcpMessage->rspHeader.rspId); + // Something is messing with our MCI memory, we cannot know if the Trustlet was loaded. + // Had in been loaded, we are loosing track of it here. + + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + mcRet = mcpMessage->rspCheckLoad.rspHeader.result; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("MCP CHECK_LOAD returned code %d.", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + return MC_DRV_OK; + + } while (0); + return MC_DRV_ERR_UNKNOWN; +} + + + +//------------------------------------------------------------------------------ +TrustletSession *MobiCoreDevice::registerTrustletConnection( + Connection *connection, + MC_DRV_CMD_NQ_CONNECT_struct *cmdNqConnect +) +{ + LOG_I(" Registering notification socket with Service session %d.", + cmdNqConnect->sessionId); + LOG_V(" Searching sessionId %d with sessionMagic %d", + cmdNqConnect->sessionId, + cmdNqConnect->sessionMagic); + + for (trustletSessionIterator_t iterator = trustletSessions.begin(); + iterator != trustletSessions.end(); + ++iterator) + { + TrustletSession *session = *iterator; + + if (session != (TrustletSession *)(uintptr_t) (cmdNqConnect->deviceSessionId)) { + continue; + } + + if ( (session->sessionMagic != cmdNqConnect->sessionMagic) + || (session->sessionId != cmdNqConnect->sessionId)) { + continue; + } + + session->notificationConnection = connection; + + LOG_I(" Found Service session, registered connection."); + + return session; + } + + LOG_I("registerTrustletConnection(): search failed"); + return NULL; +} + + +//------------------------------------------------------------------------------ +/** + * Need connection as well as according session ID, so that a client can not + * close sessions not belonging to him. + */ +mcResult_t MobiCoreDevice::closeSession( + Connection *deviceConnection, + uint32_t sessionId +) { + TrustletSession *session = findSession(deviceConnection,sessionId); + if (session == NULL) { + LOG_E("cannot close session with id=%d", sessionId); + return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION; + } + + if (session->gp_level == 1) { + mutex_connection.lock(); + LOG_I(" Closing GP TA session..."); + // Disconnect client from this session + session->deviceConnection = NULL; + // Free connection, i.e. close nq socket + delete session->notificationConnection; + session->notificationConnection = NULL; + // If exit notification from task arrives during MCP_CLOSE, + // Daemon can see that CA is already away + session->sessionState = TrustletSession::TS_CLOSE_SEND; + mutex_connection.unlock(); + } + + /* close session */ + mcResult_t mcRet = closeSessionInternal(session); + + if ((session->gp_level==1) && (mcRet == MAKE_MC_DRV_MCP_ERROR(MC_MCP_RET_ERR_CLOSE_TASK_FAILED))) { + LOG_I(" Close session failed this time."); + // We could have received a spurious notification of TA dead + if (session->sessionState == TrustletSession::TS_TA_DEAD) { + LOG_V(" TA died in the meantime, try closing again"); + // Try again + mcRet = closeSessionInternal(session); + assert(mcRet == MC_MCP_RET_OK); + } else { + // Clean up is deferred to handleTaExit() + return MC_MCP_RET_OK; + } + } + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("closeSession failed with %d", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + + + // clean session WSM + LOG_I("unlocking session buffers!"); + CWsm_ptr pWsm = session->popBulkBuff(); + while (pWsm) + { + unlockWsmL2(pWsm->handle); + delete pWsm; + pWsm = session->popBulkBuff(); + } + + // remove sesson from list. + for (trustletSessionIterator_t iterator = trustletSessions.begin(); + iterator != trustletSessions.end(); + ++iterator) + { + if (session == *iterator) + { + trustletSessions.erase(iterator); + delete session; + break; + } + } + + return MC_MCP_RET_OK; +} + + +//------------------------------------------------------------------------------ +void MobiCoreDevice::queueUnknownNotification( + notification_t notification +) { + notifications.push(notification); +} + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDevice::notify( + Connection *deviceConnection, + uint32_t sessionId +) { + TrustletSession *session = findSession(deviceConnection,sessionId); + if (session == NULL) + { + LOG_E("cannot notify session with id=%d", sessionId); + return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION; + } + + notify(sessionId); + + return MC_DRV_OK; +} + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDevice::mapBulk( + Connection *deviceConnection, + uint32_t sessionId, + uint32_t handle, + uint64_t pAddrL2, + uint32_t offsetPayload, + uint32_t lenBulkMem, + uint32_t *secureVirtualAdr +) { + TrustletSession *session = findSession(deviceConnection,sessionId); + if (session == NULL) { + LOG_E("cannot mapBulk on session with id=%d", sessionId); + return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION; + } + + // TODO-2012-09-06-haenellu: considernot ignoring the error case, ClientLib + // does not allow this. + session->addBulkBuff( + new CWsm((void *)(uintptr_t)offsetPayload, + lenBulkMem, + handle, + pAddrL2)); + + // Write MCP map message to buffer + mcpMessage->cmdMap.cmdHeader.cmdId = MC_MCP_CMD_MAP; + mcpMessage->cmdMap.sessionId = sessionId; + mcpMessage->cmdMap.wsmType = WSM_L2; + mcpMessage->cmdMap.adrBuffer = pAddrL2; + mcpMessage->cmdMap.ofsBuffer = offsetPayload; + mcpMessage->cmdMap.lenBuffer = lenBulkMem; + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for MAP, code %d.", mcRet); + return mcRet; + } + + // Check if the command response ID is correct + if (mcpMessage->rspHeader.rspId != (MC_MCP_CMD_MAP | FLAG_RESPONSE)) { + LOG_E("invalid MCP response for CMD_MAP"); + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + mcRet = mcpMessage->rspMap.rspHeader.result; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("MCP MAP returned code %d.", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + + *secureVirtualAdr = mcpMessage->rspMap.secureVirtualAdr; + return MC_DRV_OK; +} + + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDevice::unmapBulk( + Connection *deviceConnection, + uint32_t sessionId, + uint32_t handle, + uint32_t secureVirtualAdr, + uint32_t lenBulkMem +) { + TrustletSession *session = findSession(deviceConnection,sessionId); + if (session == NULL) { + LOG_E("cannot unmapBulk on session with id=%d", sessionId); + return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION; + } + + if (!session->findBulkBuff(handle, lenBulkMem)) { + LOG_E("cannot unmapBulk with handle=%d", handle); + return MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND; + } + + // Write MCP unmap command to buffer + mcpMessage->cmdUnmap.cmdHeader.cmdId = MC_MCP_CMD_UNMAP; + mcpMessage->cmdUnmap.sessionId = sessionId; + mcpMessage->cmdUnmap.wsmType = WSM_L2; + mcpMessage->cmdUnmap.secureVirtualAdr = secureVirtualAdr; + mcpMessage->cmdUnmap.lenVirtualBuffer = lenBulkMem; + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for UNMAP, code %d.", mcRet); + return mcRet; + } + + // Check if the command response ID is correct + if (mcpMessage->rspHeader.rspId != (MC_MCP_CMD_UNMAP | FLAG_RESPONSE)) { + LOG_E("invalid MCP response for OPEN_SESSION"); + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + mcRet = mcpMessage->rspUnmap.rspHeader.result; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("MCP UNMAP returned code %d.", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + + // Just remove the buffer + // TODO-2012-09-06-haenellu: Haven't we removed it already? + if (!session->removeBulkBuff(handle)) + { + LOG_I("unmapBulk(): no buffer found found with handle=%u", handle); + } + + return MC_DRV_OK; +} + +mcResult_t MobiCoreDevice::getMobiCoreVersion( + mcDrvRspGetMobiCoreVersionPayload_ptr pRspGetMobiCoreVersionPayload +) { + // retunt info it we have already fetched it before + if (mcVersionInfo != NULL) + { + pRspGetMobiCoreVersionPayload->versionInfo = *mcVersionInfo; + return MC_DRV_OK; + } + + // Write MCP unmap command to buffer + mcpMessage->cmdGetMobiCoreVersion.cmdHeader.cmdId = MC_MCP_CMD_GET_MOBICORE_VERSION; + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for GET_MOBICORE_VERSION, code %d.", mcRet); + return mcRet; + } + + // Check if the command response ID is correct + if ((MC_MCP_CMD_GET_MOBICORE_VERSION | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) { + LOG_E("invalid MCP response for GET_MOBICORE_VERSION"); + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + mcRet = mcpMessage->rspGetMobiCoreVersion.rspHeader.result; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("MC_MCP_CMD_GET_MOBICORE_VERSION error %d", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + + pRspGetMobiCoreVersionPayload->versionInfo = mcpMessage->rspGetMobiCoreVersion.versionInfo; + + // Store MobiCore info for future reference. + mcVersionInfo = new mcVersionInfo_t(); + *mcVersionInfo = pRspGetMobiCoreVersionPayload->versionInfo; + return MC_DRV_OK; +} + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDevice::loadToken(Connection *deviceConnection __unused, + loadTokenData_ptr pLoadTokenData) +{ + do { + mcpMessage->cmdLoadToken.cmdHeader.cmdId = MC_MCP_CMD_LOAD_TOKEN; + mcpMessage->cmdLoadToken.wsmTypeLoadData = WSM_L2; + mcpMessage->cmdLoadToken.adrLoadData = (uint32_t) pLoadTokenData->addr; + mcpMessage->cmdLoadToken.ofsLoadData = pLoadTokenData->offs; + mcpMessage->cmdLoadToken.lenLoadData = pLoadTokenData->len; + + /* Clear the notifications queue. We asume the race condition we have + * seen in openSession never happens elsewhere + */ + notifications = std::queue(); + + mcResult_t mcRet = mshNotifyAndWait(); + if (mcRet != MC_MCP_RET_OK) + { + LOG_E("mshNotifyAndWait failed for LOAD_TOKEN, code 0x%x.", mcRet); + /* Here rspHeader.rspId) { + LOG_E("CMD_LOAD_TOKEN got invalid MCP command response(0x%X)", + mcpMessage->rspHeader.rspId); + return MC_DRV_ERR_DAEMON_MCI_ERROR; + } + + mcRet = mcpMessage->rspLoadToken.rspHeader.result; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("MCP LOAD_TOKEN returned code 0x%x.", mcRet); + return MAKE_MC_DRV_MCP_ERROR(mcRet); + } + + } while (0); + + return MC_DRV_OK; +} + +/** @} */ diff --git a/mobicore/TuiService/src/com/trustonic/util/tLog.java b/mobicore/daemon/Daemon/Device/NotificationQueue.cpp similarity index 57% rename from mobicore/TuiService/src/com/trustonic/util/tLog.java rename to mobicore/daemon/Daemon/Device/NotificationQueue.cpp index bc93a10..a034c4c 100644 --- a/mobicore/TuiService/src/com/trustonic/util/tLog.java +++ b/mobicore/daemon/Daemon/Device/NotificationQueue.cpp @@ -1,4 +1,8 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -28,44 +32,51 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include "NotificationQueue.h" +#include -package com.trustonic.util; +#include "log.h" -import android.util.Log; - -public class tLog { - /* Enable log with the command: - * adb shell setprop log.tag.YOUR_APP_TAG LEVEL - * e.g adb shell setprop log.tag.TuiActivity DEBUG - * */ - public static void d(String tag, String msg) { - if (Log.isLoggable(tag, Log.DEBUG)) { - Log.d(tag, msg); - } - } +//------------------------------------------------------------------------------ +NotificationQueue::NotificationQueue( + notificationQueue_t *i, + notificationQueue_t *o, + uint32_t size +) : in(i), out(o) +{ + in->hdr.queueSize = size; + out->hdr.queueSize = size; +} - public static void i(String tag, String msg) { - if (Log.isLoggable(tag, Log.INFO)) { - Log.i(tag, msg); - } - } - public static void e(String tag, String msg) { - if (Log.isLoggable(tag, Log.ERROR)) { - Log.e(tag, msg); - } +//------------------------------------------------------------------------------ +void NotificationQueue::putNotification( + notification_t *notification +) +{ + mutex.lock(); + if ((out->hdr.writeCnt - out->hdr.readCnt) < out->hdr.queueSize) { + out->notification[out->hdr.writeCnt & (out->hdr.queueSize - 1)] + = *notification; + out->hdr.writeCnt++; } + mutex.unlock(); +} - public static void v(String tag, String msg) { - if (Log.isLoggable(tag, Log.VERBOSE)) { - Log.v(tag, msg); - } - } - public static void w(String tag, String msg) { - if (Log.isLoggable(tag, Log.WARN)) { - Log.w(tag, msg); - } +//------------------------------------------------------------------------------ +notification_t *NotificationQueue::getNotification( + void +) +{ + notification_t *ret = NULL; + mutex.lock(); + if ((in->hdr.writeCnt - in->hdr.readCnt) > 0) { + ret = &(in->notification[in->hdr.readCnt & (in->hdr.queueSize - 1)]); + in->hdr.readCnt++; } + mutex.unlock(); + return ret; } +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/NotificationQueue.h b/mobicore/daemon/Daemon/Device/NotificationQueue.h new file mode 100644 index 0000000..cd004bb --- /dev/null +++ b/mobicore/daemon/Daemon/Device/NotificationQueue.h @@ -0,0 +1,90 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * MobiCore Notification Queue handling. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 NOTIFICATIONQUEUE_H_ +#define NOTIFICATIONQUEUE_H_ + +#include //C99 data +#include "Mci/mcinq.h" +#include "CMutex.h" + + +class NotificationQueue +{ + +public: + + /** NQ Constructor, initializes the NQ component. + * + * makes the given queue object usable with the queue type of functions + * + * @param in queue to initialize + * @param out beginning of queue header + * @param queueSize Size of the queue + */ + NotificationQueue( + notificationQueue_t *in, + notificationQueue_t *out, + uint32_t size + ); + + /** Places an element to the outgoing queue. + * + * @param notification Data to be placed in queue. + */ + void putNotification( + notification_t *notification + ); + + /** Retrieves the first element from the queue. + * + * @return first notification Queue element. + * @return NULL if the queue is empty. + */ + notification_t *getNotification( + void + ); + +private: + + notificationQueue_t *in; + notificationQueue_t *out; + CMutex mutex; + +}; + +#endif /* NOTIFICATIONQUEUE_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/Platforms/Android.mk b/mobicore/daemon/Daemon/Device/Platforms/Android.mk new file mode 100644 index 0000000..48dd98a --- /dev/null +++ b/mobicore/daemon/Daemon/Device/Platforms/Android.mk @@ -0,0 +1,15 @@ +# ============================================================================= +# +# Makefile pointing to the platform specific makefile. +# +# ============================================================================= + +PLATFORMS_PATH := $(LOCAL_PATH)/Daemon/Device/Platforms + +# Always include the Generic code +include $(PLATFORMS_PATH)/Generic/Android.mk + +ifneq ($(filter-out Generic,$(PLATFORM)),) + $(info PLATFORM: $(PLATFORM)) + include $(PLATFORMS_PATH)/$(PLATFORM)/Android.mk +endif diff --git a/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk b/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk new file mode 100644 index 0000000..a6607de --- /dev/null +++ b/mobicore/daemon/Daemon/Device/Platforms/Generic/Android.mk @@ -0,0 +1,16 @@ +# ============================================================================= +# +# Generic TrustZone device includes +# +# ============================================================================= + +# This is not a separate module. +# Only for inclusion by other modules. + +GENERIC_PATH := Daemon/Device/Platforms/Generic + +# Add new source files here +LOCAL_SRC_FILES += $(GENERIC_PATH)/TrustZoneDevice.cpp + +# Header files for components including this module +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 new file mode 100644 index 0000000..20652d6 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.cpp @@ -0,0 +1,725 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + */ + +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ + +#include +#include +#include +#include + +#include "McTypes.h" +#include "mc_linux.h" +#include "McTypes.h" +#include "Mci/mci.h" +#include "mcVersionHelper.h" + +#include "CSemaphore.h" +#include "CMcKMod.h" + +#include "MobiCoreDevice.h" +#include "TrustZoneDevice.h" +#include "NotificationQueue.h" + +#include "log.h" + + +#define NQ_NUM_ELEMS (16) +#define NQ_BUFFER_SIZE (2 * (sizeof(notificationQueueHeader_t)+ NQ_NUM_ELEMS * sizeof(notification_t))) +#define MCP_BUFFER_SIZE (sizeof(mcpBuffer_t)) +#define MCI_BUFFER_SIZE (NQ_BUFFER_SIZE + MCP_BUFFER_SIZE) + +//------------------------------------------------------------------------------ +__attribute__ ((weak)) MobiCoreDevice *getDeviceInstance( + void +) +{ + return new TrustZoneDevice(); +} + +//------------------------------------------------------------------------------ +TrustZoneDevice::TrustZoneDevice( + void +) +{ + schedulerEnabled = false; + pMcKMod = NULL; + pWsmMcp = NULL; + mobicoreInDDR = NULL; +} + +//------------------------------------------------------------------------------ +TrustZoneDevice::~TrustZoneDevice( + void +) +{ + delete pMcKMod; + delete pWsmMcp; + delete nq; +} + + +//------------------------------------------------------------------------------ +/** + * Set up MCI and wait till MC is initialized + * @return true if open(devFile); + if (ret != MC_DRV_OK) + { + LOG_W(" Opening kernel module device failed"); + return false; + } + if (!pMcKMod->checkVersion()) + { + LOG_E("kernel module version mismatch"); + return false; + } + + this->schedulerEnabled = enableScheduler; + + // Init MC with NQ and MCP buffer addresses + + // Set up MCI buffer + if (!getMciInstance(MCI_BUFFER_SIZE, &pWsmMcp, &mciReused)) + { + LOG_E("getMciInstance failed"); + return false; + } + mciBuffer = pWsmMcp->virtAddr; + + // Only do a fastcall if MCI has not been reused (MC already initialized) + if (!mciReused) + { + // Wipe memory before first usage + memset(mciBuffer, 0, MCI_BUFFER_SIZE); + + // Init MC with NQ and MCP buffer addresses + int ret = pMcKMod->fcInit(NQ_BUFFER_SIZE, NQ_BUFFER_SIZE, MCP_BUFFER_SIZE); + if (ret != 0) + { + LOG_E("pMcKMod->fcInit() failed"); + return false; + } + + // Here we are safe to setup the mcFlags); + + // Set up the MCP message + mcpMessage = &(mcpBuf->mcpMessage); + + // convert virtual address of mapping to physical address for the init. + LOG_I("MCI established, at %p, phys=%#llx, reused=%s", + pWsmMcp->virtAddr, + pWsmMcp->physAddr, + mciReused ? "true" : "false"); + return true; +} + + +//------------------------------------------------------------------------------ +void TrustZoneDevice::initDeviceStep2( + void +) +{ + // not needed +} + + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::yield( + void +) +{ + int32_t ret = pMcKMod->fcYield(); + if (ret != 0) { + LOG_E("pMcKMod->fcYield() failed: %d", ret); + } + return ret == 0; +} + + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::nsiq( + void +) +{ + // There is no need to set the NON-IDLE flag here. Sending an N-SIQ will + // make the schedule = MC_FLAG_SCHEDULE_NON_IDLE; + + int32_t ret = pMcKMod->fcNSIQ(); + if (ret != 0) { + LOG_E("pMcKMod->fcNSIQ() failed : %d", ret); + return false; + } + // now we have to wake the scheduler, so 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 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; +} + +//------------------------------------------------------------------------------ +void TrustZoneDevice::dumpMobicoreStatus( + void +) { + uint32_t status, info; + + // read additional info about exception-point and print + LOG_E("fcInfo(1, &status, &info); + LOG_W(" flags = 0x%08x", info); + pMcKMod->fcInfo(2, &status, &info); + LOG_W(" haltCode = 0x%08x", info); + pMcKMod->fcInfo(3, &status, &info); + LOG_W(" haltIp = 0x%08x", info); + pMcKMod->fcInfo(4, &status, &info); + LOG_W(" faultRec.cnt = 0x%08x", info); + pMcKMod->fcInfo(5, &status, &info); + LOG_W(" faultRec.cause = 0x%08x", info); + pMcKMod->fcInfo(6, &status, &info); + LOG_W(" faultRec.meta = 0x%08x", info); + pMcKMod->fcInfo(7, &status, &info); + LOG_W(" faultRec.thread = 0x%08x", info); + pMcKMod->fcInfo(8, &status, &info); + LOG_W(" faultRec.ip = 0x%08x", info); + pMcKMod->fcInfo(9, &status, &info); + LOG_W(" faultRec.sp = 0x%08x", info); + pMcKMod->fcInfo(10, &status, &info); + LOG_W(" faultRec.arch.dfsr = 0x%08x", info); + pMcKMod->fcInfo(11, &status, &info); + LOG_W(" faultRec.arch.adfsr = 0x%08x", info); + pMcKMod->fcInfo(12, &status, &info); + LOG_W(" faultRec.arch.dfar = 0x%08x", info); + pMcKMod->fcInfo(13, &status, &info); + LOG_W(" faultRec.arch.ifsr = 0x%08x", info); + pMcKMod->fcInfo(14, &status, &info); + LOG_W(" faultRec.arch.aifsr = 0x%08x", info); + pMcKMod->fcInfo(15, &status, &info); + LOG_W(" faultRec.arch.ifar = 0x%08x", info); + pMcKMod->fcInfo(16, &status, &info); + LOG_W(" mcData.flags = 0x%08x", info); + pMcKMod->fcInfo(19, &status, &info); + LOG_W(" mcExcep.partner = 0x%08x", info); + pMcKMod->fcInfo(20, &status, &info); + LOG_W(" mcExcep.peer = 0x%08x", info); + pMcKMod->fcInfo(21, &status, &info); + LOG_W(" mcExcep.message = 0x%08x", info); + pMcKMod->fcInfo(22, &status, &info); + LOG_W(" mcExcep.data = 0x%08x", info); +} + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::waitSsiq(void) +{ + uint32_t cnt; + if (!pMcKMod->waitSSIQ(&cnt)) { + LOG_E("pMcKMod->SSIQ() failed"); + return false; + } + LOG_I(" Received SSIQ interrupt from mapMCI(len, &handle, &virtAddr, &physAddr, &isReused); + if (ret != MC_DRV_OK) { + LOG_E("pMcKMod->mmap() failed: %x", 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, 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) +{ + uint64_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); +} + + +//------------------------------------------------------------------------------ +CWsm_ptr TrustZoneDevice::allocateContiguousPersistentWsm(uint32_t len) +{ + CWsm_ptr pWsm = NULL; + // Allocate shared memory + addr_t virtAddr; + uint32_t handle; + uint64_t physAddr; + + if (len == 0 ) + return NULL; + + if (pMcKMod->mapWsm(len, &handle, &virtAddr, &physAddr)) + return NULL; + + // Register (vaddr,paddr) with device + pWsm = new CWsm(virtAddr, len, handle, physAddr); + + // Return pointer to the allocated memory + return pWsm; +} + + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::unregisterWsmL2(CWsm_ptr pWsm) +{ + int ret = pMcKMod->unregisterWsmL2(pWsm->handle); + if (ret != 0) { + LOG_E("pMcKMod->unregisterWsmL2 failed: %d", ret); + //IMPROVEMENT-2012-03-07 maneaval Make sure we don't leak objects + return false; + } + delete pWsm; + return true; +} + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::lockWsmL2(uint32_t handle) +{ + int ret = pMcKMod->lockWsmL2(handle); + if (ret != 0) { + LOG_E("pMcKMod->unregisterWsmL2 failed: %d", ret); + return false; + } + return true; +} + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::unlockWsmL2(uint32_t handle) +{ + LOG_I(" Unlocking buffer with handle %u", handle); + int ret = pMcKMod->unlockWsmL2(handle); + if (ret != 0) { + // Failure here is not important + LOG_I(" pMcKMod->unregisterWsmL2 failed: %d", ret); + return false; + } + return true; +} + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::cleanupWsmL2(void) +{ + int ret = pMcKMod->cleanupWsmL2(); + if (ret != 0) { + LOG_E("pMcKMod->cleanupWsmL2 failed: %d", ret); + return false; + } + return true; +} + +//------------------------------------------------------------------------------ +uint64_t TrustZoneDevice::findWsmL2(uint32_t handle, int fd) +{ + uint64_t ret = pMcKMod->findWsmL2(handle, fd); + if (!ret) { + LOG_E("pMcKMod->findWsmL2 failed"); + return 0; + } + LOG_I("Resolved buffer with handle %u to %#llx", handle, ret); + return ret; +} + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::findContiguousWsm(uint32_t handle, int fd, uint64_t *phys, uint32_t *len) +{ + if (pMcKMod->findContiguousWsm(handle, fd, phys, len)) { + LOG_V(" pMcKMod->findContiguousWsm failed"); + return false; + } + LOG_I("Resolved buffer with handle %u to %#llx", handle, *phys); + return true; +} +//------------------------------------------------------------------------------ +bool TrustZoneDevice::setupLog(void) +{ + if (pMcKMod->setupLog()) { + LOG_W("pMcKMod->setupLog failed"); + return false; + } + return true; +} + +//------------------------------------------------------------------------------ +bool TrustZoneDevice::schedulerAvailable(void) +{ + return schedulerEnabled; +} + +//------------------------------------------------------------------------------ +//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; + + // loop forever + for (;;) + { + // Scheduling decision + if (MC_FLAG_SCHEDULE_IDLE == mcFlags->schedule) + { + // sessionState == TrustletSession::TS_TA_DEAD) { + LOG_I("Cleaning up session %i", ts->sessionId); + + // Tell t-base to close the session + mcResult_t mcRet = closeSessionInternal(ts); + + // If ok, remove objects + if (mcRet == MC_DRV_OK) { + iterator = trustletSessions.erase(iterator); + LOG_I("TA session %i finally closed", ts->sessionId); + delete ts; + continue; + } else { + LOG_I("TA session %i could not be closed yet.", ts->sessionId); + } + } + ++iterator; + } + mutex_mcp.unlock(); + } + TAExitHandler::setExiting(); + signalMcpNotification(); + + LOG_E("schedule loop terminated"); +} + + +//------------------------------------------------------------------------------ +void TrustZoneDevice::handleIrq( + void +) { + LOG_I("Starting Notification Queue IRQ handler..."); + + for (;;) + { + + LOG_I(" No notifications pending, waiting for S-SIQ"); + if (!waitSsiq()) + { + LOG_E("Waiting for S-SIQ failed"); + break; + } + + LOG_V("S-SIQ received"); + + // get notifications from queue + for (;;) + { + notification_t *notification = nq->getNotification(); + if (NULL == notification) + { + break; + } + + // process the notification + // check if the notification belongs to the MCP session + if (notification->sessionId == SID_MCP) + { + LOG_I(" Notification for MCP, payload=%d", + notification->payload); + + // Signal main thread of the driver to continue after MCP + // command has been processed by the MC + signalMcpNotification(); + + continue; + } + + LOG_I(" Notification for session %d, payload=%d", + notification->sessionId, notification->payload); + + // Get the Trustlet session for the session ID + TrustletSession *ts = NULL; + + ts = getTrustletSession(notification->sessionId); + if (ts == NULL) { + /* Couldn't find the session for this notifications + * In practice this only means one thing: there is + * a race condition between RTM and the Daemon and + * RTM won. But we shouldn't drop the notification + * right away we should just queue it in the device + */ + LOG_W("Notification for unknown session ID"); + queueUnknownNotification(*notification); + } else { + mutex_connection.lock(); + // Get the NQ connection for the session ID + Connection *connection = ts->notificationConnection; + if (connection == NULL) { + ts->queueNotification(notification); + if (ts->deviceConnection == NULL) { + LOG_I(" Notification for disconnected client, scheduling cleanup of sessions."); + taExitNotification.signal(); + } + } else { + LOG_I(" Forward notification to McClient."); + // Forward session ID and additional payload of + // notification to the TLC/Application layer + connection->writeData((void *)notification, + sizeof(notification_t)); + } + mutex_connection.unlock(); + } + } // for (;;) over notifiction queue + + // finished processing notifications. It does not matter if there were + // any notification or not. S-SIQs can also be triggered by an SWd + // driver which was waiting for a FIQ. In this case the S-SIQ tells + // NWd that SWd is no longer idle an will need scheduling again + schedSync.signal(); + + } //for (;;) + + + LOG_E("S-SIQ exception"); + // Tell main thread that "something happened" + // MSH thread MUST not block! + DeviceIrqHandler::setExiting(); + signalMcpNotification(); +} +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.h b/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.h new file mode 100644 index 0000000..a895fa2 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/Platforms/Generic/TrustZoneDevice.h @@ -0,0 +1,148 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * Class for TrustZone Devices. + * TrustZone device implements communication functions needed for + * accessing MobiCore located in an TrustZone environment. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 TRUSTZONEDEVICE_H_ +#define TRUSTZONEDEVICE_H_ + + +#include + +#include "McTypes.h" + +#include "CSemaphore.h" +#include "CMcKMod.h" +#include "CWsm.h" + +#include "ExcDevice.h" +#include "MobiCoreDevice.h" + + +#define SCHEDULING_FREQ 5 /**< N-SIQ every n-th time */ + +class TrustZoneDevice : public MobiCoreDevice +{ + +protected: + bool schedulerEnabled; /**< NQ IRQ Scheduler enabling */ + CSemaphore schedSync; /**< Semaphore to synchronize S-SIQs with scheduler thread */ + CMcKMod_ptr pMcKMod; /**< kernel module */ + CWsm_ptr pWsmMcp; /**< WSM use for MCP */ + CWsm_ptr mobicoreInDDR; /**< WSM used for Mobicore binary */ + + /** Access functions to the MC Linux kernel module + */ + bool yield(void); + + bool nsiq(void); + + bool waitSsiq(void); + +public: + + TrustZoneDevice(void); + + virtual ~TrustZoneDevice(void); + +// static MobiCoreDevice* getDeviceInstance( +// void +// ); + /** Set up MCI and wait till MC is initialized + * + * @param devFile the device node to speak to. + * @param loadMobiCore + * @param mobicoreImage + * @param enableScheduler + * + * @return true if mobicore is initialized + * @trows ExcDevice + */ + bool initDevice( + const char *devFile, + bool enableScheduler + ); + + void initDeviceStep2(void); + + void notify(uint32_t sessionId); + + void dumpMobicoreStatus(void); + + uint32_t getMobicoreStatus(void); + + bool checkMciVersion(void); + + /** Memory allocation functions */ + bool getMciInstance(uint32_t len, CWsm_ptr *mci, bool *reused); + + //bool freeWsm(CWsm_ptr pWsm); + + CWsm_ptr registerWsmL2(addr_t buffer, uint32_t len, uint32_t pid); + + bool unregisterWsmL2(CWsm_ptr pWsm); + + bool lockWsmL2(uint32_t handle); + + bool unlockWsmL2(uint32_t handle); + + uint64_t findWsmL2(uint32_t handle, int fd); + + bool findContiguousWsm(uint32_t handle, int fd, uint64_t *phys, uint32_t *len); + + /** + * Cleanup all orphaned bulk buffers. + */ + bool cleanupWsmL2(void); + + /** + * Allocates persistent WSM memory for TL (won't be fried when TLC exits). + */ + CWsm_ptr allocateContiguousPersistentWsm(uint32_t len); + + bool setupLog(void); + + bool schedulerAvailable(void); + + void schedule(void); + + void handleIrq(void); + + void handleTaExit(void); +}; + +#endif /* TRUSTZONEDEVICE_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/TAExitHandler.cpp b/mobicore/daemon/Daemon/Device/TAExitHandler.cpp new file mode 100644 index 0000000..cf60b04 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/TAExitHandler.cpp @@ -0,0 +1,48 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ + +#include "TAExitHandler.h" +#include "log.h" + +//------------------------------------------------------------------------------ +void TAExitHandler::run( + void +) +{ + handleTaExit(); + this->exit(-1); +} + +/** @} */ diff --git a/mobicore/TuiService/src/com/trustonic/tuiapi/TUI_Event.java b/mobicore/daemon/Daemon/Device/TAExitHandler.h similarity index 79% rename from mobicore/TuiService/src/com/trustonic/tuiapi/TUI_Event.java rename to mobicore/daemon/Daemon/Device/TAExitHandler.h index 79c04d6..037cd12 100644 --- a/mobicore/TuiService/src/com/trustonic/tuiapi/TUI_Event.java +++ b/mobicore/daemon/Daemon/Device/TAExitHandler.h @@ -1,4 +1,9 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * Trusted Application exit handler thread. + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -29,23 +34,24 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package com.trustonic.tuiapi; +#ifndef _TAEXITHANDLER_H_ +#define _TAEXITHANDLER_H_ + +#include "CThread.h" +#include "CMutex.h" +#include "TrustletSession.h" + -public class TUI_Event { - private TUI_EventType type; +class TAExitHandler: public CThread +{ +public: + CSemaphore taExitNotification; - public TUI_Event() { - super(); - this.type = new TUI_EventType(TUI_EventType.TUI_UNKNOW_EVENT); - } + virtual void handleTaExit() = 0; - public TUI_Event(int type) { - super(); - this.type = new TUI_EventType(type); - } + void run(); +}; - public int getType(){ - return this.type.is(); - } +#endif /* TAEXITHANDLER_H_ */ -} +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/TrustletSession.cpp b/mobicore/daemon/Daemon/Device/TrustletSession.cpp new file mode 100644 index 0000000..d0bd1e0 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/TrustletSession.cpp @@ -0,0 +1,161 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ + +#include "TrustletSession.h" +#include + +#include "log.h" + +using namespace std; + +//------------------------------------------------------------------------------ +TrustletSession::TrustletSession(Connection *deviceConnection, uint32_t sessionId) +{ + this->deviceConnection = deviceConnection; + this->notificationConnection = NULL; + this->sessionId = sessionId; + sessionMagic = rand(); + this->gp_level=0; + this->sessionState=TS_TA_RUNNING; +} + + +//------------------------------------------------------------------------------ +TrustletSession::~TrustletSession(void) +{ + map::iterator it; + delete notificationConnection; + + if (!buffers.empty()) { + LOG_W("%s: Mapped buffers still available %u", __func__, buffers.size()); + } + for ( it = buffers.begin() ; it != buffers.end(); it++ ) + delete (*it).second; + + buffers.clear(); +} + +//------------------------------------------------------------------------------ +void TrustletSession::queueNotification(notification_t *notification) +{ + if (sessionState == TS_TA_DEAD) { + return; + } + if ((gp_level == 1) && (notification->payload != 0)) { + LOG_I(" Mark session %i dead", sessionId); + sessionState = TS_TA_DEAD; + } + // Note this is a very subtle synchronization requirement: + // The TrustletSession object is manipulated by several threads + // If the sessionState is set to closed, + // it means another thread could soon delete the object + // Also in this case we don't care about any notifications anymore + if (sessionState == TS_CLOSE_SEND) { + return; + } + + notifications.push(*notification); +} + +//------------------------------------------------------------------------------ +void TrustletSession::processQueuedNotifications(void) +{ + LOG_I(" %s:%i", __FILE__, __LINE__ ); + + // Nothing to do here! + if (notificationConnection == NULL) + return; + + while (!notifications.empty()) { + // Forward session ID and additional payload of + // notification to the just established connection + notificationConnection->writeData((void *)¬ifications.front(), + sizeof(notification_t)); + notifications.pop(); + } +} + +//------------------------------------------------------------------------------ +bool TrustletSession::addBulkBuff(CWsm_ptr pWsm) +{ + if (!pWsm) + return false; + if (buffers.find(pWsm->handle) != buffers.end()) { + delete pWsm; + return false; + } + buffers[pWsm->handle] = pWsm; + return true; +} + +//------------------------------------------------------------------------------ +bool TrustletSession::removeBulkBuff(uint32_t handle) +{ + if (buffers.find(handle) == buffers.end()) { + return false; + } + CWsm_ptr pWsm = buffers[handle]; + delete pWsm; + buffers.erase(handle); + return true; +} + +//------------------------------------------------------------------------------ +bool TrustletSession::findBulkBuff(uint32_t handle, uint32_t lenBulkMem) +{ + if (buffers.find(handle) == buffers.end()) { + return false; + } + CWsm_ptr pWsm = buffers[handle]; + if ((uint32_t)pWsm->len != lenBulkMem) { + return false; + } + + return true; +} + +//------------------------------------------------------------------------------ +CWsm_ptr TrustletSession::popBulkBuff() +{ + if (buffers.empty()) { + return NULL; + } + + CWsm_ptr pWsm = buffers.begin()->second; + // Remove it from the map + buffers.erase(pWsm->handle); + return pWsm; +} + +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/TrustletSession.h b/mobicore/daemon/Daemon/Device/TrustletSession.h new file mode 100644 index 0000000..76deba1 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/TrustletSession.h @@ -0,0 +1,86 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 TRUSTLETSESSION_H_ +#define TRUSTLETSESSION_H_ + +#include "NotificationQueue.h" +#include "CWsm.h" +#include "Connection.h" +#include +#include + + +class TrustletSession +{ +private: + std::queue notifications; + std::map buffers; + +public: + uint32_t sessionId; // Assigned by t-base + uint32_t sessionMagic; // Random data + Connection *deviceConnection; // Command socket for client "device" + Connection *notificationConnection; // Notification socket for client session + uint32_t gp_level; + enum TS_STATE { + TS_TA_RUNNING,//->dead,close_send + TS_TA_DEAD, //->close_send, closed + TS_CLOSE_SEND,//->close_send, dead, closed + TS_CLOSED,//unused + } sessionState; + + TrustletSession(Connection *deviceConnection, uint32_t sessionId); + + ~TrustletSession(void); + + void queueNotification(notification_t *notification); + + void processQueuedNotifications(void); + + bool addBulkBuff(CWsm_ptr pWsm); + + bool removeBulkBuff(uint32_t handle); + + bool findBulkBuff(uint32_t handle, uint32_t lenBulkMem); + + CWsm_ptr popBulkBuff(); + +}; + +typedef std::list trustletSessionList_t; +typedef trustletSessionList_t::iterator trustletSessionIterator_t; + +#endif /* TRUSTLETSESSION_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/public/ExcDevice.h b/mobicore/daemon/Daemon/Device/public/ExcDevice.h new file mode 100644 index 0000000..733fbcd --- /dev/null +++ b/mobicore/daemon/Daemon/Device/public/ExcDevice.h @@ -0,0 +1,72 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * Device exceptions. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 EXCDEVICE_H_ +#define EXCDEVICE_H_ + +#include +#include +#include +#include + +#define ERROR_MCI_VERSION_MISMATCH ((int)(-2)) +#define ERROR_KMOD_VERSION_MISMATCH ((int)(-3)) + +class ExcDevice: public std::exception +{ + +public: + + ExcDevice(const char *description, int cause) : + cause(cause), description(description) { + } + + virtual int getCause() const throw () { + return cause; + } + + virtual const char *getDescription() const throw () { + return description; + } + +private: + + int cause; + const char *description; +}; + +#endif /* EXCDEVICE_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Device/public/MobiCoreDevice.h b/mobicore/daemon/Daemon/Device/public/MobiCoreDevice.h new file mode 100644 index 0000000..5d05028 --- /dev/null +++ b/mobicore/daemon/Daemon/Device/public/MobiCoreDevice.h @@ -0,0 +1,253 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_DEV + * @{ + * @file + * + * MobiCore device. + * The MobiCore device class handles the MCP processing within the driver. + * Concrete devices implementing the communication behavior for the platforms have to be derived + * from this. + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 MOBICOREDEVICE_H_ +#define MOBICOREDEVICE_H_ + +#include +#include + +#include "McTypes.h" +#include "MobiCoreDriverApi.h" + +#include "Mci/mcimcp.h" +#include "mcLoadFormat.h" +#include "MobiCoreDriverCmd.h" + +#include "Connection.h" +#include "CWsm.h" + +#include "ExcDevice.h" +#include "DeviceScheduler.h" +#include "DeviceIrqHandler.h" +#include "TAExitHandler.h" +#include "NotificationQueue.h" +#include "TrustletSession.h" +#include "mcVersionInfo.h" + + +class MobiCoreDevice; + +typedef struct { + uint64_t baseAddr; /**< Physical address of the data to load. */ + uint32_t offs; /**< Offset to the data. */ + uint32_t len; /**< Length of the data to load. */ + mclfHeader_ptr tlHeader; /**< Pointer to trustlet header. */ +} loadDataOpenSession_t, *loadDataOpenSession_ptr; + +typedef struct { + uint64_t addr; /**< Physical address of the data to load. */ + uint64_t offs; /**< Offset to the data. */ + uint64_t len; /**< Length of the data to load. */ +} loadTokenData_t, *loadTokenData_ptr; + +/** + * Factory method to return the platform specific MobiCore device. + * Implemented in the platform specific *Device.cpp + */ +extern MobiCoreDevice *getDeviceInstance(void); + +class MobiCoreDevice : public DeviceScheduler, public DeviceIrqHandler, public TAExitHandler +{ + +protected: + + NotificationQueue *nq; /**< Pointer to the notification queue within the MCI buffer */ + mcFlags_t *mcFlags; /**< Pointer to the MC flags within the MCI buffer */ + mcpMessage_t *mcpMessage; /**< Pointer to the MCP message structure within the MCI buffer */ + CSemaphore mcpSessionNotification; /**< Semaphore to synchronize incoming notifications for the MCP session */ + + trustletSessionList_t trustletSessions; /**< Available Trustlet Sessions */ + mcVersionInfo_t *mcVersionInfo; /**< MobiCore version info. */ + bool mcFault; /**< Signal RTM fault */ + bool mciReused; /**< Signal restart of Daemon. */ + CMutex mutex_connection; // Mutex to share session->notificationConnection for GP cases + + /* In a special case a Trustlet can create a race condition in the daemon. + * If at Trustlet start it detects an error of some sort and calls the + * exit function before waiting for any notifications from NWD then the daemon + * will receive the openSession notification from RTM and the error notification + * from the Trustlet at the same time but because the internal objects in + * the daemon are not yet completely setup then the error notification will + * never be sent to the TLC! + * + * This queue holds notifications received between the time the daemon + * puts the MCP command for open session until the internal session objects + * are setup correctly. + */ + std::queue notifications; /**< Notifications queue for open session notification */ + + MobiCoreDevice(); + + mcResult_t closeSessionInternal( + TrustletSession* session); + + mcResult_t sendSessionCloseCmd( + uint32_t sessionId); + + TrustletSession* findSession( + Connection *deviceConnection, + uint32_t sessionId); + + TrustletSession *getTrustletSession( + uint32_t sessionId); + + mcResult_t mshNotifyAndWait(void); + + void signalMcpNotification(void); + + bool waitMcpNotification(void); + +private: + virtual bool yield(void) = 0; + + virtual bool nsiq(void) = 0; + + virtual bool waitSsiq(void) = 0; + +public: + CMutex mutex_mcp; // This mutex should be taken before any access to below functions + + virtual ~MobiCoreDevice(); + + Connection *getSessionConnection(uint32_t sessionId, notification_t *notification); + + bool open(Connection *connection); + + void close(Connection *connection); + + mcResult_t openSession(Connection *deviceConnection, + loadDataOpenSession_ptr pLoadDataOpenSession, + uint32_t tciHandle, + uint32_t tciLen, + uint32_t tciOffset, + mcDrvRspOpenSessionPayload_ptr pRspOpenSessionPayload); + + mcResult_t checkLoad(loadDataOpenSession_ptr pLoadDataOpenSession, + mcDrvRspOpenSessionPayload_ptr pRspOpenSessionPayload); + + + TrustletSession *registerTrustletConnection(Connection *connection, + MC_DRV_CMD_NQ_CONNECT_struct *cmdNqConnect); + + + mcResult_t closeSession(Connection *deviceConnection, uint32_t sessionId); + + virtual mcResult_t notify(Connection *deviceConnection, uint32_t sessionId); + + virtual void notify(uint32_t sessionId) = 0; + + mcResult_t mapBulk(Connection *deviceConnection, uint32_t sessionId, uint32_t handle, uint64_t pAddrL2, + uint32_t offsetPayload, uint32_t lenBulkMem, uint32_t *secureVirtualAdr); + + mcResult_t unmapBulk(Connection *deviceConnection, uint32_t sessionId, uint32_t handle, + uint32_t secureVirtualAdr, uint32_t lenBulkMem); + + void start(); + + mcResult_t getMobiCoreVersion(mcDrvRspGetMobiCoreVersionPayload_ptr pRspGetMobiCoreVersionPayload); + + bool getMcFault() { + return mcFault; + } + + void queueUnknownNotification(notification_t notification); + + virtual void dumpMobicoreStatus(void) = 0; + + virtual uint32_t getMobicoreStatus(void) = 0; + + virtual bool schedulerAvailable(void) = 0; + + virtual void schedule(void) = 0; + + virtual void handleIrq(void) = 0; + + //virtual bool freeWsm(CWsm_ptr pWsm) = 0; + + /** + * Initialize MobiCore. + * + * @param devFile the device node to speak to. + * @param loadMobiCore + * @param mobicoreImage + * @param enableScheduler + * + * @returns true if MobiCore is already initialized. + * */ + virtual bool initDevice( + const char *devFile, + bool enableScheduler + ) = 0; + + virtual void initDeviceStep2(void) = 0; + + virtual bool getMciInstance(uint32_t len, CWsm_ptr *mci, bool *reused) = 0; + + virtual CWsm_ptr registerWsmL2(addr_t buffer, uint32_t len, uint32_t pid) = 0; + + virtual bool unregisterWsmL2(CWsm_ptr pWsm) = 0; + + virtual bool lockWsmL2(uint32_t handle) = 0; + + virtual bool unlockWsmL2(uint32_t handle) = 0; + + virtual uint64_t findWsmL2(uint32_t handle, int fd) = 0; + + virtual bool findContiguousWsm(uint32_t handle, int fd, uint64_t *phys, uint32_t *len) = 0; + + /** + * Cleanup all orphaned bulk buffers. + */ + virtual bool cleanupWsmL2(void) = 0; + + virtual bool setupLog(void) = 0; + + /** + * Allocates persistent WSM memory for TL (won't be released when TLC exits). + */ + virtual CWsm_ptr allocateContiguousPersistentWsm(uint32_t len) = 0; + + mcResult_t loadToken(Connection *deviceConnection, + loadTokenData_ptr pLoadTokenData); + +}; + +#endif /* MOBICOREDEVICE_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/FSD/Android.mk b/mobicore/daemon/Daemon/FSD/Android.mk new file mode 100644 index 0000000..8c8f578 --- /dev/null +++ b/mobicore/daemon/Daemon/FSD/Android.mk @@ -0,0 +1,17 @@ +# ============================================================================= +# +# MC driver server files +# +# ============================================================================= + +# This is not a separate module. +# Only for inclusion by other modules. + +FSD_PATH := Daemon/FSD + +# Add new folders with header files here +LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(FSD_PATH)/public \ + $(MOBICORE_PROJECT_PATH)/include/GPD_TEE_Internal_API + +# Add new source files here +LOCAL_SRC_FILES += $(FSD_PATH)/FSD.cpp \ No newline at end of file diff --git a/mobicore/daemon/Daemon/FSD/FSD.cpp b/mobicore/daemon/Daemon/FSD/FSD.cpp new file mode 100644 index 0000000..87c9bd1 --- /dev/null +++ b/mobicore/daemon/Daemon/FSD/FSD.cpp @@ -0,0 +1,584 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * FSD server. + * + * Handles incoming storage requests from TA through STH + */ +/* Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include "public/FSD.h" +#include +#include +#include +#include +#include + +//#define LOG_VERBOSE +#include "log.h" + +extern string getTlRegistryPath(); + +extern pthread_mutex_t syncMutex; +extern pthread_cond_t syncCondition; +extern bool Th_sync; + +//------------------------------------------------------------------------------ +FSD::FSD( + void +) +{ + sessionHandle = {0,0}; + dci = NULL; +} + +FSD::~FSD( + void +) +{ + FSD_Close(); +} + +//------------------------------------------------------------------------------ +void FSD::run( + void +) +{ + struct stat st; + mcResult_t ret; + string storage = getTlRegistryPath()+"/TbStorage"; + const char* tbstpath = storage.c_str(); + + /*Create Tbase storage directory*/ + if (stat(tbstpath, &st) == -1) { + LOG_I("%s: Creating command.header.commandId = CMD_ST_SYNC; + mcRet = mcNotify(&sessionHandle); + if (MC_DRV_OK != mcRet) + { + LOG_E("FSD_Open(): mcNotify returned: %d\n", mcRet); + goto close_session; + } + + /* Wait for notification from SWd */ + mcRet = mcWaitNotification(&sessionHandle, MC_INFINITE_TIMEOUT); + if (MC_DRV_OK != mcRet) + { + goto close_session; + } + LOG_I("FSD_Open(): received first notification \n"); + LOG_I("FSD_Open(): send notification back \n"); + mcRet = mcNotify(&sessionHandle); + if (MC_DRV_OK != mcRet) + { + LOG_E("FSD_Open(): mcNotify returned: %d\n", mcRet); + goto close_session; + } + + LOG_I("FSD_Open(): returning success"); + return mcRet; + +close_session: + mcCloseSession(&sessionHandle); + +close_device: + mcCloseDevice(MC_DEVICE_ID_DEFAULT); + +error: + free(dci); + dci = NULL; + + return mcRet; +} + +mcResult_t FSD::FSD_Close(void){ + mcResult_t mcRet; + + /* Clear DCI message buffer */ + memset(dci, 0, sizeof(dciMessage_t)); + + /* Close session to the debug driver trustlet */ + mcRet = mcCloseSession(&sessionHandle); + if (MC_DRV_OK != mcRet) + { + LOG_E("FSD_Close(): mcCloseSession returned: %d\n", mcRet); + } + + free(dci); + dci = NULL; + memset(&sessionHandle,0,sizeof(mcSessionHandle_t)); + + /* Close sth_request.type); + + mcRet = FSD_ExecuteCommand(); + + /* notify the STH*/ + mcRet = mcNotify(&sessionHandle); + if (MC_DRV_OK != mcRet) + { + LOG_E("FSD_executeCommand(): mcNotify returned: %d\n", mcRet); + break; + } + } +} + +void FSD_HexFileName( + unsigned char* fn, + char* FileName, + uint32_t elems +){ + + char tmp[elems * 2 + 1]; + uint32_t i=0; + + for (i = 0; i < elems; i++) { + sprintf(&tmp[i * 2], "%02x", fn[i]); + } + strcpy(FileName,tmp); +} + + +void FSD_CreateTaDirName( + TEE_UUID* ta_uuid, + char* DirName, + uint32_t elems +){ + + char tmp[elems * 2 + 1]; + unsigned char* fn; + uint32_t i=0; + + fn = (unsigned char*)ta_uuid; + for (i = 0; i < elems; i++) { + sprintf(&tmp[i * 2], "%02x", fn[i]); + } + strcat(DirName,tmp); +} + +//------------------------------------------------------------------------------ +mcResult_t FSD::FSD_ExecuteCommand(void){ + switch(dci->sth_request.type) + { + //-------------------------------------- + case STH_MESSAGE_TYPE_LOOK: + LOG_I("FSD_ExecuteCommand(): Looking for file\n"); + dci->sth_request.status=FSD_LookFile(); + + break; + //-------------------------------------- + case STH_MESSAGE_TYPE_READ: + LOG_I("FSD_ExecuteCommand(): Reading file\n"); + dci->sth_request.status=FSD_ReadFile(); + + break; + //-------------------------------------- + case STH_MESSAGE_TYPE_WRITE: + LOG_I("FSD_ExecuteCommand(): Writing file\n"); + dci->sth_request.status=FSD_WriteFile(); + + break; + //-------------------------------------- + case STH_MESSAGE_TYPE_DELETE: + LOG_I("FSD_ExecuteCommand(): Deleting file\n"); + dci->sth_request.status=FSD_DeleteFile(); + LOG_I("FSD_ExecuteCommand(): file deleted status is 0x%08x\n",dci->sth_request.status); + + break; + //-------------------------------------- + default: + LOG_E("FSD_ExecuteCommand(): Received unknown command %x. Ignoring..\n", dci->sth_request.type); + break; + } + return dci->sth_request.status; +} + + +/**************************** File operations *******************************/ + + +mcResult_t FSD::FSD_LookFile(void){ + FILE * pFile=NULL; + STH_FSD_message_t* sth_request=NULL; + uint32_t res=0; + string storage = getTlRegistryPath()+"/TbStorage"; + const char* tbstpath = storage.c_str(); + char tadirname[TEE_UUID_STRING_SIZE+1]; + char filename[2*FILENAMESIZE+1]; + char TAdirpath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1]; + char Filepath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1+2*FILENAMESIZE+1]; + + sth_request= &dci->sth_request; + //create TA folder name from TA UUID + FSD_CreateTaDirName(&sth_request->uuid,tadirname,sizeof(TEE_UUID)); + FSD_HexFileName(sth_request->filename,filename,FILENAMESIZE); + + //Create path to TA folder and test if does exist + strcpy(TAdirpath,tbstpath); + strcat(TAdirpath, "/"); + strcat(TAdirpath, tadirname); + + strcpy(Filepath, TAdirpath); + strcat(Filepath, "/"); + strcat(Filepath, filename); + LOG_I("%s: Storage %s\n", __func__, tbstpath); + LOG_I("%s: TA dirname %s\n", __func__, tadirname); + LOG_I("%s: filename %s\n", __func__, filename); + LOG_I("%s: fullpath %s\n", __func__, Filepath); + pFile = fopen(Filepath, "r"); + if (pFile==NULL) + { + LOG_E("%s: Error looking for file 0x%.8x\n",__func__,TEE_ERROR_ITEM_NOT_FOUND); + return TEE_ERROR_ITEM_NOT_FOUND; + } + + res = fread(sth_request->payload,sizeof(char),sth_request->payloadLen,pFile); + fclose(pFile); + + if (res != sth_request->payloadLen) + { + LOG_E("%s: Error reading file res is %d and errno is %s\n",__func__,res,strerror(errno)); + return TEE_ERROR_ITEM_NOT_FOUND; + } + return TEE_SUCCESS; +} + + +mcResult_t FSD::FSD_ReadFile(void){ + FILE * pFile=NULL; + STH_FSD_message_t* sth_request=NULL; + uint32_t res=0; + string storage = getTlRegistryPath()+"/TbStorage"; + const char* tbstpath = storage.c_str(); + char tadirname[TEE_UUID_STRING_SIZE+1]; + char filename[2*FILENAMESIZE+1]; + char TAdirpath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1]; + char Filepath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1+2*FILENAMESIZE+1]; + + sth_request= &dci->sth_request; + //create TA folder name from TA UUID + FSD_CreateTaDirName(&sth_request->uuid,tadirname,sizeof(TEE_UUID)); + FSD_HexFileName(sth_request->filename,filename,FILENAMESIZE); + + //Create path to TA folder and test if does exist + strcpy(TAdirpath,tbstpath); + strcat(TAdirpath, "/"); + strcat(TAdirpath, tadirname); + + strcpy(Filepath, TAdirpath); + strcat(Filepath, "/"); + strcat(Filepath, filename); + LOG_I("%s: Storage %s\n", __func__, tbstpath); + LOG_I("%s: TA dirname %s\n", __func__, tadirname); + LOG_I("%s: filename %s\n", __func__, filename); + LOG_I("%s: fullpath %s\n", __func__, Filepath); + pFile = fopen(Filepath, "r"); + if (pFile==NULL) + { + LOG_E("%s: Error looking for file 0x%.8x\n", __func__,TEE_ERROR_ITEM_NOT_FOUND); + return TEE_ERROR_ITEM_NOT_FOUND; + } + res = fread(sth_request->payload,sizeof(char),sth_request->payloadLen,pFile); + + fclose(pFile); + + if (res != sth_request->payloadLen) + { + LOG_E("%s: Error reading file res is %d and errno is %s\n",__func__,res,strerror(errno)); + return TEE_ERROR_ITEM_NOT_FOUND; + } + return TEE_SUCCESS; +} + + +mcResult_t FSD::FSD_WriteFile(void){ + FILE * pFile=NULL; + int fd=0; + STH_FSD_message_t* sth_request=NULL; + uint32_t res=0; + int stat=0; + string storage = getTlRegistryPath()+"/TbStorage"; + const char* tbstpath = storage.c_str(); + char tadirname[TEE_UUID_STRING_SIZE+1]; + char filename[2*FILENAMESIZE+1]; + char TAdirpath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1]; + char Filepath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1+2*FILENAMESIZE+1]; + char Filepath_new[strlen(tbstpath)+TEE_UUID_STRING_SIZE+2*FILENAMESIZE+strlen(NEW_EXT)+1]; + + sth_request= &dci->sth_request; + + FSD_CreateTaDirName(&sth_request->uuid,tadirname,sizeof(TEE_UUID)); + FSD_HexFileName(sth_request->filename,filename,FILENAMESIZE); + + strcpy(TAdirpath,tbstpath); + strcat(TAdirpath, "/"); + strcat(TAdirpath, tadirname); + + stat = mkdir(TAdirpath, 0700); + if((stat==-1) && (errno!=EEXIST)) + { + LOG_I("%s: error when creating TA dir: %s (%s)\n",__func__,TAdirpath,strerror(errno)); + return TEE_ERROR_STORAGE_NO_SPACE; + } + + /* Directory exists. */ + strcpy(Filepath, TAdirpath); + strcat(Filepath, "/"); + strcat(Filepath, filename); + strcpy(Filepath_new,Filepath); + strcat(Filepath_new, NEW_EXT); + LOG_I("%s: Storage %s\n", __func__, tbstpath); + LOG_I("%s: TA dirname %s\n", __func__, tadirname); + LOG_I("%s: filename %s\n", __func__, filename); + LOG_I("%s: fullpath %s\n", __func__, Filepath); + LOG_I("%s: filename.new %s\n", __func__, Filepath_new); + if(sth_request->flags == TEE_DATA_FLAG_EXCLUSIVE) + { + LOG_I("%s: opening file in exclusive mode\n",__func__); + fd = open (Filepath, O_WRONLY | O_CREAT | O_EXCL, S_IWUSR); + if (fd == -1) + { + LOG_I("%s: error creating file: %s (%s)\n",__func__,Filepath,strerror(errno)); + return TEE_ERROR_ACCESS_CONFLICT; + } + else + { + close(fd); + } + } + pFile = fopen(Filepath_new, "w"); + LOG_I("%s: opening file for writing\n",__func__); + if(pFile==NULL) + { + remove(Filepath); + return TEE_ERROR_STORAGE_NO_SPACE; + } + res = fwrite(sth_request->payload,sizeof(char),sth_request->payloadLen,pFile); + + + if (res != sth_request->payloadLen) + { + LOG_E("%s: Error writing file res is %d and errno is %s\n",__func__,res,strerror(errno)); + fclose(pFile); + remove(Filepath); + remove(Filepath_new); + return TEE_ERROR_ITEM_NOT_FOUND; + } + else + { + res = fclose(pFile); + if (res < 0) + { + LOG_E("%s: Error closing file res is %d and errno is %s\n",__func__,res,strerror(errno)); + remove(Filepath); + remove(Filepath_new); + return TEE_ERROR_STORAGE_NO_SPACE; + } + + res = rename(Filepath_new,Filepath); + if (res < 0) + { + LOG_E("%s: Error renaming %s: %s\n",__func__,Filepath_new,strerror(errno)); + remove(Filepath); + remove(Filepath_new); + return TEE_ERROR_STORAGE_NO_SPACE; + } + } + return TEE_SUCCESS; +} + + +mcResult_t FSD::FSD_DeleteFile(void){ + FILE * pFile=NULL; + uint32_t res=0; + STH_FSD_message_t* sth_request=NULL; + string storage = getTlRegistryPath()+"/TbStorage"; + const char* tbstpath = storage.c_str(); + char tadirname[TEE_UUID_STRING_SIZE+1]; + char filename[2*FILENAMESIZE+1]; + char TAdirpath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1]; + char Filepath[strlen(tbstpath)+1+TEE_UUID_STRING_SIZE+1+2*FILENAMESIZE+1]; + + sth_request= &dci->sth_request; + + //create TA folder name from TA UUID + FSD_CreateTaDirName(&sth_request->uuid,tadirname,sizeof(TEE_UUID)); + FSD_HexFileName(sth_request->filename,filename,FILENAMESIZE); + + //Create path to TA folder and test if does exist + strcpy(TAdirpath,tbstpath); + strcat(TAdirpath, "/"); + strcat(TAdirpath, tadirname); + + /* Directory exists. */ + strcpy(Filepath, TAdirpath); + strcat(Filepath, "/"); + strcat(Filepath, filename); + LOG_I("%s: Storage %s\n", __func__, tbstpath); + LOG_I("%s: TA dirname %s\n", __func__, tadirname); + LOG_I("%s: filename %s\n", __func__, filename); + LOG_I("%s: fullpath %s\n", __func__, Filepath); + + pFile = fopen(Filepath, "r"); + if (pFile==NULL) + { + LOG_I("%s: file not found: %s (%s)\n",__func__, Filepath, strerror(errno)); + res = TEE_SUCCESS; + } + else + { + fclose(pFile); + if(remove(Filepath)==-1) + { + res = TEE_ERROR_STORAGE_NO_SPACE; + } + } + + LOG_I("%s: before rmdir res %d errno %d (%s)\n",__func__,res, errno,strerror(errno)); + + res = rmdir(TAdirpath); + + LOG_I("%s: after rmdir res %d errno %d (%s)\n",__func__,res, errno,strerror(errno)); + + if ((res < 0) && (errno != ENOTEMPTY) && (errno != EEXIST) && (errno != ENOENT)) + { + res = TEE_ERROR_STORAGE_NO_SPACE; + LOG_I("%s: rmdir failed: %s (%s)\n",__func__, TAdirpath, strerror(errno)); + } + else + { + res = TEE_SUCCESS; + } + + return res; +} + + +//------------------------------------------------------------------------------ + +/** @} */ diff --git a/mobicore/daemon/Daemon/FSD/public/FSD.h b/mobicore/daemon/Daemon/FSD/public/FSD.h new file mode 100644 index 0000000..9a44fa6 --- /dev/null +++ b/mobicore/daemon/Daemon/FSD/public/FSD.h @@ -0,0 +1,169 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * FSD server. + * + * Handles incoming storage requests from TA through STH + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 FSD_H_ +#define FSD_H_ + +#include +#include +#include +#include "CThread.h" +#include "MobiCoreDriverApi.h" +#include "drSecureStorage_Api.h" +#include +#include +#include +#include +#include + + +#define max( a, b ) ( ((a) > (b)) ? (a) : (b) ) +#define DCI_BUFF_SIZE 1000*1024 + +#define TEE_UUID_STRING_SIZE 32 +#define FILENAMESIZE 20 +#define NEW_EXT ".new" + +#define TAG_LOG "FSD" + +class FSD: public CThread +{ + +public: + /** + * FSD contructor. + * + * @param tbstoragepath Absolute path to the secure storage + */ + FSD( + void + ); + + /** + * FSD destructor. + * Close the current session and resources will be freed. + */ + virtual ~FSD( + void + ); + + /** + * Start server and listen for incoming request from STH. + */ + virtual void run(void); + + /* + * FSD_Open + * + * Open a session with the STH + * + */ + virtual mcResult_t FSD_Open(void); + + + /* + * FSD_Close + * + * Close a session opened with the STH + * + */ + virtual mcResult_t FSD_Close(void); + + + /* + * FSD_listenDci + * + * DCI listener function + * + */ + virtual void FSD_listenDci(void); + + + +private: + mcSessionHandle_t sessionHandle; /**< current session */ + dciMessage_t* dci; /**< dci buffer */ + + + /** Private methods*/ + + /* + * FSD_ExecuteCommand + * + * Execute command received from the STH + * + */ + mcResult_t FSD_ExecuteCommand(void); + + /**************************** File operations *******************************/ + + /* + * FSD_LookFile + * + * look for a file + */ + mcResult_t FSD_LookFile(void); + + + /* + * FSD_ReadFile + * + * Read a file + */ + mcResult_t FSD_ReadFile(void); + + + /* + * FSD_WriteFile + * + * Write a file + */ + mcResult_t FSD_WriteFile(void); + + + /* + * FSD_DeleteFile + * + * Delete a file + */ + mcResult_t FSD_DeleteFile(void); +}; + +#endif /* FSD_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/FSD/public/dci.h b/mobicore/daemon/Daemon/FSD/public/dci.h new file mode 100644 index 0000000..c805f5c --- /dev/null +++ b/mobicore/daemon/Daemon/FSD/public/dci.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * @file dci.h + * @brief Contains DCI (Driver Control + * Interface) definitions and data structures + * + */ + +#ifndef __DCI_H__ +#define __DCI_H__ + + +typedef uint32_t dciCommandId_t; +typedef uint32_t dciResponseId_t; +typedef uint32_t dciReturnCode_t; + +/**< Responses have bit 31 set */ +#define RSP_ID_MASK (1U << 31) +#define RSP_ID(cmdId) (((uint32_t)(cmdId)) | RSP_ID_MASK) +#define IS_CMD(cmdId) ((((uint32_t)(cmdId)) & RSP_ID_MASK) == 0) +#define IS_RSP(cmdId) ((((uint32_t)(cmdId)) & RSP_ID_MASK) == RSP_ID_MASK) + +/** + * Return codes of driver commands. + */ +#define RET_OK 0 +#define RET_ERR_UNKNOWN_CMD 1 +#define RET_ERR_NOT_SUPPORTED 2 +#define RET_ERR_INTERNAL_ERROR 3 +/* ... add more error codes when needed */ + +/** + * DCI command header. + */ +typedef struct{ + dciCommandId_t commandId; /**< Command ID */ +} dciCommandHeader_t; + +/** + * DCI response header. + */ +typedef struct{ + dciResponseId_t responseId; /**< Response ID (must be command ID | RSP_ID_MASK )*/ + dciReturnCode_t returnCode; /**< Return code of command */ +} dciResponseHeader_t; + +#endif // __DCI_H__ diff --git a/mobicore/daemon/Daemon/FSD/public/drSecureStorage_Api.h b/mobicore/daemon/Daemon/FSD/public/drSecureStorage_Api.h new file mode 100644 index 0000000..6c881e3 --- /dev/null +++ b/mobicore/daemon/Daemon/FSD/public/drSecureStorage_Api.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved + * + * The present software is the confidential and proprietary information of + * TRUSTONIC LIMITED. You shall not disclose the present software and shall + * use it only in accordance with the terms of the license agreement you + * entered into with TRUSTONIC LIMITED. This software may be subject to + * export or import laws in certain countries. + */ + +/** + * @file drSecureStorage_Api.h + * @brief Contains DCI command definitions and data structures + * + */ + +#ifndef __DRTEMPLATEAPI_H__ +#define __DRTEMPLATEAPI_H__ + +#include "dci.h" +#include "tee_internal_api.h" + + +#define RW_DATA_SIZE 4096 + +/** + * Command ID's for communication + * FSD <--> STH + */ + +#define STH_MESSAGE_TYPE_LOOK 0 +#define STH_MESSAGE_TYPE_READ 1 +#define STH_MESSAGE_TYPE_WRITE 2 +#define STH_MESSAGE_TYPE_DELETE 3 + +#define CMD_ST_SYNC 5 +#define NOTIFY_DCIH 6 +#define NOTIFY_IPCH 7 +/*... add more command ids when needed */ + +#define STH_PUBLIC_FILE_NAME_SIZE 20 + +typedef struct { + uint32_t status; + uint8_t type; + uint8_t reserved0; + uint16_t flags; + uint32_t payloadLen; + TEE_UUID uuid; + unsigned char filename[STH_PUBLIC_FILE_NAME_SIZE]; + unsigned char payload[]; +} STH_FSD_message_t; + +typedef struct +{ + char header[5]; + unsigned char version; + uint16_t cryptoLen; + uint32_t dataLen; +}FSD_plaintext; + +/** + * command message. + * + * @param len Lenght of the data to process. + * @param data Data to be processed + */ +typedef struct { + dciCommandHeader_t header; /**< Command header */ + uint32_t len; /**< Length of data to process */ +} cmd_t; + + +/** + * Response structure + */ +typedef struct { + dciResponseHeader_t header; /**< Response header */ + uint32_t len; +} rsp_t; + +/** + * DCI message data. + */ +typedef struct { + union { + cmd_t command; + rsp_t response; + }; + + STH_FSD_message_t sth_request; +} dciMessage_t; + +/** + * Driver UUID. Update accordingly after reserving UUID + */ +#define DRV_STH_UUID { { 0x07, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } + + +#endif // __DRTEMPLATEAPI_H__ diff --git a/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp b/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp new file mode 100644 index 0000000..b4a6b81 --- /dev/null +++ b/mobicore/daemon/Daemon/MobiCoreDriverDaemon.cpp @@ -0,0 +1,1484 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_CONHDLR + * @{ + * @file + * + * Entry of the MobiCore Driver. + */ + +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ + +#include +#include +#include +#include + +#include "mcVersion.h" +#include "mcVersionHelper.h" +#include "mc_linux.h" +#include "log.h" +#include "Mci/mci.h" + +#include "MobiCoreDriverApi.h" +#include "MobiCoreDriverCmd.h" +#include "MobiCoreDriverDaemon.h" +#include "PrivateRegistry.h" +#include "MobiCoreDevice.h" +#include "NetlinkServer.h" +#include "FSD.h" + +#define DRIVER_TCI_LEN 4096 + +MC_CHECK_VERSION(MCI, 0, 2); +MC_CHECK_VERSION(SO, 2, 0); +MC_CHECK_VERSION(MCLF, 2, 0); +MC_CHECK_VERSION(CONTAINER, 2, 0); + +static void checkMobiCoreVersion(MobiCoreDevice *mobiCoreDevice); + +#define LOG_I_RELEASE(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) + +pthread_mutex_t syncMutex = PTHREAD_MUTEX_INITIALIZER; +pthread_cond_t syncCondition = PTHREAD_COND_INITIALIZER; +bool Th_sync=false; + +//------------------------------------------------------------------------------ +MobiCoreDriverDaemon::MobiCoreDriverDaemon( + bool enableScheduler, + bool loadDriver, + std::vector drivers) +{ + mobiCoreDevice = NULL; + + this->enableScheduler = enableScheduler; + this->loadDriver = loadDriver; + this->drivers = drivers; + + for (int i = 0; i < MAX_SERVERS; i++) { + servers[i] = NULL; + } +} + +//------------------------------------------------------------------------------ +MobiCoreDriverDaemon::~MobiCoreDriverDaemon( + void +) +{ + // Unload any device drivers might have been loaded + driverResourcesList_t::iterator it; + for (it = driverResources.begin(); it != driverResources.end(); it++) { + MobicoreDriverResources *res = *it; + mobiCoreDevice->closeSession(res->conn, res->sessionId); + mobiCoreDevice->unregisterWsmL2(res->pTciWsm); + } + delete mobiCoreDevice; + for (int i = 0; i < MAX_SERVERS; i++) { + delete servers[i]; + servers[i] = NULL; + } +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::run( + void +) +{ + const char *devNode = "/dev/" MC_ADMIN_DEVNODE; + + LOG_I_RELEASE("Daemon starting up..."); + LOG_I_RELEASE("Socket interface version is %u.%u", DAEMON_VERSION_MAJOR, DAEMON_VERSION_MINOR); + +#ifdef MOBICORE_COMPONENT_BUILD_TAG + LOG_I_RELEASE("%s", MOBICORE_COMPONENT_BUILD_TAG); +#else +#warning "MOBICORE_COMPONENT_BUILD_TAG is not defined!" +#endif + + LOG_I_RELEASE("Build timestamp is %s %s", __DATE__, __TIME__); + + int i; + + mobiCoreDevice = getDeviceInstance(); + + LOG_I("Initializing Device, Daemon sheduler is %s", + enableScheduler ? "enabled" : "disabled"); + + // initialize device (setupo MCI) + if (!mobiCoreDevice->initDevice( + devNode, + enableScheduler)) { + LOG_E("Could not initialize start(); + + // Load device driver if requested + if (loadDriver) { + for (unsigned int i = 0; i < drivers.size(); i++) + loadDeviceDriver(drivers[i]); + } + + /* Look for tokens in the registry and pass them to start(i ? "McDaemon.Server" : "NetlinkServer"); + } + + // Create the start("McDaemon.FSD"); + + // then wait for them to exit + for (i = 0; i < MAX_SERVERS; i++) { + servers[i]->join(); + } + //Wait for File Storage Daemon to exit + FileStorageDaemon->join(); + delete FileStorageDaemon; +} + +//------------------------------------------------------------------------------ +bool MobiCoreDriverDaemon::checkPermission(Connection *connection __unused) +{ +#ifdef REGISTRY_CHECK_PERMISSIONS + struct ucred cred; + if (!connection) + return true; + + if (connection->getPeerCredentials(cred)) { + gid_t gid = getegid(); + uid_t uid = geteuid(); + LOG_I("Peer connection has pid = %u and uid = %u gid = %u", cred.pid, cred.uid, cred.gid); + LOG_I("Daemon has uid = %u gid = %u", cred.uid, cred.gid); + // If the daemon and the peer have the same uid or gid then we're good + if (gid == cred.gid || uid == cred.uid) { + return true; + } + return false; + + } + return false; +#else + return true; +#endif +} + +//------------------------------------------------------------------------------ +MobiCoreDevice *MobiCoreDriverDaemon::getDevice( + uint32_t deviceId +) +{ + // Always return the trustZoneDevice as it is currently the only one supported + if (MC_DEVICE_ID_DEFAULT != deviceId) + return NULL; + return mobiCoreDevice; +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::dropConnection( + Connection *connection +) +{ + // Check if a Device has already been registered with the connection + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + + if (device != NULL) { + // A connection has been found and has to be closed + LOG_I("dropConnection(): closing still open device."); + + // Make sure nobody else writes the MCP, e.g. netlink/socket server, cleanup of TAs + device->mutex_mcp.lock(); + device->close(connection); + device->mutex_mcp.unlock(); + } +} + + +//------------------------------------------------------------------------------ +size_t MobiCoreDriverDaemon::writeResult( + Connection *connection, + mcResult_t code +) +{ + if (0 != code) { + LOG_V(" sending error code %d", code); + } + return connection->writeData(&code, sizeof(mcResult_t)); +} + +//------------------------------------------------------------------------------ +bool MobiCoreDriverDaemon::loadDeviceDriver( + std::string driverPath +) +{ + bool ret = false; + CWsm_ptr pWsm = NULL, pTciWsm = NULL; + regObject_t *regObj = NULL; + Connection *conn = NULL; + mcDrvRspOpenSession_t rspOpenSession; + + do { + //mobiCoreDevice + LOG_I("%s: loading %s", __FUNCTION__, driverPath.c_str()); + + regObj = mcRegistryGetDriverBlob(driverPath.c_str()); + if (regObj == NULL) { + break;; + } + + LOG_I("registering L2 in kmod, p=%p, len=%i", + regObj->value, regObj->len); + + pWsm = mobiCoreDevice->registerWsmL2( + (addr_t)(regObj->value), regObj->len, 0); + if (pWsm == NULL) { + LOG_E("allocating WSM for Trustlet failed"); + break; + } + // Initialize information data of open session command + loadDataOpenSession_t loadDataOpenSession; + loadDataOpenSession.baseAddr = pWsm->physAddr; + loadDataOpenSession.offs = ((uintptr_t) regObj->value) & 0xFFF; + loadDataOpenSession.len = regObj->len; + loadDataOpenSession.tlHeader = (mclfHeader_ptr) (regObj->value + regObj->tlStartOffset); + + pTciWsm = mobiCoreDevice->allocateContiguousPersistentWsm(DRIVER_TCI_LEN); + if (pTciWsm == NULL) { + LOG_E("allocating WSM TCI for Trustlet failed"); + break; + } + + conn = new Connection(); + uint32_t mcRet = mobiCoreDevice->openSession( + conn, + &loadDataOpenSession, + pTciWsm->handle, + pTciWsm->len, + 0, + &(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 (mcRet != MC_MCP_RET_OK) { + LOG_E("open session error %d", mcRet); + break; + } + + ret = true; + } while (false); + // Free all allocated resources + if (ret == false) { + 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 + delete pWsm; + } + } + // No matter if we free NULL objects + free(regObj); + + if (conn != NULL) { + delete conn; + } + } else if (conn != NULL) { + driverResources.push_back(new MobicoreDriverResources( + conn, pTciWsm, rspOpenSession.payload.sessionId)); + } + + return ret; +} + +#define RECV_PAYLOAD_FROM_CLIENT(CONNECTION, CMD_BUFFER) \ +{ \ + void *payload = (void*)((uintptr_t)CMD_BUFFER + sizeof(mcDrvCommandHeader_t)); \ + uint32_t payload_len = sizeof(*CMD_BUFFER) - sizeof(mcDrvCommandHeader_t); \ + int32_t rlen = CONNECTION->readData(payload, payload_len); \ + if (rlen < 0) { \ + LOG_E("reading from Client failed"); \ + /* it is questionable, if writing to broken socket has any effect here. */ \ + writeResult(CONNECTION, MC_DRV_ERR_DAEMON_SOCKET); \ + return; \ + } \ + if (rlen != (int32_t)payload_len) {\ + LOG_E("wrong buffer length %i received from Client", rlen); \ + writeResult(CONNECTION, MC_DRV_ERR_DAEMON_SOCKET); \ + return; \ + } \ +} + +#define CHECK_DEVICE(DEVICE, CONNECTION) \ + if (DEVICE == NULL) \ + { \ + LOG_V("%s: no device associated with connection",__FUNCTION__); \ + writeResult(CONNECTION, MC_DRV_ERR_DAEMON_DEVICE_NOT_OPEN); \ + return; \ + } + +//------------------------------------------------------------------------------ +inline bool getData(Connection *con, void *buf, uint32_t len) +{ + uint32_t rlen = con->readData(buf, len); + if (rlen < len || (int32_t)rlen < 0) { + LOG_E("reading from Client failed"); + return false; + } + return true; +} + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processOpenDevice(Connection *connection) +{ + MC_DRV_CMD_OPEN_DEVICE_struct cmdOpenDevice; + RECV_PAYLOAD_FROM_CLIENT(connection, &cmdOpenDevice); + + // Check if device has been registered to the connection + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + if (NULL != device) { + LOG_E("processOpenDevice(): device already set"); + writeResult(connection, MC_DRV_ERR_DEVICE_ALREADY_OPEN); + return; + } + + LOG_I(" Opening deviceId %d ", cmdOpenDevice.deviceId); + + // Get device for device ID + device = getDevice(cmdOpenDevice.deviceId); + + // Check if a device for the given name has been found + if (device == NULL) { + LOG_E("invalid deviceId"); + writeResult(connection, MC_DRV_ERR_UNKNOWN_DEVICE); + return; + } + + // Register device object with connection + device->open(connection); + + // Return result code to client lib (no payload) + writeResult(connection, MC_DRV_OK); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processCloseDevice( + Connection *connection +) +{ + // there is no payload to read + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + // No command data will be read + // Unregister device object with connection + device->close(connection); + + // there is no payload + writeResult(connection, MC_DRV_OK); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processOpenSession(Connection *connection, bool isGpUuid) +{ + MC_DRV_CMD_OPEN_SESSION_struct cmdOpenSession; + RECV_PAYLOAD_FROM_CLIENT(connection, &cmdOpenSession); + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + // Get service blob from registry + regObject_t *regObj = mcRegistryGetServiceBlob(&cmdOpenSession.uuid, isGpUuid); + if (NULL == regObj) { + writeResult(connection, MC_DRV_ERR_TRUSTLET_NOT_FOUND); + return; + } + if (regObj->len == 0) { + free(regObj); + writeResult(connection, MC_DRV_ERR_TRUSTLET_NOT_FOUND); + return; + } + LOG_I(" Sharing Service loaded at %p with Secure World", (addr_t)(regObj->value)); + + CWsm_ptr pWsm = device->registerWsmL2((addr_t)(regObj->value), regObj->len, 0); + if (pWsm == NULL) { + // Free memory occupied by Trustlet data + free(regObj); + LOG_E("allocating WSM for Trustlet failed"); + writeResult(connection, MC_DRV_ERR_DAEMON_KMOD_ERROR); + return; + } + // Initialize information data of open session command + loadDataOpenSession_t loadDataOpenSession; + loadDataOpenSession.baseAddr = pWsm->physAddr; + loadDataOpenSession.offs = ((uintptr_t) regObj->value) & 0xFFF; + loadDataOpenSession.len = regObj->len; + loadDataOpenSession.tlHeader = (mclfHeader_ptr) (regObj->value + regObj->tlStartOffset); + + mcDrvRspOpenSession_t rspOpenSession; + mcResult_t ret = device->openSession( + connection, + &loadDataOpenSession, + cmdOpenSession.handle, + cmdOpenSession.len, + cmdOpenSession.tci, + &rspOpenSession.payload); + + // Unregister physical memory from kernel module. + 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 might still be running. + free(regObj); + writeResult(connection, MC_DRV_ERR_DAEMON_KMOD_ERROR); + return; + } + + // Free memory occupied by Trustlet data + free(regObj); + + if (ret != MC_DRV_OK) { + LOG_E("Service could not be loaded."); + writeResult(connection, ret); + } else { + rspOpenSession.header.responseId = ret; + connection->writeData( + &rspOpenSession, + sizeof(rspOpenSession)); + } +} + +//------------------------------------------------------------------------------ +mcResult_t MobiCoreDriverDaemon::processLoadCheck(mcSpid_t spid, void *blob, uint32_t size) +{ + + // Device required + MobiCoreDevice *device = getDevice(MC_DEVICE_ID_DEFAULT); + + if (device == NULL) { + LOG_E(" No device found"); + return MC_DRV_ERR_DAEMON_DEVICE_NOT_OPEN; + } + + // Get service blob from registry + regObject_t *regObj = mcRegistryMemGetServiceBlob(spid, blob, size); + if (NULL == regObj) { + LOG_E(" mcRegistryMemGetServiceBlob failed"); + return MC_DRV_ERR_TRUSTLET_NOT_FOUND; + } + if (regObj->len == 0) { + free(regObj); + LOG_E("mcRegistryMemGetServiceBlob returned registry object with length equal to zero"); + return MC_DRV_ERR_TRUSTLET_NOT_FOUND; + } + LOG_I(" Sharing Service loaded at %p with Secure World", (addr_t)(regObj->value)); + + CWsm_ptr pWsm = device->registerWsmL2((addr_t)(regObj->value), regObj->len, 0); + if (pWsm == NULL) { + // Free memory occupied by Trustlet data + free(regObj); + LOG_E("allocating WSM for Trustlet failed"); + return MC_DRV_ERR_DAEMON_KMOD_ERROR; + } + // Initialize information data of open session command + loadDataOpenSession_t loadDataOpenSession; + loadDataOpenSession.baseAddr = pWsm->physAddr; + loadDataOpenSession.offs = ((uintptr_t) regObj->value) & 0xFFF; + loadDataOpenSession.len = regObj->len; + loadDataOpenSession.tlHeader = (mclfHeader_ptr) (regObj->value + regObj->tlStartOffset); + + mcDrvRspOpenSession_t rspOpenSession; + mcResult_t ret = device->checkLoad( + &loadDataOpenSession, + &rspOpenSession.payload); + + // Unregister physical memory from kernel module. + 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)) { + // Free memory occupied by Trustlet data + free(regObj); + LOG_E("deallocating WSM for Trustlet failed"); + return MC_DRV_ERR_DAEMON_KMOD_ERROR; + } + + // Free memory occupied by Trustlet data + free(regObj); + + if (ret != MC_DRV_OK) { + LOG_E("TA could not be loaded."); + return ret; + } else { + return MC_DRV_OK; + } +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processOpenTrustlet(Connection *connection) +{ + MC_DRV_CMD_OPEN_TRUSTLET_struct cmdOpenTrustlet; + RECV_PAYLOAD_FROM_CLIENT(connection, &cmdOpenTrustlet); + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + uint32_t total_len, rlen, len = cmdOpenTrustlet.trustlet_len; + uint8_t *payload = (uint8_t *)malloc(len); + uint8_t *p = payload; + if (payload == NULL) { + LOG_E("failed to allocate payload buffer"); + writeResult(connection, MC_DRV_ERR_DAEMON_SOCKET); + return; + } + total_len = 0; + while (total_len < len) { + rlen = connection->readData(p, len - total_len); + if ((int32_t)rlen < 0) { + LOG_E("reading from Client failed"); + /* it is questionable, if writing to broken socket has any effect here. */ + writeResult(connection, MC_DRV_ERR_DAEMON_SOCKET); + free(payload); + return; + } + total_len += rlen; + p += rlen; + } + + // Get service blob from registry + regObject_t *regObj = mcRegistryMemGetServiceBlob(cmdOpenTrustlet.spid, (uint8_t *)payload, len); + + // Free the payload object no matter what + free(payload); + if (regObj == NULL) { + writeResult(connection, MC_DRV_ERR_TRUSTLET_NOT_FOUND); + return; + } + + if (regObj->len == 0) { + free(regObj); + writeResult(connection, MC_DRV_ERR_TRUSTLET_NOT_FOUND); + return; + } + LOG_I(" Sharing Service loaded at %p with Secure World", (addr_t)(regObj->value)); + + CWsm_ptr pWsm = device->registerWsmL2((addr_t)(regObj->value), regObj->len, 0); + if (pWsm == NULL) { + free(regObj); + LOG_E("allocating WSM for Trustlet failed"); + writeResult(connection, MC_DRV_ERR_DAEMON_KMOD_ERROR); + return; + } + // Initialize information data of open session command + loadDataOpenSession_t loadDataOpenSession; + loadDataOpenSession.baseAddr = pWsm->physAddr; + loadDataOpenSession.offs = ((uintptr_t) regObj->value) & 0xFFF; + loadDataOpenSession.len = regObj->len; + loadDataOpenSession.tlHeader = (mclfHeader_ptr) (regObj->value + regObj->tlStartOffset); + + mcDrvRspOpenSession_t rspOpenSession; + mcResult_t ret = device->openSession( + connection, + &loadDataOpenSession, + cmdOpenTrustlet.handle, + cmdOpenTrustlet.len, + cmdOpenTrustlet.tci, + &rspOpenSession.payload); + + // Unregister physical memory from kernel module. + 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)) { + free(regObj); + // TODO-2012-07-02-haenellu: Can this ever happen? And if so, we should assert(), also TL might still be running. + writeResult(connection, MC_DRV_ERR_DAEMON_KMOD_ERROR); + return; + } + + // Free memory occupied by Trustlet data + free(regObj); + + if (ret != MC_DRV_OK) { + LOG_E("Service could not be loaded."); + writeResult(connection, ret); + } else { + rspOpenSession.header.responseId = ret; + connection->writeData( + &rspOpenSession, + sizeof(rspOpenSession)); + } +} + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processCloseSession(Connection *connection) +{ + MC_DRV_CMD_CLOSE_SESSION_struct cmdCloseSession; + RECV_PAYLOAD_FROM_CLIENT(connection, &cmdCloseSession) + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + mcResult_t ret = device->closeSession(connection, cmdCloseSession.sessionId); + + // there is no payload + writeResult(connection, ret); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processNqConnect(Connection *connection) +{ + // Set up the channel for sending SWd notifications to the client + // MC_DRV_CMD_NQ_CONNECT is only allowed on new connections not + // associated with a device. If a device is registered to the + // connection NQ_CONNECT is not allowed. + + // Read entire command data + MC_DRV_CMD_NQ_CONNECT_struct cmd; + RECV_PAYLOAD_FROM_CLIENT(connection, &cmd); + + // device must be empty since this is a new connection + MobiCoreDevice *device = (MobiCoreDevice *)(connection->connectionData); + if (device != NULL) { + LOG_E("device already set\n"); + writeResult(connection, MC_DRV_ERR_NQ_FAILED); + return; + } + + // Remove the connection from the list of known client connections + for (int i = 0; i < MAX_SERVERS; i++) { + servers[i]->detachConnection(connection); + } + + device = getDevice(cmd.deviceId); + // Check if a device for the given name has been found + if (NULL == device) { + LOG_E("invalid deviceId"); + writeResult(connection, MC_DRV_ERR_UNKNOWN_DEVICE); + return; + } + + TrustletSession *ts = device->registerTrustletConnection( + connection, + &cmd); + if (!ts) { + LOG_E("registerTrustletConnection() failed!"); + writeResult(connection, MC_DRV_ERR_UNKNOWN); + return; + } + + writeResult(connection, MC_DRV_OK); + ts->processQueuedNotifications(); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processNotify(Connection *connection) +{ + // Read entire command data + MC_DRV_CMD_NOTIFY_struct cmd; + //RECV_PAYLOAD_FROM_CLIENT(connection, &cmd); + void *payload = (void *)((uintptr_t)&cmd + sizeof(mcDrvCommandHeader_t)); + uint32_t payload_len = sizeof(cmd) - sizeof(mcDrvCommandHeader_t); + uint32_t rlen = connection->readData(payload, payload_len); + if ((int) rlen < 0) { + LOG_E("reading from Client failed"); + /* it is questionable, if writing to broken socket has any effect here. */ + // NOTE: notify fails silently + //writeResult(connection, MC_DRV_RSP_SOCKET_ERROR); + return; + } + if (rlen != payload_len) { + LOG_E("wrong buffer length %i received from Client", rlen); + // NOTE: notify fails silently + //writeResult(connection, MC_DRV_RSP_PAYLOAD_LENGTH_ERROR); + return; + } + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + if (NULL == device) { + LOG_V("%s: no device associated with connection", __FUNCTION__); + // NOTE: notify fails silently + // writeResult(connection,MC_DRV_RSP_DEVICE_NOT_OPENED); + return; + } + + device->notify(connection, cmd.sessionId); + // NOTE: for notifications there is no response at all +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processMapBulkBuf(Connection *connection) +{ + MC_DRV_CMD_MAP_BULK_BUF_struct cmd; + + RECV_PAYLOAD_FROM_CLIENT(connection, &cmd); + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + if (!device->lockWsmL2(cmd.handle)) { + LOG_E("Couldn't lock the buffer!"); + writeResult(connection, MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND); + return; + } + + uint32_t secureVirtualAdr = (uint32_t)NULL; + uint64_t pAddrL2 = device->findWsmL2(cmd.handle, connection->socketDescriptor); + + if (pAddrL2 == 0) { + LOG_E("Failed to resolve WSM with handle %u", cmd.handle); + writeResult(connection, MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND); + return; + } + + // Map bulk memory to secure world + mcResult_t mcResult = device->mapBulk(connection, cmd.sessionId, cmd.handle, pAddrL2, + cmd.offsetPayload, cmd.lenBulkMem, &secureVirtualAdr); + + if (mcResult != MC_DRV_OK) { + writeResult(connection, mcResult); + return; + } + + mcDrvRspMapBulkMem_t rsp; + rsp.header.responseId = MC_DRV_OK; + rsp.payload.sessionId = cmd.sessionId; + rsp.payload.secureVirtualAdr = secureVirtualAdr; + connection->writeData(&rsp, sizeof(mcDrvRspMapBulkMem_t)); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processUnmapBulkBuf(Connection *connection) +{ + MC_DRV_CMD_UNMAP_BULK_BUF_struct cmd; + RECV_PAYLOAD_FROM_CLIENT(connection, &cmd) + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + // Unmap bulk memory from secure world + uint32_t mcResult = device->unmapBulk(connection, cmd.sessionId, cmd.handle, + cmd.secureVirtualAdr, cmd.lenBulkMem); + + if (mcResult != MC_DRV_OK) { + LOG_V("MCP UNMAP returned code %d", mcResult); + writeResult(connection, mcResult); + return; + } + + // TODO-2012-09-06-haenellu: Think about not ignoring the error case. + device->unlockWsmL2(cmd.handle); + + writeResult(connection, MC_DRV_OK); +} + + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processGetVersion( + Connection *connection +) +{ + // there is no payload to read + + mcDrvRspGetVersion_t rspGetVersion; + rspGetVersion.version = MC_MAKE_VERSION(DAEMON_VERSION_MAJOR, DAEMON_VERSION_MINOR); + rspGetVersion.responseId = MC_DRV_OK; + + connection->writeData(&rspGetVersion, sizeof(mcDrvRspGetVersion_t)); +} + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processGetMobiCoreVersion( + Connection *connection +) +{ + // there is no payload to read + + // Device required + MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData); + CHECK_DEVICE(device, connection); + + // Get getMobiCoreVersion(&rspGetMobiCoreVersion.payload); + + if (mcResult != MC_DRV_OK) { + LOG_V("MC GET_MOBICORE_VERSION returned code %d", mcResult); + writeResult(connection, mcResult); + return; + } + + rspGetMobiCoreVersion.header.responseId = MC_DRV_OK; + connection->writeData( + &rspGetMobiCoreVersion, + sizeof(rspGetMobiCoreVersion)); +} + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processRegistryReadData(uint32_t commandId, Connection *connection) +{ +#define MAX_DATA_SIZE 512 +mcDrvResponseHeader_t rspRegistry = { .responseId = + MC_DRV_ERR_INVALID_OPERATION + }; + void *buf = alloca(MAX_DATA_SIZE); + uint32_t len = MAX_DATA_SIZE; + mcSoAuthTokenCont_t auth; + mcSpid_t spid; + mcUuid_t uuid; + + if (!checkPermission(connection)) { + connection->writeData(&rspRegistry, sizeof(rspRegistry)); + return; + } + + switch (commandId) { + case MC_DRV_REG_READ_AUTH_TOKEN: + rspRegistry.responseId = mcRegistryReadAuthToken(&auth); + buf = &auth; + len = sizeof(mcSoAuthTokenCont_t); + break; + case MC_DRV_REG_READ_ROOT_CONT: + rspRegistry.responseId = mcRegistryReadRoot(buf, &len); + break; + case MC_DRV_REG_READ_SP_CONT: + if (!getData(connection, &spid, sizeof(spid))) + break; + rspRegistry.responseId = mcRegistryReadSp(spid, buf, &len); + break; + case MC_DRV_REG_READ_TL_CONT: + if (!getData(connection, &uuid, sizeof(uuid))) + break; + if (!getData(connection, &spid, sizeof(spid))) + break; + rspRegistry.responseId = mcRegistryReadTrustletCon(&uuid, spid, buf, &len); + break; + default: + break; + } + connection->writeData(&rspRegistry, sizeof(rspRegistry)); + if (rspRegistry.responseId != MC_DRV_ERR_INVALID_OPERATION) + connection->writeData(buf, len); +} + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processRegistryWriteData(uint32_t commandId, Connection *connection) +{ +mcDrvResponseHeader_t rspRegistry = { .responseId = + MC_DRV_ERR_INVALID_OPERATION + }; + uint32_t soSize; + void *so; + + if (!checkPermission(connection)) { + connection->writeData(&rspRegistry, sizeof(rspRegistry)); + return; + } + + // First read the SO data size + if (!getData(connection, &soSize, sizeof(soSize))) { + LOG_E("Failed to read SO data size"); + connection->writeData(&rspRegistry, sizeof(rspRegistry)); + return; + } + so = malloc(soSize); + if (so == NULL) { + LOG_E("Allocation failure"); + rspRegistry.responseId = MC_DRV_ERR_NO_FREE_MEMORY; + connection->writeData(&rspRegistry, sizeof(rspRegistry)); + return; + } + + switch (commandId) { + case MC_DRV_REG_STORE_AUTH_TOKEN: { + if (!getData(connection, so, soSize)) + break; + rspRegistry.responseId = mcRegistryStoreAuthToken(so, soSize); + break; + } + case MC_DRV_REG_WRITE_ROOT_CONT: { + if (!getData(connection, so, soSize)) + break; + rspRegistry.responseId = mcRegistryStoreRoot(so, soSize); + break; + } + case MC_DRV_REG_WRITE_SP_CONT: { + mcSpid_t spid; + if (!getData(connection, &spid, sizeof(spid))) + break; + if (!getData(connection, so, soSize)) + break; + rspRegistry.responseId = mcRegistryStoreSp(spid, so, soSize); + break; + } + case MC_DRV_REG_WRITE_TL_CONT: { + mcUuid_t uuid; + mcSpid_t spid; + if (!getData(connection, &uuid, sizeof(uuid))) + break; + if (!getData(connection, &spid, sizeof(spid))) + break; + if (!getData(connection, so, soSize)) + break; + rspRegistry.responseId = mcRegistryStoreTrustletCon(&uuid, spid, so, soSize); + break; + } + case MC_DRV_REG_WRITE_SO_DATA: { + if (!getData(connection, so, soSize)) + break; + rspRegistry.responseId = mcRegistryStoreData(so, soSize); + break; + } + case MC_DRV_REG_STORE_TA_BLOB: { + uint32_t blobSize = soSize; + mcSpid_t spid; + void *blob; + if (!getData(connection, &spid, sizeof(spid))) + break; + blob = malloc(blobSize); + if (blob == NULL) { + LOG_E("Allocation failure"); + rspRegistry.responseId = MC_DRV_ERR_NO_FREE_MEMORY; + break; + } + if (!getData(connection, blob, blobSize)) { + free(blob); + break; + } + //LOG_I("processLoadCheck"); + rspRegistry.responseId = processLoadCheck(spid, blob, blobSize); + if (rspRegistry.responseId != MC_DRV_OK){ + LOG_I("processLoadCheck failed"); + free(blob); + break; + } + //LOG_I("mcRegistryStoreTABlob"); + rspRegistry.responseId = mcRegistryStoreTABlob(spid, blob, blobSize); + free(blob); + break; + } + default: + break; + } + free(so); + connection->writeData(&rspRegistry, sizeof(rspRegistry)); +} + +//------------------------------------------------------------------------------ +void MobiCoreDriverDaemon::processRegistryDeleteData(uint32_t commandId, Connection *connection) +{ +mcDrvResponseHeader_t rspRegistry = { .responseId = + MC_DRV_ERR_INVALID_OPERATION + }; + mcSpid_t spid; + + if (!checkPermission(connection)) { + connection->writeData(&rspRegistry, sizeof(rspRegistry)); + return; + } + + switch (commandId) { + case MC_DRV_REG_DELETE_AUTH_TOKEN: + rspRegistry.responseId = mcRegistryDeleteAuthToken(); + break; + case MC_DRV_REG_DELETE_ROOT_CONT: + rspRegistry.responseId = mcRegistryCleanupRoot(); + break; + case MC_DRV_REG_DELETE_SP_CONT: + if (!getData(connection, &spid, sizeof(spid))) + break; + rspRegistry.responseId = mcRegistryCleanupSp(spid); + break; + case MC_DRV_REG_DELETE_TL_CONT: + mcUuid_t uuid; + if (!getData(connection, &uuid, sizeof(uuid))) + break; + if (!getData(connection, &spid, sizeof(spid))) + break; + rspRegistry.responseId = mcRegistryCleanupTrustlet(&uuid, spid); + break; + default: + break; + } + + connection->writeData(&rspRegistry, sizeof(rspRegistry)); +} + +//------------------------------------------------------------------------------ +bool MobiCoreDriverDaemon::handleConnection( + Connection *connection +) +{ + bool ret = false; + + // This is the big lock around everything the Daemon does, including socket and MCI access + 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()) { + LOG_I("Ignore request, mutex_mcp.lock(); + + LOG_I("handleConnection()==== %p", connection); + do { + // Read header + mcDrvCommandHeader_t mcDrvCommandHeader; + ssize_t rlen = connection->readData( + &(mcDrvCommandHeader), + sizeof(mcDrvCommandHeader)); + + if (rlen == 0) { + LOG_V(" handleConnection(): Connection closed."); + break; + } + if (rlen == -1) { + LOG_E("Socket error."); + break; + } + if (rlen == -2) { + LOG_E("Timeout."); + break; + } + ret = true; + + switch (mcDrvCommandHeader.commandId) { + //----------------------------------------- + case MC_DRV_CMD_OPEN_DEVICE: + processOpenDevice(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_CLOSE_DEVICE: + processCloseDevice(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_OPEN_SESSION: + processOpenSession(connection, false); + break; + //----------------------------------------- + case MC_DRV_CMD_OPEN_TRUSTLET: + processOpenTrustlet(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_OPEN_TRUSTED_APP: + processOpenSession(connection, true); + break; + //----------------------------------------- + case MC_DRV_CMD_CLOSE_SESSION: + processCloseSession(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_NQ_CONNECT: + processNqConnect(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_NOTIFY: + processNotify(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_MAP_BULK_BUF: + processMapBulkBuf(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_UNMAP_BULK_BUF: + processUnmapBulkBuf(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_GET_VERSION: + processGetVersion(connection); + break; + //----------------------------------------- + case MC_DRV_CMD_GET_MOBICORE_VERSION: + processGetMobiCoreVersion(connection); + break; + //----------------------------------------- + /* Registry functionality */ + // Write Registry Data + case MC_DRV_REG_STORE_AUTH_TOKEN: + case MC_DRV_REG_WRITE_ROOT_CONT: + case MC_DRV_REG_WRITE_SP_CONT: + case MC_DRV_REG_WRITE_TL_CONT: + case MC_DRV_REG_WRITE_SO_DATA: + case MC_DRV_REG_STORE_TA_BLOB: + processRegistryWriteData(mcDrvCommandHeader.commandId, connection); + break; + //----------------------------------------- + // Read Registry Data + case MC_DRV_REG_READ_AUTH_TOKEN: + case MC_DRV_REG_READ_ROOT_CONT: + case MC_DRV_REG_READ_SP_CONT: + case MC_DRV_REG_READ_TL_CONT: + processRegistryReadData(mcDrvCommandHeader.commandId, connection); + break; + //----------------------------------------- + // Delete registry data + case MC_DRV_REG_DELETE_AUTH_TOKEN: + case MC_DRV_REG_DELETE_ROOT_CONT: + case MC_DRV_REG_DELETE_SP_CONT: + case MC_DRV_REG_DELETE_TL_CONT: + processRegistryDeleteData(mcDrvCommandHeader.commandId, connection); + break; + //----------------------------------------- + default: + LOG_E("Unknown command: %d=0x%x", + mcDrvCommandHeader.commandId, + mcDrvCommandHeader.commandId); + ret = false; + break; + } + } while (0); + mobiCoreDevice->mutex_mcp.unlock(); + mutex.unlock(); + LOG_I("handleConnection()<-------"); + + return ret; +} + +//------------------------------------------------------------------------------ +/** + * Print daemon command line options + */ + +void printUsage( + int argc __unused, + char *args[] +) +{ +#ifdef MOBICORE_COMPONENT_BUILD_TAG + fprintf(stderr, " read() on a FD will now return EINTR + */ +void terminateDaemon( + int signum +) +{ + LOG_E("Signal %d received\n", signum); +} + +//------------------------------------------------------------------------------ +/** + * Main entry of the drivers; + // By default don't fork + bool forkDaemon = false; + + /* Initialize mutex and condition variable objects */ + pthread_mutex_init(&syncMutex, NULL); + pthread_cond_init (&syncCondition, NULL); + + while ((c = getopt(argc, args, "r:sbhp:")) != -1) { + switch (c) { + case 'h': /* Help */ + errFlag++; + break; + case 's': /* Disable Scheduler */ + schedulerFlag = 0; + break; + case 'b': /* Fork to background */ + forkDaemon = true; + break; + case 'r': /* Load 0) { + exit(0); + } + + // obtain a new process group */ + setsid(); + /* close all descriptors */ + for (i = sysconf(_SC_OPEN_MAX); i >= 0; --i) { + close(i); + } + // STDIN, STDOUT and STDERR should all point to /dev/null */ + i = open("/dev/null", O_RDWR); + dup(i); + dup(i); + /* ignore tty signals */ + signal(SIGTSTP, SIG_IGN); + signal(SIGTTOU, SIG_IGN); + signal(SIGTTIN, SIG_IGN); + } + + // Set up the structure to specify the new action. + action.sa_handler = terminateDaemon; + sigemptyset (&action.sa_mask); + action.sa_flags = 0; + sigaction (SIGINT, &action, NULL); + sigaction (SIGTERM, &action, NULL); + signal(SIGPIPE, SIG_IGN); + + mobiCoreDriverDaemon = new MobiCoreDriverDaemon( + /* Scheduler status */ + schedulerFlag, + /* Auto Driver loading */ + driverLoadFlag, + drivers); + + // Start the driver + mobiCoreDriverDaemon->run(); + + delete mobiCoreDriverDaemon; + + pthread_mutex_destroy(&syncMutex); + pthread_cond_destroy(&syncCondition); + + // This should not happen + LOG_E("Exiting getMobiCoreVersion(&versionPayload); + + if (mcResult != MC_DRV_OK) { + LOG_E("Failed to obtain registerWsmL2((addr_t) (token), sosize, 0); + if (pWsm == NULL) { + LOG_E("allocating WSM for Token failed"); + break; + } + + /* Initialize information data of LOAD_TOKEN command */ + loadTokenData_t loadTokenData; + loadTokenData.addr = pWsm->physAddr; + loadTokenData.offs = ((uintptr_t) token) & 0xFFF; + loadTokenData.len = sosize; + + conn = new Connection(); + uint32_t mcRet = mobiCoreDevice->loadToken(conn, &loadTokenData); + + /* Unregister physical memory from kernel module. This will also destroy + * the WSM object. + */ + mobiCoreDevice->unregisterWsmL2(pWsm); + pWsm = NULL; + + if (mcRet != MC_MCP_RET_OK) { + LOG_E("LOAD_TOKEN error 0x%x", mcRet); + break; + } + ret = true; + + } while (false); + + delete pWsm; + delete conn; + + return ret; +} + +/** @} */ diff --git a/mobicore/daemon/Daemon/MobiCoreDriverDaemon.h b/mobicore/daemon/Daemon/MobiCoreDriverDaemon.h new file mode 100644 index 0000000..148d457 --- /dev/null +++ b/mobicore/daemon/Daemon/MobiCoreDriverDaemon.h @@ -0,0 +1,271 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_CONHDLR + * @{ + * @file + * + * +#include + + +#define MAX_SERVERS 2 + +extern string getTlRegistryPath(); + +class MobicoreDriverResources +{ +public: + Connection *conn; + CWsm *pTciWsm; + uint32_t sessionId; + + MobicoreDriverResources( + Connection *conn, + CWsm *pTciWsm, + uint32_t sessionId + ) { + this->conn = conn; + this->pTciWsm = pTciWsm; + this->sessionId = sessionId; + }; +}; + +typedef std::list driverResourcesList_t; + +class MobiCoreDriverDaemon : ConnectionHandler +{ + +public: + + /** + * Create daemon object + * + * @param enableScheduler Enable NQ IRQ scheduler + * @param loadDriver Load driver at daemon startup + * @param driverPath Startup driver path + */ + MobiCoreDriverDaemon( + bool enableScheduler, + + /**< drivers + ); + + virtual ~MobiCoreDriverDaemon( + void + ); + + void dropConnection( + Connection *connection + ); + + bool handleConnection( + Connection *connection + ); + + void run( + void + ); + +private: + MobiCoreDevice *mobiCoreDevice; + /**< Flag to start/stop the scheduler */ + bool enableScheduler; + /**< Flag to load drivers at startup */ + bool loadDriver; + std::vector drivers; + /**< List of resources for the loaded drivers */ + driverResourcesList_t driverResources; + /**< List of servers processing connections */ + Server *servers[MAX_SERVERS]; + + bool checkPermission(Connection *connection); + + size_t writeResult( + Connection *connection, + mcResult_t code + ); + + /** + * Resolve a device ID to a MobiCore device. + * + * @param deviceId Device identifier of the device. + * @return Reference to the device or NULL if device could not be found. + */ + MobiCoreDevice *getDevice( + uint32_t deviceId + ); + + /** + * Load Device driver + * + * @param driverPath Path to the driver file + * @return True for success/false for failure + */ + bool loadDeviceDriver(std::string driverPath); + + /** + * Open Device command + * + * @param connection Connection object + */ + void processOpenDevice(Connection *connection); + + /** + * Open Session command + * + * @param connection Connection object + */ + void processOpenSession(Connection *connection, bool isGpUuid); + + /** + * Check Load TA command + * + * @param spid claimed + * @param blob TA blob pointer + * @param size TA blob pointer size + * @return true in case of success, false in case of failure + */ + + mcResult_t processLoadCheck(mcSpid_t spid, void *blob, uint32_t size); + + /** + * Open Trustlet command + * + * @param connection Connection object + */ + void processOpenTrustlet(Connection *connection); + + /** + * NQ Connect command + * + * @param connection Connection object + */ + void processNqConnect(Connection *connection); + + /** + * Close Device command + * + * @param connection Connection object + */ + void processCloseDevice(Connection *connection); + + /** + * Notify command + * + * @param connection Connection object + */ + void processNotify(Connection *connection); + + /** + * Close Session command + * + * @param connection Connection object + */ + void processCloseSession(Connection *connection); + + /** + * Map Bulk buf command + * + * @param connection Connection object + */ + void processMapBulkBuf(Connection *connection); + + /** + * Unmap bulk buf command + * + * @param connection Connection object + */ + void processUnmapBulkBuf(Connection *connection); + + /** + * Get Version command + * + * @param connection Connection object + */ + void processGetVersion(Connection *connection); + + /** + * Get MobiCore version command + * + * @param connection Connection object + */ + void processGetMobiCoreVersion(Connection *connection); + + /** + * Generic Registry read command + * + * @param commandId Actual command id + * @param connection Connection object + */ + void processRegistryReadData(uint32_t commandId, Connection *connection); + + /** + * Generic Registry write command + * + * @param commandId Actual command id + * @param connection Connection object + */ + void processRegistryWriteData(uint32_t commandId, Connection *connection); + + /** + * Generic Registry Delete command + * + * @param commandId Actual command id + * @param connection Connection object + */ + void processRegistryDeleteData(uint32_t commandId, Connection *connection); + + /** + * Load Token + * This function loads a token (if found) from the registry and uses it as + * the basis for the device attestation functionality + * + * @param token the token to base the attestation on (raw format) + * @param sosize the size of the token + */ + bool loadToken(uint8_t *token, uint32_t sosize); +}; + +#endif /* MOBICOREDRIVER_H_ */ + +/** @} */ diff --git a/mobicore/daemon/Daemon/Server/Android.mk b/mobicore/daemon/Daemon/Server/Android.mk new file mode 100644 index 0000000..3f92d73 --- /dev/null +++ b/mobicore/daemon/Daemon/Server/Android.mk @@ -0,0 +1,17 @@ +# ============================================================================= +# +# MC driver server files +# +# ============================================================================= + +# This is not a separate module. +# Only for inclusion by other modules. + +SERVER_PATH := Daemon/Server + +# Add new folders with header files here +LOCAL_C_INCLUDES += $(LOCAL_PATH)/$(SERVER_PATH)/public + +# Add new source files here +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 new file mode 100644 index 0000000..5ffd41b --- /dev/null +++ b/mobicore/daemon/Daemon/Server/NetlinkServer.cpp @@ -0,0 +1,287 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection server. + * + * Handles incoming socket connections from clients using the MobiCore driver. + */ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include "public/NetlinkServer.h" +#include +#include +#include +#include + +#include +#include "NetlinkConnection.h" +#include + +#define LOG_TAG "McDaemon" +#include "log.h" + +//------------------------------------------------------------------------------ +NetlinkServer::NetlinkServer( + ConnectionHandler *connectionHandler +): Server(connectionHandler, "dummy") +{ +} + + +//------------------------------------------------------------------------------ +void NetlinkServer::run( +) +{ + do { + 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_ERRNO("Opening socket"); + break; + } + + // Fill in address structure and bind to socket + struct sockaddr_nl src_addr; + struct nlmsghdr *nlh = NULL; + struct iovec iov; + struct msghdr msg; + uint32_t len; + + memset(&src_addr, 0, sizeof(src_addr)); + src_addr.nl_family = AF_NETLINK; + 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_ERRNO("Binding to server socket failed, because bind"); + close(serverSock); + serverSock = -1; + break; + } + + // Start reading the socket + LOG_I("\n********* successfully initialized *********\n"); + + for (;;) { + // This buffer will be taken over by the connection it was routed to + nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD)); + if (nlh == NULL) { + LOG_E("Allocation failure"); + break; + } + memset(&msg, 0, sizeof(msg)); + iov.iov_base = (void *)nlh; + iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_name = &src_addr; + msg.msg_namelen = sizeof(src_addr); + + memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD)); + + // Read the incoming message and route it to the connection based + // on the incoming PID + if ((int) (len = recvmsg(serverSock, &msg, 0)) < 0) { + LOG_ERRNO("recvmsg"); + break; + } + + if (NLMSG_OK(nlh, len)) { + handleMessage(nlh); + } else { + break; + } + } + close(serverSock); + serverSock = -1; + } while (false); + + LOG_W("Could not open netlink socket. KernelAPI disabled"); +} + +//------------------------------------------------------------------------------ +void NetlinkServer::handleMessage( + struct nlmsghdr *nlh +) +{ + uint32_t seq = nlh->nlmsg_seq; + uint32_t pid = nlh->nlmsg_pid; + //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(); + + 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", __FUNCTION__); + connection = new NetlinkConnection(this, serverSock, pid, seq); + // Add the new connection + insertConnection(hash, connection); + } + + connection->handleMessage(nlh); + + // Only handle connections which have not been detached + if (connection->detached == false) { + if (!connectionHandler->handleConnection(connection)) { + LOG_I("%s: No command processed.", __FUNCTION__); + connection->socketDescriptor = -1; + //Inform the driver + connectionHandler->dropConnection(connection); + + // Remove connection from list + removeConnection(hash); + connection->socketDescriptor = -1; + delete connection; + } + // If connection data is set to NULL then device close has been called + // so we must remove all connections associated with this hash + else if (connection->connectionData == NULL && + connection->detached == false) { + delete connection; + } + } +} + + +//------------------------------------------------------------------------------ +void NetlinkServer::detachConnection( + Connection *connection +) +{ + connection->detached = true; +} + + +//------------------------------------------------------------------------------ +NetlinkServer::~NetlinkServer( + void +) +{ + connectionMap_t::iterator i; + // Shut down the server socket + if(serverSock != -1) { + close(serverSock); + serverSock = -1; + } + + // Destroy all client connections + for (i = peerConnections.begin(); i != peerConnections.end(); i++) { + if (i->second->detached == false) { + delete i->second; + } + } + peerConnections.clear(); +} + + +//------------------------------------------------------------------------------ +NetlinkConnection *NetlinkServer::findConnection( + uint64_t hash +) +{ + connectionMap_t::iterator i = peerConnections.find(hash); + if (i != peerConnections.end()) { + return i->second; + } + + return NULL; +} + + +//------------------------------------------------------------------------------ +void NetlinkServer::insertConnection( + uint64_t hash, + NetlinkConnection *connection +) +{ + peerConnections[hash] = connection; +} + +/* This is called from multiple threads! */ +//------------------------------------------------------------------------------ +void NetlinkServer::removeConnection( + uint64_t hash +) +{ + connectionMap_t::iterator i = peerConnections.find(hash); + if (i != peerConnections.end()) { + peerConnections.erase(i); + } +} + +//------------------------------------------------------------------------------ +void NetlinkServer::cleanupConnections( + void +) +{ + connectionMap_t::reverse_iterator i; + pid_t pid; + NetlinkConnection *connection = NULL; + // Destroy all client connections + for (i = peerConnections.rbegin(); i != peerConnections.rend(); ++i) { + 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", __FUNCTION__, pid); + // Check if the peer pid is still alive + if (pid == 0) { + continue; + } + if (kill(pid, 0)) { + bool detached = connection->detached; + LOG_I("%s: PID %u has died, cleaning up session 0x%X", + __FUNCTION__, pid, connection->peerPid); + + connection->socketDescriptor = -1; + //Inform the driver + connectionHandler->dropConnection(connection); + + // We aren't handling this connection anymore no matter what + removeConnection(connection->hash); + + // Remove connection from list only if detached, the detached + // connections are managed by the device + if (detached == false) { + delete connection; + } + if (peerConnections.size() == 0) { + break; + } + i = peerConnections.rbegin(); + } + } +} + +/** @} */ diff --git a/mobicore/daemon/Daemon/Server/Server.cpp b/mobicore/daemon/Daemon/Server/Server.cpp new file mode 100644 index 0000000..24e3ca9 --- /dev/null +++ b/mobicore/daemon/Daemon/Server/Server.cpp @@ -0,0 +1,255 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection server. + * + * Handles incoming socket connections from clients using the MobiCore driver. + */ +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ +#include "public/Server.h" +#include +#include +#include + +//#define LOG_VERBOSE +#include "log.h" + +extern pthread_mutex_t syncMutex; +extern pthread_cond_t syncCondition; +extern bool Th_sync; + +//------------------------------------------------------------------------------ +Server::Server( + ConnectionHandler *connectionHandler, + const char *localAddr +) : socketAddr(localAddr) +{ + this->connectionHandler = connectionHandler; + this->serverSock = -1; +} + + +//------------------------------------------------------------------------------ +void Server::run( + void +) +{ + do { + pthread_mutex_lock(&syncMutex); + + 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_ERRNO("Can't open stream socket, because socket"); + break; + } + + // Fill in address structure and bind to socket + struct sockaddr_un serverAddr; + serverAddr.sun_family = AF_UNIX; + strncpy(serverAddr.sun_path, socketAddr.c_str(), sizeof(serverAddr.sun_path) - 1); + + uint32_t len = strlen(serverAddr.sun_path) + sizeof(serverAddr.sun_family); + // Make the socket in the Abstract Domain(no path but everyone can connect) + serverAddr.sun_path[0] = 0; + if (::bind(serverSock, (struct sockaddr *) &serverAddr, len) < 0) { + LOG_ERRNO("Binding to server socket failed, because bind"); + } + + // Start listening on the socket + if (listen(serverSock, LISTEN_QUEUE_LEN) < 0) { + LOG_ERRNO("listen"); + break; + } + + LOG_I("\n********* successfully initialized Daemon *********\n"); + + + + for (;;) { + fd_set fdReadSockets; + + // Clear FD for select() + FD_ZERO(&fdReadSockets); + + // Select server socket descriptor + FD_SET(serverSock, &fdReadSockets); + int maxSocketDescriptor = serverSock; + + // Select socket descriptor of all connections + for (connectionIterator_t iterator = peerConnections.begin(); + iterator != peerConnections.end(); + ++iterator) { + Connection *connection = (*iterator); + int peerSocket = connection->socketDescriptor; + FD_SET(peerSocket, &fdReadSockets); + if (peerSocket > maxSocketDescriptor) { + maxSocketDescriptor = peerSocket; + } + } + + pthread_cond_signal(&syncCondition); + Th_sync=true; + pthread_mutex_unlock(&syncMutex); + + // Wait for activities, select() returns the number of sockets + // which require processing + LOG_V(" Server: waiting on sockets"); + int numSockets = select( + maxSocketDescriptor + 1, + &fdReadSockets, + NULL, NULL, NULL); + + // Check if select failed + if (numSockets < 0) { + LOG_ERRNO("select"); + break; + } + + // actually, this should not happen. + if (0 == numSockets) { + LOG_W(" Server: select() returned 0, spurious event?."); + continue; + } + + 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_V(" Server: new connection attempt."); + numSockets--; + + struct sockaddr_un clientAddr; + socklen_t clientSockLen = sizeof(clientAddr); + int clientSock = accept( + serverSock, + (struct sockaddr *) &clientAddr, + &clientSockLen); + + if (clientSock <= 0) { + LOG_ERRNO("accept"); + break; + } + + Connection *connection = new Connection(clientSock, &clientAddr); + peerConnections.push_back(connection); + LOG_I(" Server: new socket connection established and start listening."); + } while (false); + + // we can ignore any errors from accepting a new connection. + // If this fail, the client has to deal with it, we are done + // and nothing has changed. + } + + // Handle traffic on existing client connections + connectionIterator_t iterator = peerConnections.begin(); + while ( (iterator != peerConnections.end()) + && (numSockets > 0) ) { + Connection *connection = (*iterator); + int peerSocket = connection->socketDescriptor; + + if (!FD_ISSET(peerSocket, &fdReadSockets)) { + ++iterator; + continue; + } + + numSockets--; + + // the connection will be terminated if command processing + // fails + if (!connectionHandler->handleConnection(connection)) { + LOG_I(" Server: dropping connection."); + + //Inform the driver + connectionHandler->dropConnection(connection); + + // Remove connection from list + delete connection; + iterator = peerConnections.erase(iterator); + continue; + } + + ++iterator; + } + } + + } while (false); + + LOG_ERRNO("Exiting Server, because"); +} + + +//------------------------------------------------------------------------------ +void Server::detachConnection( + Connection *connection +) +{ + LOG_V(" Stopping to listen on notification socket."); + + for (connectionIterator_t iterator = peerConnections.begin(); + iterator != peerConnections.end(); + ++iterator) { + Connection *tmpConnection = (*iterator); + if (tmpConnection == connection) { + peerConnections.erase(iterator); + LOG_I(" Stopped listening on notification socket."); + break; + } + } +} + + +//------------------------------------------------------------------------------ +Server::~Server( + void +) +{ + // Shut down the server socket + if(serverSock != -1) { + close(serverSock); + serverSock = -1; + } + + // Destroy all client connections + connectionIterator_t iterator = peerConnections.begin(); + while (iterator != peerConnections.end()) { + Connection *tmpConnection = (*iterator); + delete tmpConnection; + iterator = peerConnections.erase(iterator); + } +} + +/** @} */ diff --git a/mobicore/Daemon/src/ConnectionHandler.h b/mobicore/daemon/Daemon/Server/public/ConnectionHandler.h similarity index 80% rename from mobicore/Daemon/src/ConnectionHandler.h rename to mobicore/daemon/Daemon/Server/public/ConnectionHandler.h index 8d44c63..f647398 100644 --- a/mobicore/Daemon/src/ConnectionHandler.h +++ b/mobicore/daemon/Daemon/Server/public/ConnectionHandler.h @@ -1,5 +1,11 @@ -/* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Interface for connection handlers used by Server. + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -33,6 +39,7 @@ #include "Connection.h" + class ConnectionHandler { @@ -43,21 +50,24 @@ public: * Handle connection activities. * The connection handler shall process pending connection activities. * - * @param [in] connection Reference to the connection which - * has data to process. + * @param [in] connection Reference to the connection which has data to process. */ - virtual bool handleConnection(Connection &connection) = 0; + virtual bool handleConnection( + Connection *connection + ) = 0; /** * Connection has been closed. - * The connection handler shall clean up all resources associated with - * the given connection. After the method has been executed the connection - * object will be deleted. + * The connection handler shall clean up all resources associated with the given connection. + * After the method has been executed the connection object will be deleted. * * @param [in] connection Reference to the connection which will be deleted. */ - virtual void dropConnection(Connection &connection) = 0; + virtual void dropConnection( + Connection *connection + ) = 0; }; #endif /* CONNECTIONHANDLER_H_ */ +/** @} */ diff --git a/mobicore/daemon/Daemon/Server/public/NetlinkServer.h b/mobicore/daemon/Daemon/Server/public/NetlinkServer.h new file mode 100644 index 0000000..14e8b85 --- /dev/null +++ b/mobicore/daemon/Daemon/Server/public/NetlinkServer.h @@ -0,0 +1,161 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection server. + * + * Handles incoming socket connections from clients using the MobiCore driver. + * + * Iterative socket server using Netlink dgram protocol. + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 NETLINKSERVER_H_ +#define NETLINKSERVER_H_ + +#include +#include +#include +#include +#include +#include + +#include "NetlinkConnection.h" +#include "ConnectionHandler.h" +#include "Server.h" + +class NetlinkServer: public Server, public NetlinkConnectionManager +{ +public: + /** + * Server contructor. + * + * @param connectionHanler Connection handler to pass incoming connections to. + */ + NetlinkServer( + ConnectionHandler *connectionHandler + ); + + /** + * Server destructor. + * All available connections will be terminated. Resources will be freed. + */ + virtual ~NetlinkServer( + void + ); + + /** + * Start server and listen for incoming connections. + * Implements the central socket server loop. Incoming connections will be stored. + */ + virtual void run( + void + ); + + /** + * Remove a connection object from the list of available connections. + * Detaching is required for notification connections wich are never used to transfer command + * data from TLCs to the driver. If the function succeeds, freeing the connection will no longer + * be the server's responsability. + * + * @param connection The connection object to remove. + */ + virtual void detachConnection( + Connection *connection + ); + +private: + /** + * Handle incomming Netlink message. + * It routes the incomming packet to the apropriate connection based on the packet's + * session magic. + * + * @param nlh The netlink message's header + payload + */ + void handleMessage( + struct nlmsghdr *nlh + ); + + /** + * Retreive connection based on hash. + * Search the peer connections hashmap for a hash and return + * the associated Connection object + * + * @param seq The seq to search + * @return The NetlinkConnection object if found or NULL if not found + */ + NetlinkConnection *findConnection( + uint64_t hash + ); + + /** + * Insert a connection in the peer connection hashmap + * Insert a new connection in the peer connections hashmap. If there is + * already such a connection it will be overriden! + * + * @param seq The seq to use + * @param connection The connection object to insert + */ + void insertConnection( + uint64_t hash, + NetlinkConnection *connection + ); + + /** + * Remove a connection from the peer connections + * Remove the connection associated with seq from the peer list. + * This doesn't actually free the connection object! + * If the seq is invalid nothing happens. + * + * @param seq The seq to use + */ + void removeConnection( + uint64_t hash + ); + + + /** + * Check for sessions started by applications that died(exited) + * Remove the connections to applications that are not active anymore + * If the application has died then all the sessions associated with it + * should be closed! + * + */ + void cleanupConnections( + void + ); + + connectionMap_t peerConnections; /**< Hashmap with connections to clients */ +}; + +#endif /* SERVER_H_ */ + +/** @} */ diff --git a/mobicore/Daemon/src/Server.h b/mobicore/daemon/Daemon/Server/public/Server.h similarity index 62% rename from mobicore/Daemon/src/Server.h rename to mobicore/daemon/Daemon/Server/public/Server.h index 1d777c7..fb09f23 100644 --- a/mobicore/Daemon/src/Server.h +++ b/mobicore/daemon/Daemon/Server/public/Server.h @@ -1,5 +1,15 @@ -/* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED +/** @addtogroup MCD_MCDIMPL_DAEMON_SRV + * @{ + * @file + * + * Connection server. + * + * Handles incoming socket connections from clients using the MobiCore driver. + * + * Iterative socket server using UNIX domain stream protocol. + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -36,68 +46,67 @@ #include #include #include -#include - -#include - +#include #include "CThread.h" #include "ConnectionHandler.h" /** Number of incoming connections that can be queued. * Additional clients will generate the error ECONNREFUSED. */ -#define LISTEN_QUEUE_LEN 8 +#define LISTEN_QUEUE_LEN (16) -typedef std::list connectionList_t; -typedef connectionList_t::iterator connectionIterator_t; class Server: public CThread { + public: /** * Server contructor. * * @param connectionHanler Connection handler to pass incoming connections to. - * @param localAdrerss Pointer to a zero terminated - * string containing the file to listen to. + * @param localAdrerss Pointer to a zero terminated string containing the file to listen to. */ - Server(ConnectionHandler *connectionHandler, - const char *localAddr, const int listen_queue_sz = LISTEN_QUEUE_LEN); + Server( + ConnectionHandler *connectionHandler, + const char *localAddr + ); /** * Server destructor. * All available connections will be terminated. Resources will be freed. */ - virtual ~Server(); + virtual ~Server( + void + ); /** * Start server and listen for incoming connections. - * Implements the central socket server loop. - * Incoming connections will be stored. + * Implements the central socket server loop. Incoming connections will be stored. */ - virtual void run(); - - void start() - { - CThread::start(Server::m_server_name); - } + virtual void run( + ); - void stop(); + /** + * Remove a connection object from the list of available connections. + * Detaching is required for notification connections wich are never used to transfer command + * data from TLCs to the driver. If the function succeeds, the connection object will no longer + * be handled by the server. + * + * @param connection The connection object to remove. + */ + virtual void detachConnection( + Connection *connection + ); - bool valid() const - { - return m_serverSock != -1; - } protected: - - int m_serverSock; - /**< Connection handler registered to the server */ - ConnectionHandler * const m_connectionHandler; + int serverSock; + string socketAddr; + ConnectionHandler *connectionHandler; /**< Connection handler registered to the server */ private: - pthread_mutex_t m_close_lock; - connectionList_t m_peerConnections; /**< Connections to devices */ - static const char * const m_server_name; + connectionList_t peerConnections; /**< Connections to devices */ + }; #endif /* SERVER_H_ */ +/** @} */ diff --git a/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h b/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h new file mode 100644 index 0000000..8abf70a --- /dev/null +++ b/mobicore/daemon/Daemon/public/MobiCoreDriverCmd.h @@ -0,0 +1,292 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON + * @{ + * @file + * + * + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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 MCDAEMON_H_ +#define MCDAEMON_H_ + +#include // ANSI C99 + +#include "mcUuid.h" +#include "mcVersionInfo.h" + +#define SOCK_PATH "#mcdaemon" + +typedef enum { + MC_DRV_CMD_PING = 0, + MC_DRV_CMD_GET_INFO = 1, + MC_DRV_CMD_OPEN_DEVICE = 2, + MC_DRV_CMD_CLOSE_DEVICE = 3, + MC_DRV_CMD_NQ_CONNECT = 4, + MC_DRV_CMD_OPEN_SESSION = 5, + MC_DRV_CMD_CLOSE_SESSION = 6, + MC_DRV_CMD_NOTIFY = 7, + MC_DRV_CMD_MAP_BULK_BUF = 8, + MC_DRV_CMD_UNMAP_BULK_BUF = 9, + MC_DRV_CMD_GET_VERSION = 10, + MC_DRV_CMD_GET_MOBICORE_VERSION = 11, + MC_DRV_CMD_OPEN_TRUSTLET = 12, + MC_DRV_CMD_OPEN_TRUSTED_APP = 13, + + // Registry Commands + + // Auth token OPS + MC_DRV_REG_STORE_AUTH_TOKEN = 0x100000, + MC_DRV_REG_READ_AUTH_TOKEN = 0x100001, + MC_DRV_REG_DELETE_AUTH_TOKEN = 0x100002, + // Root container OPS + MC_DRV_REG_READ_ROOT_CONT = 0x100003, + MC_DRV_REG_WRITE_ROOT_CONT = 0x100004, + MC_DRV_REG_DELETE_ROOT_CONT = 0x100005, + // Service Provider Container OPS + MC_DRV_REG_READ_SP_CONT = 0x100006, + MC_DRV_REG_WRITE_SP_CONT = 0x100007, + MC_DRV_REG_DELETE_SP_CONT = 0x100008, + // Trustlet Container OPS + MC_DRV_REG_READ_TL_CONT = 0x100009, + MC_DRV_REG_WRITE_TL_CONT = 0x10000A, + MC_DRV_REG_DELETE_TL_CONT = 0x10000B, + // Shared Object Data write + MC_DRV_REG_WRITE_SO_DATA = 0x10000C, + // TA Blob store + MC_DRV_REG_STORE_TA_BLOB = 0x10000D, + +} mcDrvCmd_t; + +typedef struct { + mcDrvCmd_t commandId; +} mcDrvCommandHeader_t; + +typedef struct { + /* + +#include +#include +#include + +#include "CKMod.h" + +#include "log.h" + +#define INVALID_FILE_DESCRIPTOR ((int)(-1)) + +//------------------------------------------------------------------------------ +CKMod::CKMod(void) +{ + fdKMod = INVALID_FILE_DESCRIPTOR; +} + + +//------------------------------------------------------------------------------ +CKMod::~CKMod(void) +{ + close(); +} + + +//------------------------------------------------------------------------------ +bool CKMod::isOpen(void) +{ + return (INVALID_FILE_DESCRIPTOR == fdKMod) ? false : true; +} + + +//------------------------------------------------------------------------------ +mcResult_t CKMod::open(const char *deviceName) +{ + if (isOpen()) { + LOG_W("already open"); + return MC_DRV_ERR_DEVICE_ALREADY_OPEN; + } + + LOG_I(" Opening kernel module at %s.", deviceName); + + // open return -1 on error, "errno" is set with details + int openRet = ::open(deviceName, O_RDWR); + if (openRet == -1) { + LOG_ERRNO("open"); + return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno); + } + + fdKMod = openRet; + return MC_DRV_OK; +} + + +//------------------------------------------------------------------------------ +void CKMod::close( + void +) +{ + if (isOpen()) { + if (::close(fdKMod) != 0) { + LOG_ERRNO("close"); + } else { + fdKMod = INVALID_FILE_DESCRIPTOR; + } + } else { + LOG_W(" Kernel module device not open"); + } +} + +/** @} */ diff --git a/mobicore/rootpa/Code/Common/include/wrapper.h b/mobicore/daemon/Kernel/CKMod.h similarity index 72% rename from mobicore/rootpa/Code/Common/include/wrapper.h rename to mobicore/daemon/Kernel/CKMod.h index d48143f..d0022e2 100644 --- a/mobicore/rootpa/Code/Common/include/wrapper.h +++ b/mobicore/daemon/Kernel/CKMod.h @@ -1,4 +1,10 @@ -/* +/** @addtogroup MCD_MCDIMPL_DAEMON_KERNEL + * @{ + * @file + * + * Kernel Module Interface. + * + * * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * @@ -28,33 +34,48 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WRAPPER_H_ -#define WRAPPER_H_ +#ifndef CKMOD_H_ +#define CKMOD_H_ + +#include +#include "ClientLib/public/MobiCoreDriverApi.h" + + +/** + * Base class for accessing a kernel module. + */ +class CKMod +{ + +protected: + + int fdKMod; + + /** + * Helper function to check if connected to kernel module. + */ + bool isOpen( + void + ); -#ifdef WIN32 - #ifdef __cplusplus - extern "C" { - #endif - #include - #include +public: - #define snprintf _snprintf + CKMod( + void + ); - typedef int pid_t; + virtual ~CKMod( + void + ); - #define bool int - #define TRUE 1 - #define FALSE 0 + mcResult_t open( + const char *deviceName + ); - #define false FALSE - #define true TRUE + void close( + void + ); - #define sleep(x) Sleep(x) +}; - #ifdef __cplusplus - } - #endif // __cplusplus -#else - #include -#endif // WINDOWS_BUILD -#endif //WRAPPER_H_ +#endif // CKMOD_H_ diff --git a/mobicore/daemon/Kernel/Platforms/Generic/Android.mk b/mobicore/daemon/Kernel/Platforms/Generic/Android.mk new file mode 100644 index 0000000..8b4b8b4 --- /dev/null +++ b/mobicore/daemon/Kernel/Platforms/Generic/Android.mk @@ -0,0 +1,15 @@ +# ============================================================================= +# +# Generic TrustZone device includes +# +# ============================================================================= + +# This is not a separate module. +# All paths are relative to APP_PROJECT_PATH! +KERNEL_PATH := Kernel/Platforms/Generic + +# Add new source files here +LOCAL_SRC_FILES += $(KERNEL_PATH)/CMcKMod.cpp + +# Header files for components including this module +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 new file mode 100644 index 0000000..427f91c --- /dev/null +++ b/mobicore/daemon/Kernel/Platforms/Generic/CMcKMod.cpp @@ -0,0 +1,561 @@ +/** @addtogroup MCD_MCDIMPL_DAEMON_KERNEL + * @{ + * @file + * + * + +#include +#include +#include +#include +#include + +#include "McTypes.h" +#include "mc_linux.h" +#include "mcVersionHelper.h" + +#include "CMcKMod.h" + +#include "log.h" + +//------------------------------------------------------------------------------ +MC_CHECK_VERSION(MCDRVMODULEAPI, 1, 1); + +//------------------------------------------------------------------------------ +mcResult_t CMcKMod::mapWsm( + uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + uint64_t *pPhysAddr) +{ + int ret = 0; + LOG_V(" mapWsm(): len=%d", len); + + if (!isOpen()) { + LOG_E("no connection to kmod"); + return MC_DRV_ERR_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 MAKE_MC_DRV_KMOD_WITH_ERRNO(errno); + } + + addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, + fdKMod, mapParams.phys_addr); + if (virtAddr == MAP_FAILED) { + LOG_ERRNO("mmap"); + return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno); + } + + + LOG_V(" mapped to %p, handle=%d, phys=0x%llX ", virtAddr, + mapParams.handle, mapParams.phys_addr); + + if (pVirtAddr != NULL) { + *pVirtAddr = virtAddr; + } + + if (pHandle != NULL) { + *pHandle = mapParams.handle; + } + + if (pPhysAddr != NULL) { + *pPhysAddr = mapParams.phys_addr; + } + + return 0; +} + +//------------------------------------------------------------------------------ +mcResult_t CMcKMod::mapMCI( + uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + uint64_t *pPhysAddr, + bool *pReuse) +{ + 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 MC_DRV_ERR_KMOD_NOT_OPEN; + } + + int ret = ioctl(fdKMod, MC_IO_MAP_MCI, &mapParams); + if (ret != 0) { + LOG_ERRNO("ioctl MC_IO_MAP_MCI"); + return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno); + } + + addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, + fdKMod, 0); + if (virtAddr == MAP_FAILED) { + LOG_ERRNO("mmap"); + return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno); + } + unsigned long addr = (unsigned long)virtAddr; + *pReuse = mapParams.reused; + + LOG_V(" MCI mapped to %p, handle=%d, phys=%p, reused=%s", + (void *)addr, mapParams.handle, mapParams.phys_addr, + mapParams.reused ? "true" : "false"); + + if (pVirtAddr != NULL) { + *pVirtAddr = (void *)addr; + } + + if (pHandle != NULL) { + *pHandle = mapParams.handle; + } + + if (pPhysAddr != NULL) { + *pPhysAddr = mapParams.phys_addr; + } + + // clean memory + //memset(pMmapResp, 0, sizeof(*pMmapResp)); + + return MC_DRV_OK; +} + +//------------------------------------------------------------------------------ +mcResult_t CMcKMod::mapPersistent( + uint32_t len __unused, + uint32_t *pHandle __unused, + addr_t *pVirtAddr __unused, + addr_t *pPhysAddr __unused) +{ + // Not currently supported by the driver + LOG_E(" + +#include "McTypes.h" +#include "CKMod.h" + + +/** + * 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 + * + * @return 0 if all went fine + * @return MC_DRV_ERR_KMOD_NOT_OPEN + * @return MC_DRV_ERR_KERNEL_MODULE or'ed with errno<<16 + */ + mcResult_t mapWsm(uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + uint64_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 MC_DRV_ERR_KMOD_NOT_OPEN + * @return MC_DRV_ERR_KERNEL_MODULE or'ed with errno<<16 + */ + mcResult_t mapMCI( + uint32_t len, + uint32_t *pHandle, + addr_t *pVirtAddr, + uint64_t *pPhysAddr, + bool *pReuse); + + /** + * Map persistent WSM which will not be freed up once the calling process dies. + */ + mcResult_t 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 nqLength, + uint32_t mcpOffset, + uint32_t mcpLength); + + int fcInfo( + uint32_t extInfoId, + uint32_t *pState, + uint32_t *pExtInfo); + + int fcYield(void); + + int fcNSIQ(void); + + mcResult_t free(uint32_t handle, addr_t buffer, uint32_t len); + + mcResult_t registerWsmL2( + addr_t buffer, + uint32_t len, + uint32_t pid, + uint32_t *pHandle, + uint64_t *pPhysWsmL2); + + mcResult_t unregisterWsmL2(uint32_t handle); + + mcResult_t lockWsmL2(uint32_t handle); + + mcResult_t unlockWsmL2(uint32_t handle); + + mcResult_t cleanupWsmL2(void); + + uint64_t findWsmL2(uint32_t handle, int fd); + + mcResult_t findContiguousWsm(uint32_t handle, int fd, uint64_t *phys, uint32_t *len); + + mcResult_t setupLog(void); + + bool checkVersion(void); +}; + +typedef CMcKMod *CMcKMod_ptr; + +#endif // CMCKMOD_H_ diff --git a/mobicore/Daemon/MODULE_LICENSE_BSD b/mobicore/daemon/MODULE_LICENSE_BSD similarity index 100% rename from mobicore/Daemon/MODULE_LICENSE_BSD rename to mobicore/daemon/MODULE_LICENSE_BSD diff --git a/mobicore/daemon/NOTICE b/mobicore/daemon/NOTICE new file mode 100644 index 0000000..d742e22 --- /dev/null +++ b/mobicore/daemon/NOTICE @@ -0,0 +1,25 @@ + 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: + 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. \ No newline at end of file diff --git a/mobicore/daemon/README.android b/mobicore/daemon/README.android new file mode 100644 index 0000000..29edee1 --- /dev/null +++ b/mobicore/daemon/README.android @@ -0,0 +1,64 @@ +MobiCore Daemon in Android +--- +Command line +-- +The MobiCore Daemon supports 4 command line options. It also displays them with the help option: + +# ./mcDriverDaemon -h +usage: ./mcDriverDaemon [-mdsbh] +Start MobiCore Daemon + +-h show this help +-b fork to background +-m IMAGE load mobicore from IMAGE to DDR +-s disable daemon scheduler(default enabled) +-r DRIVER load dyamic driver + +-b Forks the daemon to background + +# ./mcDriverDaemon -b + +Makes the daemon run in background and returns immediate control to the shell. No need to use shell forking with & + +-m Loads a mobicore image to DDR + +# ./mcDriverDaemon -m /data/app/mobicore.img + +Loads the mobicore.img to DDR and starts executing it. + +-s Disables NQ IRQ scheduler + +# ./mcDriverDaemon -s + +-r Loads dynamic driver at startup. The full path of the driver binary must be given, eg. /data/app/driver.drbin + +# ./mcDriverDaemon -r /data/app/driver.drbin + +Custom registry locations +-- +Registry fallback + +In case of a Device wipe in Android the /data/app/mcRegistry folder will be deleted with all it's contents. To overcome +this the daemon supports a fallback location(eg /system/app/mcRegistry): it first tries to load the trustlet +from /data/app/mcRegistry/[uuid].tlbin and if it fails then it tries to read the trustlet from /system/app/mcRegistry/[uuid].tlb + +Both paths are completely configurable for the Daemon using 2 environment variables:MC_REGISTRY_PATH and MC_REGISTRY_FALLBACK_PATH + +For example if you want to use /data/app/mcRegistry as the default path and /system/app/mcRegistry as the fallback path: + +$ export MC_REGISTRY_PATH=/data/app/mcRegistry +$ export MC_REGISTRY_FALLBACK_PATH=/system/app/mcRegistry +$ /data/app/mcDriverDaemon + +Custom authtoken path +-- + +The authtoken file is created at provisioning and is by default located in /data/app/mcRegistry/00000.authtoken + +Because a device wipe could delete this file and make MobiCore unusable a new environment variable has been added to change the +default behaviour: MC_AUTH_TOKEN_PATH + +$ export MC_AUTH_TOKEN_PATH=/efs +$ /data/app/mcDriverDaemon + +This would change the location of the authtoken file to /efs diff --git a/mobicore/daemon/Registry/Android.mk b/mobicore/daemon/Registry/Android.mk new file mode 100644 index 0000000..d83160c --- /dev/null +++ b/mobicore/daemon/Registry/Android.mk @@ -0,0 +1,11 @@ +# ============================================================================= +# +# Module: MobiCore driver registry +# +# ============================================================================= + +# Add new folders with header files here +LOCAL_C_INCLUDES += $(LOCAL_PATH)/Registry/Public + +# Add new source files here +LOCAL_SRC_FILES += Registry/Registry.cpp diff --git a/mobicore/Daemon/src/PrivateRegistry.cpp b/mobicore/daemon/Registry/PrivateRegistry.cpp similarity index 53% rename from mobicore/Daemon/src/PrivateRegistry.cpp rename to mobicore/daemon/Registry/PrivateRegistry.cpp index e4f40fb..694ed15 100644 --- a/mobicore/Daemon/src/PrivateRegistry.cpp +++ b/mobicore/daemon/Registry/PrivateRegistry.cpp @@ -1,5 +1,13 @@ +/** Mobicore Driver Registry. + * + * Implements the MobiCore driver registry which maintains trustlets. + * + * @file + * @ingroup MCD_MCDIMPL_DAEMON_REG + */ + /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -28,15 +36,8 @@ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** Mobicore Driver Registry. - * - * Implements the MobiCore driver registry which maintains trustlets. - * - * @file - * @ingroup MCD_MCDIMPL_DAEMON_REG - */ + #include -#include #include #include #include @@ -55,20 +56,24 @@ #include "mcVersionHelper.h" #include "PrivateRegistry.h" +#include "MobiCoreRegistry.h" -#include #include "uuid_attestation.h" -#include +#include "log.h" +/** Maximum size of a trustlet in bytes. */ +#define MAX_TL_SIZE (1 * 1024 * 1024) /** Maximum size of a shared object container in bytes. */ #define MAX_SO_CONT_SIZE (512) -#define MC_REGISTRY_ALL 0 -#define MC_REGISTRY_WRITABLE 1 +// Asserts expression at compile-time (to be used within a function body). +#define ASSERT_STATIC(e) do { enum { assert_static__ = 1 / (e) }; } while (0) +#define MC_REGISTRY_CONTAINER_PATH "/data/app/mcRegistry" +#define MC_REGISTRY_DEFAULT_PATH "/system/app/mcRegistry" +#define MC_REGISTRY_FALLBACK_PATH "/data/app/mcRegistry" #define AUTH_TOKEN_FILE_NAME "00000000.authtokcont" -#define AUTH_TOKEN_FILE_NAME_BACKUP_SUFFIX ".backup" #define ENV_MC_AUTH_TOKEN_PATH "MC_AUTH_TOKEN_PATH" #define ROOT_FILE_NAME "00000000.rootcont" #define SP_CONT_FILE_EXT ".spcont" @@ -78,349 +83,204 @@ #define GP_TA_BIN_FILE_EXT ".tabin" #define GP_TA_SPID_FILE_EXT ".spid" -static std::vector search_paths; -static std::string tb_storage_path; +using namespace std; //------------------------------------------------------------------------------ -static std::string byteArrayToString(const void *bytes, size_t elems) +static string byteArrayToString(const void *bytes, size_t elems) { - auto cbytes = static_cast(bytes); char hx[elems * 2 + 1]; for (size_t i = 0; i < elems; i++) { - sprintf(&hx[i * 2], "%02x", cbytes[i]); + sprintf(&hx[i * 2], "%02x", ((uint8_t *)bytes)[i]); } - return std::string(hx); + return string(hx); } //------------------------------------------------------------------------------ -static std::string uint32ToString(uint32_t value) +static string uint32ToString(uint32_t value) { char hx[8 + 1]; snprintf(hx, sizeof(hx), "%08X", value); - std::string str(hx); - return std::string(str.rbegin(), str.rend()); + string str(hx); + return string(str.rbegin(), str.rend()); } //------------------------------------------------------------------------------ -static bool dirExists(const char *path) +static bool doesDirExist(const char *path) { struct stat ss; + if (path != NULL && stat(path, &ss) == 0 && S_ISDIR(ss.st_mode)) { + return true; + } + return false; +} + +//------------------------------------------------------------------------------ +static string getRegistryPath() +{ + string registryPath; + + // use the default registry path. + registryPath = MC_REGISTRY_CONTAINER_PATH; + LOG_I(" Using default registry path %s", registryPath.c_str()); - return (path != NULL) && (stat(path, &ss) == 0) && S_ISDIR(ss.st_mode); + assert(registryPath.length() != 0); + + return registryPath; } //------------------------------------------------------------------------------ -const std::string& getTbStoragePath() +string getTlRegistryPath() { - return tb_storage_path; + string registryPath; + + // First, attempt to use regular registry environment variable. + if (doesDirExist(MC_REGISTRY_DEFAULT_PATH)) { + registryPath = MC_REGISTRY_DEFAULT_PATH; + LOG_I(" Using MC_REGISTRY_PATH %s", registryPath.c_str()); + } else if (doesDirExist(MC_REGISTRY_FALLBACK_PATH)) { + // Second, attempt to use fallback registry environment variable. + registryPath = MC_REGISTRY_FALLBACK_PATH; + LOG_I(" Using MC_REGISTRY_FALLBACK_PATH %s", registryPath.c_str()); + } + + // As a last resort, use the default registry path. + if (registryPath.length() == 0) { + registryPath = MC_REGISTRY_CONTAINER_PATH; + LOG_I(" Using default registry path %s", registryPath.c_str()); + } + + assert(registryPath.length() != 0); + + return registryPath; } //------------------------------------------------------------------------------ -static std::string getAuthTokenFilePath() +static string getAuthTokenFilePath() { const char *path; - std::string authTokenPath; + string authTokenPath; // First, attempt to use regular auth token path environment variable. path = getenv(ENV_MC_AUTH_TOKEN_PATH); - if (dirExists(path)) { - LOG_D("getAuthTokenFilePath(): Using MC_AUTH_TOKEN_PATH %s", path); + if (doesDirExist(path)) { + LOG_I("getAuthTokenFilePath(): Using MC_AUTH_TOKEN_PATH %s", path); authTokenPath = path; } else { - authTokenPath = search_paths[0]; - LOG_D("getAuthTokenFilePath(): Using path %s", authTokenPath.c_str()); + authTokenPath = getRegistryPath(); + LOG_I("getAuthTokenFilePath(): Using path %s", authTokenPath.c_str()); } return authTokenPath + "/" + AUTH_TOKEN_FILE_NAME; } //------------------------------------------------------------------------------ -static std::string getAuthTokenFilePathBackup() -{ - return getAuthTokenFilePath() + AUTH_TOKEN_FILE_NAME_BACKUP_SUFFIX; -} - -//------------------------------------------------------------------------------ -static std::string getRootContFilePath() +static string getRootContFilePath() { - return search_paths[0] + "/" + ROOT_FILE_NAME; + return getRegistryPath() + "/" + ROOT_FILE_NAME; } //------------------------------------------------------------------------------ -static std::string getSpDataPath(mcSpid_t spid) +static string getSpDataPath(mcSpid_t spid) { - return search_paths[0] + "/" + uint32ToString(spid); + return getRegistryPath() + "/" + uint32ToString(spid); } //------------------------------------------------------------------------------ -static std::string getSpContFilePath(mcSpid_t spid) +static string getSpContFilePath(mcSpid_t spid) { - return search_paths[0] + "/" + uint32ToString(spid) + SP_CONT_FILE_EXT; + return getRegistryPath() + "/" + uint32ToString(spid) + SP_CONT_FILE_EXT; } //------------------------------------------------------------------------------ -static std::string getTlContFilePath(const mcUuid_t *uuid, const mcSpid_t spid) +static string getTlContFilePath(const mcUuid_t *uuid, const mcSpid_t spid) { - return search_paths[0] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + return getRegistryPath() + "/" + byteArrayToString(uuid, sizeof(*uuid)) + "." + uint32ToString(spid) + TL_CONT_FILE_EXT; } //------------------------------------------------------------------------------ -static std::string getTlDataPath(const mcUuid_t *uuid) +static string getTlDataPath(const mcUuid_t *uuid) { - return search_paths[0] + "/" + byteArrayToString(uuid, sizeof(*uuid)); + return getRegistryPath() + "/" + byteArrayToString(uuid, sizeof(*uuid)); } //------------------------------------------------------------------------------ -static std::string getTlDataFilePath(const mcUuid_t *uuid, mcPid_t pid) +static string getTlDataFilePath(const mcUuid_t *uuid, mcPid_t pid) { return getTlDataPath(uuid) + "/" + uint32ToString(pid.data) + DATA_CONT_FILE_EXT; } //------------------------------------------------------------------------------ -static std::string getTlBinFilePath(const mcUuid_t *uuid, int registry) -{ - std::string path_rw_registry = search_paths[0] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + TL_BIN_FILE_EXT; - - if ((registry == MC_REGISTRY_ALL) && (search_paths.size() > 1)) { - std::string path_ro_registry = search_paths[1] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + TL_BIN_FILE_EXT; - struct stat tmp; - if (stat(path_ro_registry.c_str(), &tmp) == 0) { - return path_ro_registry; - } - } - return path_rw_registry; -} - -//------------------------------------------------------------------------------ -static std::string getTABinFilePath(const mcUuid_t *uuid, int registry) +static string getTlBinFilePath(const mcUuid_t *uuid) { - std::string path_rw_registry = search_paths[0] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + GP_TA_BIN_FILE_EXT; - - if ((registry == MC_REGISTRY_ALL) && (search_paths.size() > 1)) { - std::string path_ro_registry = search_paths[1] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + GP_TA_BIN_FILE_EXT; - struct stat tmp; - if (stat(path_ro_registry.c_str(), &tmp) == 0) { - return path_ro_registry; - } - } - return path_rw_registry; + return getTlRegistryPath() + "/" + byteArrayToString(uuid, sizeof(*uuid)) + TL_BIN_FILE_EXT; } //------------------------------------------------------------------------------ -static std::string getTASpidFilePath(const mcUuid_t *uuid, int registry) +static string getTABinFilePath(const mcUuid_t *uuid) { - std::string path_rw_registry = search_paths[0] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + GP_TA_SPID_FILE_EXT; - - if ((registry == MC_REGISTRY_ALL) && (search_paths.size() > 1)) { - std::string path_ro_registry = search_paths[1] + "/" + byteArrayToString(uuid, sizeof(*uuid)) + GP_TA_SPID_FILE_EXT; - struct stat tmp; - if (stat(path_ro_registry.c_str(), &tmp) == 0) { - return path_ro_registry; - } - } - return path_rw_registry; + return getTlRegistryPath() + "/" + byteArrayToString(uuid, sizeof(*uuid)) + GP_TA_BIN_FILE_EXT; } //------------------------------------------------------------------------------ -void setSearchPaths(const std::vector& paths) -{ - search_paths = paths; - tb_storage_path = search_paths[0] + "/TbStorage"; -} - -static inline bool isAllZeros(const unsigned char *so, uint32_t size) +static string getTASpidFilePath(const mcUuid_t *uuid) { - for (uint32_t i = 0; i < size; i++) { - if (so[i]) { - return false; - } - } - - return true; + return getTlRegistryPath() + "/" + byteArrayToString(uuid, sizeof(*uuid)) + GP_TA_SPID_FILE_EXT; } //------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreAuthToken(const void *so, size_t size) +mcResult_t mcRegistryStoreAuthToken(void *so, uint32_t size) { - int res = 0; if (so == NULL || size > 3 * MAX_SO_CONT_SIZE) { LOG_E("mcRegistry store So.Soc failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - const std::string &authTokenFilePath = getAuthTokenFilePath(); - LOG_D("store AuthToken: %s", authTokenFilePath.c_str()); - - /* - * This special handling is needed because some of our OEM partners do not - * supply the AuthToken to Kinibi Sphere. Instead, they retain the - * AuthToken in a dedicated (reliable) storage area on the device. And in - * that case, Kinibi Sphere is populated with a all-zero-padded AuthToken. - * (Obviously the zero-padded AuthToken won't work, so we use that zero- - * padding as an indicator to trigger the special behaviour.) - * - * When Kinibi Sphere supplies the device with the zero-padded AuthToken, - * the device must look retrieve the AuthToken from its dedicated storage, - * and use it in place of the zero-padded AuthToken supplied by Kinibi - * Sphere. Since the AuthToken Backup will already have been retrieved from - * the dedicated storage area by the time this method is called, using the - * AuthToken Backup as our source is an acceptable proxy for retrieving it - * from the dedicated storage area directly. - * - * This behaviour is triggered following Root.PA detecting a Factory Reset. - */ - void *backup = NULL; - if (isAllZeros((const unsigned char*)so, size)) { - const std::string &authTokenFilePathBackup = getAuthTokenFilePathBackup(); - - LOG_D("AuthToken is all zeros"); - FILE *backupfs = fopen(authTokenFilePathBackup.c_str(), "rb"); - if (backupfs) { - backup = malloc(size); - if (backup) { - size_t readsize = fread(backup, 1, size, backupfs); - if (readsize == size) { - LOG_D("AuthToken reset backup"); - so = backup; - } else { - LOG_E("AuthToken read size = %zu (%zu)", readsize, size); - } - } - fclose(backupfs); - } else { - LOG_W("can't open AuthToken %s", authTokenFilePathBackup.c_str()); - } - } + const string &authTokenFilePath = getAuthTokenFilePath(); + LOG_I("store AuthToken: %s", authTokenFilePath.c_str()); - mcResult_t ret = MC_DRV_OK; FILE *fs = fopen(authTokenFilePath.c_str(), "wb"); - if (fs == NULL) { - ret = MC_DRV_ERR_INVALID_DEVICE_FILE; - } else { - res = fseek(fs, 0, SEEK_SET); - if (res != 0) { - ret = MC_DRV_ERR_INVALID_PARAMETER; - } else { - fwrite(so, 1, size, fs); - if (ferror(fs)) { - ret = MC_DRV_ERR_OUT_OF_RESOURCES; - } - } - fclose(fs); - } - if (ret != MC_DRV_OK) { - LOG_ERRNO("mcRegistry store So.Soc failed"); - } - free(backup); - - return ret; -} - -//------------------------------------------------------------------------------ -mcResult_t mcRegistryReadAuthToken(mcSoAuthTokenCont_t *so) -{ - int res = 0; - if (NULL == so) { - LOG_E("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - return MC_DRV_ERR_INVALID_PARAMETER; - } - const std::string &authTokenFilePath = getAuthTokenFilePath(); - LOG_D("read AuthToken: %s", authTokenFilePath.c_str()); - - FILE *fs = fopen(authTokenFilePath.c_str(), "rb"); - if (fs==NULL) { - LOG_W("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); + if (!fs) { + LOG_E("mcRegistry store So.Soc failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_END); - if (res!=0) { - LOG_E("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - long filesize = ftell(fs); - // We ensure that mcSoAuthTokenCont_t matches with filesize, as ferror (during fread operation) can't - // handle the case where mcSoAuthTokenCont_t < filesize - if (sizeof(mcSoAuthTokenCont_t) != filesize) { - fclose(fs); - LOG_W("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - size_t read_res = fread(so, 1, sizeof(mcSoAuthTokenCont_t), fs); - if (ferror(fs)) { - fclose(fs); - LOG_E("mcRegistry read So.Soc failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - return MC_DRV_ERR_INVALID_PARAMETER; - } - if (read_res 3 * MAX_SO_CONT_SIZE) { LOG_E("mcRegistry store So.Root failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - const std::string &rootContFilePath = getRootContFilePath(); - LOG_D("store Root: %s", rootContFilePath.c_str()); + const string &rootContFilePath = getRootContFilePath(); + LOG_I("store Root: %s", rootContFilePath.c_str()); FILE *fs = fopen(rootContFilePath.c_str(), "wb"); - if (fs==NULL) { + if (!fs) { LOG_E("mcRegistry store So.Root failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry store So.Root failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - fwrite(so, 1, size, fs); - if (ferror(fs)) { - LOG_E("mcRegistry store So.Root failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - fclose(fs); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, size, fs); fflush(fs); fclose(fs); @@ -478,30 +327,25 @@ mcResult_t mcRegistryStoreRoot(const void *so, size_t size) //------------------------------------------------------------------------------ mcResult_t mcRegistryReadRoot(void *so, uint32_t *size) { - const std::string &rootContFilePath = getRootContFilePath(); + const string &rootContFilePath = getRootContFilePath(); size_t readBytes; if (so == NULL) { LOG_E("mcRegistry read So.Root failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - LOG_D(" Opening %s", rootContFilePath.c_str()); + LOG_I(" Opening %s", rootContFilePath.c_str()); FILE *fs = fopen(rootContFilePath.c_str(), "rb"); - if (fs==NULL) { + if (!fs) { LOG_W("mcRegistry read So.Root failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - readBytes = fread(so, 1, *size, fs); - if (ferror(fs)) { - fclose(fs); - LOG_E("mcRegistry read So.Root failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - return MC_DRV_ERR_INVALID_PARAMETER; - } + readBytes = fread((char *)so, 1, *size, fs); fclose(fs); if (readBytes > 0) { - *size = static_cast(readBytes); + *size = readBytes; return MC_DRV_OK; } else { LOG_E("mcRegistry read So.Root failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); @@ -511,34 +355,23 @@ mcResult_t mcRegistryReadRoot(void *so, uint32_t *size) //------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreSp(mcSpid_t spid, const void *so, size_t size) +mcResult_t mcRegistryStoreSp(mcSpid_t spid, void *so, uint32_t size) { - int res = 0; if ((spid == 0) || (so == NULL) || size > 3 * MAX_SO_CONT_SIZE) { LOG_E("mcRegistry store So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - const std::string &spContFilePath = getSpContFilePath(spid); - LOG_D("store SP: %s", spContFilePath.c_str()); + const string &spContFilePath = getSpContFilePath(spid); + LOG_I("store SP: %s", spContFilePath.c_str()); FILE *fs = fopen(spContFilePath.c_str(), "wb"); - if (fs==NULL) { + if (!fs) { LOG_E("mcRegistry store So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry store So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - fwrite(so, 1, size, fs); - if (ferror(fs)) { - LOG_E("mcRegistry store So.Sp(SpId) failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - fclose(fs); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, size, fs); fflush(fs); fclose(fs); @@ -549,29 +382,24 @@ mcResult_t mcRegistryStoreSp(mcSpid_t spid, const void *so, size_t size) //------------------------------------------------------------------------------ mcResult_t mcRegistryReadSp(mcSpid_t spid, void *so, uint32_t *size) { - const std::string &spContFilePath = getSpContFilePath(spid); + const string &spContFilePath = getSpContFilePath(spid); size_t readBytes; if ((spid == 0) || (so == NULL)) { LOG_E("mcRegistry read So.Sp(SpId=0x%x) failed", spid); return MC_DRV_ERR_INVALID_PARAMETER; } - LOG_D(" Reading %s", spContFilePath.c_str()); + LOG_I(" Reading %s", spContFilePath.c_str()); FILE *fs = fopen(spContFilePath.c_str(), "rb"); - if (fs==NULL) { + if (!fs) { LOG_E("mcRegistry read So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - readBytes = fread(so, 1, *size, fs); - if (ferror(fs)) { - fclose(fs); - LOG_E("mcRegistry read So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - return MC_DRV_ERR_INVALID_PARAMETER; - } + readBytes = fread((char *)so, 1, *size, fs); fclose(fs); if (readBytes > 0) { - *size = static_cast(readBytes); + *size = readBytes; return MC_DRV_OK; } else { LOG_E("mcRegistry read So.Sp(SpId) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); @@ -581,34 +409,23 @@ mcResult_t mcRegistryReadSp(mcSpid_t spid, void *so, uint32_t *size) //------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, const void *so, size_t size) +mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, void *so, uint32_t size) { - int res = 0; if ((uuid == NULL) || (so == NULL) || size > 3 * MAX_SO_CONT_SIZE) { LOG_E("mcRegistry store So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - const std::string &tlContFilePath = getTlContFilePath(uuid, spid); - LOG_D("store TLc: %s", tlContFilePath.c_str()); + const string &tlContFilePath = getTlContFilePath(uuid, spid); + LOG_I("store TLc: %s", tlContFilePath.c_str()); FILE *fs = fopen(tlContFilePath.c_str(), "wb"); - if (fs==NULL) { + if (!fs) { LOG_E("mcRegistry store So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry store So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - fwrite(so, 1, size, fs); - if (ferror(fs)) { - LOG_E("mcRegistry store So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - fclose(fs); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } + fseek(fs, 0, SEEK_SET); + fwrite((char *)so, 1, size, fs); fflush(fs); fclose(fs); @@ -616,18 +433,18 @@ mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, } static uint32_t getAsUint32BE( - const void *pValueUnaligned + void *pValueUnaligned ) { - auto p = static_cast(pValueUnaligned); + uint8_t *p = (uint8_t *)pValueUnaligned; uint32_t val = p[3] | (p[2] << 8) | (p[1] << 16) | (p[0] << 24); return val; } -mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) +mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, void *blob, uint32_t size) { - int res = 0; - LOG_D("mcRegistryStoreTABlob started"); + + LOG_I("mcRegistryStoreTABlob started"); // Check blob size if (size < sizeof(mclfHeaderV24_t)) { @@ -635,8 +452,8 @@ mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) return MC_DRV_ERR_INVALID_PARAMETER; } - auto header24 = reinterpret_cast(blob); - auto header20 = reinterpret_cast(blob); + mclfHeaderV24_t *header24 = (mclfHeaderV24_t *)blob; + mclfHeaderV2_t *header20 = (mclfHeaderV2_t *)blob; // Check header version if (header20->intro.version < MC_MAKE_VERSION(2, 4)) { @@ -650,7 +467,7 @@ mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) return MC_DRV_ERR_TA_HEADER_ERROR; } - mcUuid_t uuid; + TEEC_UUID uuid; switch (header20->serviceType) { case SERVICE_TYPE_SYSTEM_TRUSTLET: { // Check spid @@ -668,7 +485,7 @@ mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) return MC_DRV_ERR_INVALID_PARAMETER; } - auto pUa = reinterpret_cast(&static_cast(blob)[header24->attestationOffset]); + uuid_attestation *pUa = (uuid_attestation *) & ((uint8_t *)blob)[header24->attestationOffset]; // Check attestation size if ((header24->attestationOffset > size) && (header24->attestationOffset + getAsUint32BE(&pUa->size) > size)) { LOG_E("RegistryStoreTABlob failed - Attestation size is not correct"); @@ -677,7 +494,7 @@ mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) // Check attestation size if (getAsUint32BE(&pUa->size) < sizeof(uuid_attestation)) { - LOG_E("RegistryStoreTABlob failed - Attestation size is equal to %d and is less then %zu", getAsUint32BE(&pUa->size), sizeof(uuid_attestation)); + LOG_E("RegistryStoreTABlob failed - Attestation size is equal to %d and is less then %d", getAsUint32BE(&pUa->size), sizeof(uuid_attestation)); return MC_DRV_ERR_TA_ATTESTATION_ERROR; } @@ -700,52 +517,33 @@ mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) return MC_DRV_ERR_INVALID_PARAMETER; } } - const std::string taBinFilePath = getTABinFilePath(&uuid, MC_REGISTRY_WRITABLE); + const string tlBinFilePath = getTABinFilePath((mcUuid_t *)&uuid); - LOG_D("Store TA blob at: %s", taBinFilePath.c_str()); + LOG_I("Store TA blob at: %s", tlBinFilePath.c_str()); - FILE *fs = fopen(taBinFilePath.c_str(), "wb"); - if (fs==NULL) { + FILE *fs = fopen(tlBinFilePath.c_str(), "wb"); + if (!fs) { LOG_E("RegistryStoreTABlob failed - TA blob file open error: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("RegistryStoreTABlob failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } + fseek(fs, 0, SEEK_SET); fwrite(blob, 1, size, fs); - if (ferror(fs)) { - LOG_E("RegistryStoreTABlob failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - fclose(fs); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } fflush(fs); fclose(fs); if (header20->serviceType == SERVICE_TYPE_SP_TRUSTLET) { - const std::string taspidFilePath = getTASpidFilePath(&uuid, MC_REGISTRY_WRITABLE); + const string taspidFilePath = getTASpidFilePath((mcUuid_t *)&uuid); - LOG_D("Store spid file at: %s", taspidFilePath.c_str()); + LOG_I("Store spid file at: %s", taspidFilePath.c_str()); FILE *fs = fopen(taspidFilePath.c_str(), "wb"); - if (fs==NULL) { + if (!fs) { + //TODO: shouldn't we delete TA blob file ? LOG_E("RegistryStoreTABlob failed - TA blob file open error: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("RegistryStoreTABlob failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } + fseek(fs, 0, SEEK_SET); fwrite(&spid, 1, sizeof(mcSpid_t), fs); - if (ferror(fs)) { - LOG_E("RegistryStoreTABlob failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - fclose(fs); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } fflush(fs); fclose(fs); } @@ -755,36 +553,25 @@ mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size) //------------------------------------------------------------------------------ mcResult_t mcRegistryReadTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, void *so, uint32_t *size) { - int res = 0; if ((uuid == NULL) || (so == NULL)) { LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } size_t readBytes; - const std::string &tlContFilePath = getTlContFilePath(uuid, spid); - LOG_D("read TLc: %s", tlContFilePath.c_str()); + const string &tlContFilePath = getTlContFilePath(uuid, spid); + LOG_I("read TLc: %s", tlContFilePath.c_str()); FILE *fs = fopen(tlContFilePath.c_str(), "rb"); - if (fs==NULL) { + if (!fs) { LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); return MC_DRV_ERR_INVALID_DEVICE_FILE; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - readBytes = fread(so, 1, *size, fs); - if (ferror(fs)) { - fclose(fs); - LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - return MC_DRV_ERR_INVALID_PARAMETER; - } + fseek(fs, 0, SEEK_SET); + readBytes = fread((char *)so, 1, *size, fs); fclose(fs); if (readBytes > 0) { - *size = static_cast(readBytes); + *size = readBytes; return MC_DRV_OK; } else { LOG_E("mcRegistry read So.TrustletCont(uuid) failed: %d", MC_DRV_ERR_INVALID_DEVICE_FILE); @@ -794,16 +581,15 @@ mcResult_t mcRegistryReadTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, //------------------------------------------------------------------------------ -mcResult_t mcRegistryStoreData(const void *so, size_t size) +mcResult_t mcRegistryStoreData(void *so, uint32_t size) { - const mcSoDataCont_t *dataCont = reinterpret_cast(so); - int res = 0; + mcSoDataCont_t *dataCont = (mcSoDataCont_t *)so; if (dataCont == NULL || size != sizeof(mcSoDataCont_t)) { LOG_E("mcRegistry store So.Data failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - std::string pathname, filename; + string pathname, filename; switch (dataCont->cont.type) { case CONT_TYPE_SPDATA: @@ -824,25 +610,15 @@ mcResult_t mcRegistryStoreData(const void *so, size_t size) return MC_DRV_ERR_INVALID_PARAMETER; } - LOG_D("store DT: %s", filename.c_str()); + LOG_I("store DT: %s", filename.c_str()); FILE *fs = fopen(filename.c_str(), "wb"); - if (fs==NULL) { + 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; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry store So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - fwrite(dataCont, 1, MC_SO_SIZE(dataCont->soHeader.plainLen, dataCont->soHeader.encryptedLen), fs); - if (ferror(fs)) { - LOG_E("mcRegistry store So.Data(cid/pid) failed: %d", MC_DRV_ERR_OUT_OF_RESOURCES); - fclose(fs); - return MC_DRV_ERR_OUT_OF_RESOURCES; - } + fseek(fs, 0, SEEK_SET); + fwrite((char *)dataCont, 1, MC_SO_SIZE(dataCont->soHeader.plainLen, dataCont->soHeader.encryptedLen), fs); fflush(fs); fclose(fs); @@ -851,16 +627,15 @@ mcResult_t mcRegistryStoreData(const void *so, size_t size) //------------------------------------------------------------------------------ -mcResult_t mcRegistryReadData(uint32_t context, const mcCid_t *cid, mcPid_t, +mcResult_t mcRegistryReadData(uint32_t context, const mcCid_t *cid, mcPid_t pid __unused, mcSoDataCont_t *so, uint32_t maxLen) { - int res = 0; if ((NULL == cid) || (NULL == so)) { LOG_E("mcRegistry read So.Data failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - std::string filename; + string filename; switch (context) { case 0: LOG_E("SPDATA not supported"); @@ -873,64 +648,39 @@ mcResult_t mcRegistryReadData(uint32_t context, const mcCid_t *cid, mcPid_t, LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - LOG_D("read DT: %s", filename.c_str()); + LOG_I("read DT: %s", filename.c_str()); FILE *fs = fopen(filename.c_str(), "rb"); - if (fs==NULL) { + 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; } - res = fseek(fs, 0, SEEK_END); - if (res!=0) { - LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - long filesize = ftell(fs); - if (static_cast(maxLen) < filesize) { + fseek(fs, 0, SEEK_END); + uint32_t filesize = ftell(fs); + if (maxLen < filesize) { 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; } - res = fseek(fs, 0, SEEK_SET); - if (res!=0) { - LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } - char *p = reinterpret_cast(so); - size_t read_res = fread(p, 1, sizeof(mcSoHeader_t), fs); - if (ferror(fs)) { + fseek(fs, 0, SEEK_SET); + char *p = (char *) so; + if (fread(p, 1, sizeof(mcSoHeader_t), fs) != sizeof(mcSoHeader_t)) + { fclose(fs); LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - if (read_ressoHeader.plainLen, + if (fread(p, 1, MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen) - - sizeof(mcSoHeader_t), fs); - if (ferror(fs)) { + - sizeof(mcSoHeader_t), fs) != + MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen) + - sizeof(mcSoHeader_t)) + { fclose(fs); LOG_E("mcRegistry read So.Data(cid/pid) failed: %d", MC_DRV_ERR_INVALID_PARAMETER); return MC_DRV_ERR_INVALID_PARAMETER; } - if (read_res<(MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen) - sizeof(mcSoHeader_t))) { - //File is shorter than expected - if (feof(fs)) { - LOG_E("%s(): EOF reached: res is %zu, size of secure object is %zu", __func__, read_res, - MC_SO_SIZE(so->soHeader.plainLen, so->soHeader.encryptedLen) - sizeof(mcSoHeader_t)); - } - fclose(fs); - return MC_DRV_ERR_INVALID_PARAMETER; - } fclose(fs); return MC_DRV_OK; @@ -938,14 +688,13 @@ mcResult_t mcRegistryReadData(uint32_t context, const mcCid_t *cid, mcPid_t, //------------------------------------------------------------------------------ -static uint32_t getFileContent( +static size_t getFileContent( const char *pPath, uint8_t **ppContent) { FILE *pStream; long filesize; uint8_t *content = NULL; - size_t res = 0; /* Open the file */ pStream = fopen(pPath, "rb"); @@ -977,36 +726,28 @@ static uint32_t getFileContent( } /* Allocate a buffer for the content */ - content = new uint8_t[filesize]; + content = (uint8_t *)malloc(filesize); if (content == NULL) { LOG_E("Error: Cannot read file: Out of memory."); goto error; } /* Read data from the file into the buffer */ - res = fread(content, filesize, 1, pStream); - if (ferror(pStream)) { + if (fread(content, (size_t)filesize, 1, pStream) != 1) { LOG_E("Error: Cannot read file: %s.", pPath); goto error; } - if (res < 1) { - //File is shorter than expected - if (feof(pStream)) { - LOG_E("Error: EOF reached: %s.", pPath); - } - goto error; - } /* Close the file */ fclose(pStream); *ppContent = content; /* Return number of bytes read */ - return static_cast(filesize); + return (size_t)filesize; error: - if (content != NULL) { - delete[] content; + if (content != NULL) { + free(content); } fclose(pStream); return 0; @@ -1027,45 +768,46 @@ static bool mcCheckUuid(const mcUuid_t *uuid, const char *filename) // Check blob size if (nTASize < sizeof(mclfHeaderV24_t)) { - delete[] pTAData; - LOG_E("getFileContent failed - TA length is less than header size"); + free(pTAData); + LOG_E("RegistryStoreTABlob failed - TA blob length is less then header size"); return false; } - mclfHeaderV2_t *header20 = reinterpret_cast(pTAData); + mclfHeaderV2_t *header20 = (mclfHeaderV2_t *)pTAData; // Check header version if (header20->intro.version < MC_MAKE_VERSION(2, 4)) { - delete[] pTAData; - LOG_E("mcCheckUuid() - TA blob header version is less than 2.4"); + free(pTAData); + LOG_E("RegistryStoreTABlob failed - TA blob header version is less than 2.4"); return false; } - // Check uuid + // Check blob size if (memcmp(uuid, &header20->uuid, sizeof(mcUuid_t)) == 0) { res = true; } else { res = false; } - delete[] pTAData; + free(pTAData); return res; } //this function deletes all the files owned by a GP TA and stored in the tbase secure storage dir. //then it deletes GP TA folder. -static int CleanupGPTAStorage(const char *uuid) +static int CleanupGPTAStorage(const char *basename) { DIR *dp; struct dirent *de; int e; - std::string TAPath = getTbStoragePath() + "/" + uuid; + string TAPath = getTlRegistryPath()+"/TbStorage/"+ basename; + if (NULL != (dp = opendir(TAPath.c_str()))) { while (NULL != (de = readdir(dp))) { if (de->d_name[0] != '.') { - std::string dname = TAPath + "/" + std::string(de->d_name); - LOG_D("delete DT: %s", dname.c_str()); + string dname = TAPath + "/" + string (de->d_name); + LOG_I("delete DT: %s", dname.c_str()); if (0 != (e = remove(dname.c_str()))) { LOG_E("remove UUID-files %s failed! error: %d", dname.c_str(), e); } @@ -1074,7 +816,7 @@ static int CleanupGPTAStorage(const char *uuid) if (dp) { closedir(dp); } - LOG_D("delete dir: %s", TAPath.c_str()); + LOG_I("delete dir: %s", TAPath.c_str()); if (0 != (e = rmdir(TAPath.c_str()))) { LOG_E("remove UUID-dir failed! errno: %d", e); return e; @@ -1083,30 +825,25 @@ static int CleanupGPTAStorage(const char *uuid) return MC_DRV_OK; } - -mcResult_t mcRegistryCleanupGPTAStorage(const mcUuid_t *uuid) -{ - return CleanupGPTAStorage(byteArrayToString(uuid, sizeof(*uuid)).c_str()); -} - -static void deleteSPTA(const mcUuid_t *uuid, const mcSpid_t spid) +static void deleteSPTA(const mcUuid_t *uuid, const mcSpid_t spid, bool checkUuid) { DIR *dp; struct dirent *de; int e; // Delete TABIN and SPID files - we loop searching required spid file - if (NULL != (dp = opendir(search_paths[0].c_str()))) { + string pathname = getRegistryPath(); + if (NULL != (dp = opendir(pathname.c_str()))) { while (NULL != (de = readdir(dp))) { - std::string spidFile; - std::string tabinFile; - std::string tabinUuid; + string spidFile; + string tabinFile; + string tabinUuid; size_t pch_dot, pch_slash; - spidFile = search_paths[0] + "/" + std::string(de->d_name); + spidFile = pathname + '/' + string(de->d_name); pch_dot = spidFile.find_last_of('.'); - if (pch_dot == std::string::npos) continue; + if (pch_dot == string::npos) continue; pch_slash = spidFile.find_last_of('/'); - if ((pch_slash != std::string::npos) && (pch_slash > pch_dot)) continue; + if ((pch_slash != string::npos) && (pch_slash > pch_dot)) continue; if (spidFile.substr(pch_dot).compare(GP_TA_SPID_FILE_EXT) != 0) continue; mcSpid_t curSpid = 0; @@ -1120,31 +857,28 @@ static void deleteSPTA(const mcUuid_t *uuid, const mcSpid_t spid) } if (spid == curSpid) { tabinFile = spidFile.substr(0, pch_dot) + GP_TA_BIN_FILE_EXT; - if (mcCheckUuid(uuid, tabinFile.c_str())) { - tabinUuid = spidFile.substr(0, pch_dot); - tabinUuid = tabinUuid.substr(tabinUuid.find_last_of('/')+1); - LOG_D("Remove TA storage %s", tabinUuid.c_str()); - if (0 != (e = CleanupGPTAStorage(tabinUuid.c_str()))){ - LOG_E("Remove TA storage failed! errno: %d", e); - /* Discard error */ - } - LOG_D("Remove TA file %s", tabinFile.c_str()); + if ((!checkUuid)||(mcCheckUuid(uuid, tabinFile.c_str()))) { + tabinUuid = spidFile.substr(0, pch_dot); + if (0 != (e = CleanupGPTAStorage(tabinUuid.c_str()))){ + LOG_E("cleanup TA Storage dir failed! errno: %d", e); + //return MC_DRV_ERR_UNKNOWN; + } if (0 != (e = remove(tabinFile.c_str()))) { - LOG_E("Remove TA file failed! errno: %d", e); - /* Discard error */ + LOG_E("remove TA file failed! errno: %d", e); + //return MC_DRV_ERR_UNKNOWN; } - LOG_D("Remove spid file %s", spidFile.c_str()); if (0 != (e = remove(spidFile.c_str()))) { - LOG_E("Remove spid file failed! errno: %d", e); - /* Discard error */ + LOG_E("remove SPID file failed! errno: %d", e); + //return MC_DRV_ERR_UNKNOWN; } - break; + if (checkUuid) break; } } } if (dp) { closedir(dp); } + } } @@ -1161,12 +895,12 @@ mcResult_t mcRegistryCleanupTrustlet(const mcUuid_t *uuid, const mcSpid_t spid) } // Delete all TA related data - std::string pathname = getTlDataPath(uuid); + string pathname = getTlDataPath(uuid); if (NULL != (dp = opendir(pathname.c_str()))) { while (NULL != (de = readdir(dp))) { if (de->d_name[0] != '.') { - std::string dname = pathname + "/" + std::string(de->d_name); - LOG_D("delete DT: %s", dname.c_str()); + string dname = pathname + "/" + string (de->d_name); + LOG_I("delete DT: %s", dname.c_str()); if (0 != (e = remove(dname.c_str()))) { LOG_E("remove UUID-data %s failed! error: %d", dname.c_str(), e); } @@ -1175,34 +909,30 @@ mcResult_t mcRegistryCleanupTrustlet(const mcUuid_t *uuid, const mcSpid_t spid) if (dp) { closedir(dp); } - LOG_D("delete dir: %s", pathname.c_str()); + LOG_I("delete dir: %s", pathname.c_str()); if (0 != (e = rmdir(pathname.c_str()))) { LOG_E("remove UUID-dir failed! errno: %d", e); return MC_DRV_ERR_UNKNOWN; } } - std::string tlBinFilePath = getTlBinFilePath(uuid, MC_REGISTRY_WRITABLE); - struct stat tmp; - std::string tlContFilePath = getTlContFilePath(uuid, spid);; - - if (stat(tlBinFilePath.c_str(), &tmp) == 0) { - /* Legacy TA */ - LOG_D("Remove TA file %s", tlBinFilePath.c_str()); - if (0 != (e = remove(tlBinFilePath.c_str()))) { - LOG_E("Remove TA file failed! errno: %d", e); - } - } else { - /* GP TA */ - deleteSPTA(uuid, spid); + // Delete TA binary with the name uuid.tlbin + string tlBinFilePath = getTlBinFilePath(uuid); + LOG_I("delete Tlb: %s", tlBinFilePath.c_str()); + if (0 != (e = remove(tlBinFilePath.c_str()))) { + LOG_E("remove Tlb failed! errno: %d", e); +// return MC_DRV_ERR_UNKNOWN; // a trustlet-binary must not be present ! (registered but not usable) } - LOG_D("Remove TA container %s", tlContFilePath.c_str()); + // Delete TABIN and SPID files - we loop searching required spid file + deleteSPTA(uuid,spid,true); + + string tlContFilePath = getTlContFilePath(uuid, spid); + LOG_I("delete Tlc: %s", tlContFilePath.c_str()); if (0 != (e = remove(tlContFilePath.c_str()))) { - LOG_E("Remove TA container failed! errno: %d", e); + LOG_E("remove Tlc failed! errno: %d", e); return MC_DRV_ERR_UNKNOWN; } - return MC_DRV_OK; } @@ -1228,9 +958,7 @@ mcResult_t mcRegistryCleanupSp(mcSpid_t spid) return ret; } for (i = 0; (i < MC_CONT_CHILDREN_COUNT) && (ret == MC_DRV_OK); i++) { - if (0 != strncmp(reinterpret_cast(&data.cont.children[i]), - reinterpret_cast(&MC_UUID_FREE), - sizeof(mcUuid_t))) { + if (0 != strncmp((const char *) & (data.cont.children[i]), (const char *)&MC_UUID_FREE, sizeof(mcUuid_t))) { ret = mcRegistryCleanupTrustlet(&(data.cont.children[i]), spid); } } @@ -1239,13 +967,16 @@ mcResult_t mcRegistryCleanupSp(mcSpid_t spid) return ret; } - std::string pathname = getSpDataPath(spid); + // Delete remaining TABIN and SPID files + deleteSPTA(NULL,spid,false); + + string pathname = getSpDataPath(spid); if (NULL != (dp = opendir(pathname.c_str()))) { while (NULL != (de = readdir(dp))) { if (de->d_name[0] != '.') { - std::string dname = pathname + "/" + std::string(de->d_name); - LOG_D("delete DT: %s", dname.c_str()); + string dname = pathname + "/" + string (de->d_name); + LOG_I("delete DT: %s", dname.c_str()); if (0 != (e = remove(dname.c_str()))) { LOG_E("remove SPID-data %s failed! error: %d", dname.c_str(), e); } @@ -1254,14 +985,14 @@ mcResult_t mcRegistryCleanupSp(mcSpid_t spid) if (dp) { closedir(dp); } - LOG_D("delete dir: %s", pathname.c_str()); + LOG_I("delete dir: %s", pathname.c_str()); if (0 != (e = rmdir(pathname.c_str()))) { LOG_E("remove SPID-dir failed! error: %d", e); return MC_DRV_ERR_UNKNOWN; } } - std::string spContFilePath = getSpContFilePath(spid); - LOG_D("delete Sp: %s", spContFilePath.c_str()); + string spContFilePath = getSpContFilePath(spid); + LOG_I("delete Sp: %s", spContFilePath.c_str()); if (0 != (e = remove(spContFilePath.c_str()))) { LOG_E("remove SP failed! error: %d", e); return MC_DRV_ERR_UNKNOWN; @@ -1294,8 +1025,8 @@ mcResult_t mcRegistryCleanupRoot(void) } } - std::string rootContFilePath = getRootContFilePath(); - LOG_D("Delete root: %s", rootContFilePath.c_str()); + string rootContFilePath = getRootContFilePath(); + LOG_I("Delete root: %s", rootContFilePath.c_str()); if (0 != (e = remove(rootContFilePath.c_str()))) { LOG_E("Delete root failed! error: %d", e); return MC_DRV_ERR_UNKNOWN; @@ -1304,34 +1035,252 @@ mcResult_t mcRegistryCleanupRoot(void) } //------------------------------------------------------------------------------ -mcResult_t mcRegistryGetTrustletInfo(const mcUuid_t *uuid, bool isGpUuid, mcSpid_t *spid, std::string& path) +regObject_t *mcRegistryMemGetServiceBlob(mcSpid_t spid, void *trustlet, uint32_t tlSize) +{ + regObject_t *regobj = NULL; + + // Ensure that a UUID is provided. + if (NULL == trustlet) { + LOG_E("No trustlet buffer given"); + return NULL; + } + + // Check service blob size. + if (tlSize > MAX_TL_SIZE ) { + LOG_E("mcRegistryMemGetServiceBlob() failed: service blob too big: %d", tlSize); + return NULL; + } + + mclfIntro_t *pIntro = (mclfIntro_t *)trustlet; + // Check TL magic value. + if (pIntro->magic != MC_SERVICE_HEADER_MAGIC_BE) { + LOG_E("mcRegistryMemGetServiceBlob() failed: wrong header magic value: %d", pIntro->magic); + return NULL; + } + + // Get service type. + mclfHeaderV2_t *pHeader = (mclfHeaderV2_t *)trustlet; +#ifndef NDEBUG + { + const char *service_types[] = { + "illegal", "Driver", "Trustlet", "System Trustlet" + }; + int serviceType_safe = pHeader->serviceType > SERVICE_TYPE_SYSTEM_TRUSTLET ? SERVICE_TYPE_ILLEGAL : pHeader->serviceType; + LOG_I(" Service is a %s (service type %d)", service_types[serviceType_safe], pHeader->serviceType); + } +#endif + + LOG_I(" Trustlet text %u data %u ", pHeader->text.len, pHeader->data.len); + + // If loadable driver or system trustlet. + if (pHeader->serviceType == SERVICE_TYPE_DRIVER || pHeader->serviceType == SERVICE_TYPE_SYSTEM_TRUSTLET) { + // Take trustlet blob 'as is'. + if (NULL == (regobj = (regObject_t *) (malloc(sizeof(regObject_t) + tlSize)))) { + LOG_E("mcRegistryMemGetServiceBlob() failed: Out of memory"); + return NULL; + } + regobj->len = tlSize; + regobj->tlStartOffset = 0; + memcpy((char *)regobj->value, trustlet, tlSize); + // If user trustlet. + } else if (pHeader->serviceType == SERVICE_TYPE_SP_TRUSTLET) { + // Take trustlet blob and append root, sp, and tl container. + size_t regObjValueSize = tlSize + sizeof(mcBlobLenInfo_t) + 3 * MAX_SO_CONT_SIZE; + + // Prepare registry object. + if (NULL == (regobj = (regObject_t *) malloc(sizeof(regObject_t) + regObjValueSize))) { + LOG_E("mcRegistryMemGetServiceBlob() failed: Out of memory"); + return NULL; + } + regobj->len = regObjValueSize; + regobj->tlStartOffset = sizeof(mcBlobLenInfo_t); + uint8_t *p = regobj->value; + + // Reserve space for the blob length structure + mcBlobLenInfo_ptr lenInfo = (mcBlobLenInfo_ptr)p; + lenInfo->magic = MC_TLBLOBLEN_MAGIC; + p += sizeof(mcBlobLenInfo_t); + // Fill in trustlet blob after the len info + memcpy(p, trustlet, tlSize); + p += tlSize; + + // Final registry object value looks like this: + // + // +---------------+---------------------------+-----------+---------+---------+ + // | Blob Len Info | TL-Header TL-Code TL-Data | Root Cont | SP Cont | TL Cont | + // +---------------+---------------------------+-----------+-------------------+ + // /------ Trustlet BLOB ------/ + // + // /------------------ regobj->header.len -------------------------------------/ + + // start at the end of the trustlet blob + mcResult_t ret; + do { + uint32_t soTltContSize = MAX_SO_CONT_SIZE; + uint32_t len; + + // Fill in root container. + len = sizeof(mcSoRootCont_t); + if (MC_DRV_OK != (ret = mcRegistryReadRoot(p, &len))) { + break; + } + lenInfo->rootContBlobSize = len; + p += len; + + // Fill in SP container. + len = sizeof(mcSoSpCont_t); + if (MC_DRV_OK != (ret = mcRegistryReadSp(spid, p, &len))) { + break; + } + lenInfo->spContBlobSize = len; + p += len; + + // Fill in TLT Container + // We know exactly how much space is left in the buffer + soTltContSize = regObjValueSize - tlSize + sizeof(mcBlobLenInfo_t) + - lenInfo->spContBlobSize - lenInfo->rootContBlobSize; + if (MC_DRV_OK != (ret = mcRegistryReadTrustletCon(&pHeader->uuid, spid, p, &soTltContSize))) { + break; + } + lenInfo->tlContBlobSize = soTltContSize; + LOG_I(" Trustlet container %u bytes loaded", soTltContSize); + // Depending on the trustlet container size we decide which structure to use + // Unfortunate design but it should have to do for now + if (soTltContSize == sizeof(mcSoTltCont_2_0_t)) { + LOG_I(" Using 2.0 trustlet container"); + } else if (soTltContSize == sizeof(mcSoTltCont_2_1_t)) { + LOG_I(" Using 2.1 trustlet container"); + } else { + LOG_E("Trustlet container has unknown size"); + break; + } + } while (false); + + if (MC_DRV_OK != ret) { + LOG_E("mcRegistryMemGetServiceBlob() failed: Error code: %d", ret); + free(regobj); + return NULL; + } + // Now we know the sizes for all containers so set the correct size + regobj->len = sizeof(mcBlobLenInfo_t) + tlSize + + lenInfo->rootContBlobSize + + lenInfo->spContBlobSize + + lenInfo->tlContBlobSize; + // Any other service type. + } else { + LOG_E("mcRegistryMemGetServiceBlob() failed: Unsupported service type %u", pHeader->serviceType); + } + return regobj; +} + + +//------------------------------------------------------------------------------ +regObject_t *mcRegistryFileGetServiceBlob(const char *trustlet, mcSpid_t spid) +{ + struct stat sb; + regObject_t *regobj = NULL; + void *buffer; + + // Ensure that a file name is provided. + if (trustlet == NULL) { + LOG_E("No file given"); + return NULL; + } + + int fd = open(trustlet, O_RDONLY); + if (fd == -1) { + LOG_E("Cannot open %s", trustlet); + return NULL; + } + + if (fstat(fd, &sb) == -1) { + LOG_E("mcRegistryFileGetServiceBlob() failed: Cound't get file size"); + goto error; + } + + buffer = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (buffer == MAP_FAILED) { + LOG_E("mcRegistryFileGetServiceBlob(): Failed to map file to memory"); + goto error; + } + + regobj = mcRegistryMemGetServiceBlob(spid, buffer, sb.st_size); + + // We don't actually care if either of them fails but should still print warnings + if (munmap(buffer, sb.st_size)) { + LOG_E("mcRegistryFileGetServiceBlob(): Failed to unmap memory"); + } + +error: + if (close(fd)) { + LOG_E("mcRegistryFileGetServiceBlob(): Failed to close file %s", trustlet); + } + + return regobj; +} + + +//------------------------------------------------------------------------------ +regObject_t *mcRegistryGetServiceBlob(const mcUuid_t *uuid, bool isGpUuid) { // Ensure that a UUID is provided. if (NULL == uuid) { LOG_E("No UUID given"); - return MC_DRV_ERR_INVALID_PARAMETER; + return NULL; } + // Open service blob file. + string tlBinFilePath; if (isGpUuid) { - path = getTABinFilePath(uuid, MC_REGISTRY_ALL); + tlBinFilePath = getTABinFilePath(uuid); } else { - path = getTlBinFilePath(uuid, MC_REGISTRY_ALL); + tlBinFilePath = getTlBinFilePath(uuid); } + LOG_I("Loading %s", tlBinFilePath.c_str()); - *spid = 0; + mcSpid_t spid = 0; if (isGpUuid) { - std::string taspidFilePath = getTASpidFilePath(uuid, MC_REGISTRY_ALL); + string taspidFilePath = getTASpidFilePath(uuid); int fd = open(taspidFilePath.c_str(), O_RDONLY); - if (fd >= 0) { - bool failed = read(fd, spid, sizeof(*spid)) != sizeof(*spid); - close(fd); - if (failed) { - LOG_E("Could not read SPID (%d)", errno); - return MC_DRV_ERR_TRUSTLET_NOT_FOUND; + if (fd == -1) { + // This can be ok for System TAs + //LOG_ERRNO("open"); + //LOG_E("Cannot open %s", taspidFilePath.c_str()); + //return NULL; + } else { + if (read(fd, &spid, sizeof(mcSpid_t))!=sizeof(mcSpid_t)) { + close(fd); + return NULL; } + close(fd); } } - LOG_D("Returning %s", path.c_str()); - return MC_DRV_OK; + return mcRegistryFileGetServiceBlob(tlBinFilePath.c_str(), spid); +} + +//------------------------------------------------------------------------------ +regObject_t *mcRegistryGetDriverBlob(const char *filename) +{ + regObject_t *regobj = mcRegistryFileGetServiceBlob(filename, 0); + + if (regobj == NULL) { + LOG_E("mcRegistryGetDriverBlob() failed"); + return NULL; + } + + // Get service type. + mclfHeaderV2_t *pHeader = (mclfHeaderV2_t *)regobj->value; + + // If file is not a driver we are not interested + if (pHeader->serviceType != SERVICE_TYPE_DRIVER) { + LOG_E("mcRegistryGetDriverBlob() failed: Unsupported service type %u", pHeader->serviceType); + pHeader = NULL; + free(regobj); + regobj = NULL; + } + + return regobj; } + +/** @} */ diff --git a/mobicore/Daemon/src/PrivateRegistry.h b/mobicore/daemon/Registry/PrivateRegistry.h similarity index 74% rename from mobicore/Daemon/src/PrivateRegistry.h rename to mobicore/daemon/Registry/PrivateRegistry.h index 3232d16..9404939 100644 --- a/mobicore/Daemon/src/PrivateRegistry.h +++ b/mobicore/daemon/Registry/PrivateRegistry.h @@ -1,5 +1,14 @@ +/** + * @addtogroup MCD_MCDIMPL_DAEMON_REG + * @{ + * G&D MobiCore Registry Private implementation + * + * @file + * Mobicore Driver Registry. + */ + /* - * Copyright (c) 2013-2015 TRUSTONIC LIMITED + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,26 +40,30 @@ #ifndef MOBICORE_REGISTRY_H_ #define MOBICORE_REGISTRY_H_ -#include -#include - #include "MobiCoreDriverApi.h" #include "mcContainer.h" -#include "MobiCoreDriverCmd.h" #ifdef __cplusplus extern "C" { #endif -//----------------------------------------------------------------- - void setSearchPaths(const std::vector& paths); + /** + * Registry object. + */ + typedef struct { + uint32_t len; + uint32_t tlStartOffset; + uint8_t value[]; + } regObject_t; + +//----------------------------------------------------------------- /** Stores an authentication token in registry. * @param so Authentication token secure object. * @param size Authentication token secure object size. * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryStoreAuthToken(const void *so, size_t size); + mcResult_t mcRegistryStoreAuthToken(void *so, uint32_t size); /** Reads an authentication token from registry. * @param[out] so Authentication token secure object. @@ -58,12 +71,6 @@ extern "C" { */ mcResult_t mcRegistryReadAuthToken(mcSoAuthTokenCont_t *so); - /** Reads an authentication token backup from registry. - * @param[out] so Authentication token secure object. - * @return MC_DRV_OK if successful, otherwise error code. - */ - mcResult_t mcRegistryReadAuthTokenBackup(mcSoAuthTokenCont_t *so); - /** Deletes the authentication token secure object from the registry. * @return MC_DRV_OK if successful, otherwise error code. */ @@ -74,7 +81,7 @@ extern "C" { * @param size Root container secure object size. * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryStoreRoot(const void *so, size_t size); + mcResult_t mcRegistryStoreRoot(void *so, uint32_t size); /** Reads a root container secure object from the registry. * @param[out] so Root container secure object. @@ -89,7 +96,7 @@ extern "C" { * @param size Service provider container secure object size. * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryStoreSp(mcSpid_t spid, const void *so, size_t size); + mcResult_t mcRegistryStoreSp(mcSpid_t spid, void *so, uint32_t size); /** Reads a service provider container secure object from the registry. * @param spid Service provider ID. @@ -112,7 +119,7 @@ extern "C" { * @param size Trustlet container secure object size * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, const void *so, size_t size); + mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, const mcSpid_t spid, void *so, uint32_t size); /** Reads a trustlet container secure object from the registry. * @param uuid Trustlet UUID. @@ -130,23 +137,12 @@ extern "C" { */ mcResult_t mcRegistryCleanupTrustlet(const mcUuid_t *uuid, const mcSpid_t spid); - /** - * mcRegistryCleanupGPTAStorage() - * - * Removes all associated data of the target UUID. This function is called - * by FSD when cleaning up after a TA has been uninstalled. - * - * @param [in] uuid the UUID of the target TA - * @retval MC_DRV_OK if successful, otherwise and error code from mcResult_t - */ - mcResult_t mcRegistryCleanupGPTAStorage(const mcUuid_t *uuid); - /** Stores a data container secure object in the registry. * @param so Data container secure object. * @param size Data container secure object size * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryStoreData(const void *so, size_t size); + mcResult_t mcRegistryStoreData(void *so, uint32_t size); /** Reads a data container secure object from the registry. * @param context (service provider = 0; trustlet = 1). @@ -156,7 +152,12 @@ extern "C" { * @param maxLen Maximum size (in bytes) of the destination buffer (so). * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryReadData(uint32_t context, const mcCid_t *cid, mcPid_t pid, mcSoDataCont_t *so, uint32_t maxLen); + mcResult_t mcRegistryReadData( + uint32_t context, + const mcCid_t *cid, + mcPid_t pid, + mcSoDataCont_t *so, + uint32_t maxLen); /** Deletes the root container and all of its associated service provider * containers. @@ -164,14 +165,39 @@ extern "C" { */ mcResult_t mcRegistryCleanupRoot(void); + /** Returns a registry object for a given service from memory + * @param spid Service provider ID(ignored for System TLs) + * @param trustlet buffer with trustlet binary + * @param tlSize buffer size + * @return Registry object. + * @note It is the responsibility of the caller to free the registry object + * allocated by this function. + */ + regObject_t *mcRegistryMemGetServiceBlob(mcSpid_t spid, void *trustlet, uint32_t tlSize); + /** Returns a registry object for a given service. * @param uuid service UUID - * @param isGpUuid UUID is for a GP trustlet - * @param[out] spid SPID for secure object. - * @param[out] path The trustlet file path. - * @return MC_DRV_OK if successful, otherwise error code. + * @return Registry object. + * @note It is the responsibility of the caller to free the registry object + * allocated by this function. + */ + regObject_t *mcRegistryGetServiceBlob(const mcUuid_t *uuid, bool isGpUuid); + + /** Returns a registry object for a given service. + * @param uuid service GP UUID as mc uuid + * @return Registry object. + * @note It is the responsibility of the caller to free the registry object + * allocated by this function. + */ + regObject_t *mcRegistryGetServiceBlobGP(const mcUuid_t *uuid); + + /** Returns a registry object for a given service. + * @param driverFilename driver filename + * @return Registry object. + * @note It is the responsibility of the caller to free the registry object + * allocated by this function. */ - mcResult_t mcRegistryGetTrustletInfo(const mcUuid_t *uuid, bool isGpUuid, mcSpid_t *spid, std::string& path); + regObject_t *mcRegistryGetDriverBlob(const char *filename); /** Stores a Trustlet Application blob in the registry. * @param spid SPID of the trustlet container. @@ -179,7 +205,7 @@ extern "C" { * @param size Trustlet Application blob size. * @return MC_DRV_OK if successful, otherwise error code. */ - mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, const void *blob, size_t size); + mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, void *blob, uint32_t size); #ifdef __cplusplus } @@ -187,3 +213,4 @@ extern "C" { #endif // MOBICORE_REGISTRY_H_ +/** @} */ diff --git a/mobicore/Daemon/include/MobiCoreRegistry.h b/mobicore/daemon/Registry/Public/MobiCoreRegistry.h similarity index 94% rename from mobicore/Daemon/include/MobiCoreRegistry.h rename to mobicore/daemon/Registry/Public/MobiCoreRegistry.h index dfbb1c3..c629b14 100644 --- a/mobicore/Daemon/include/MobiCoreRegistry.h +++ b/mobicore/daemon/Registry/Public/MobiCoreRegistry.h @@ -1,5 +1,14 @@ +/** + * @addtogroup MCD_MCDIMPL_DAEMON_REG + * @{ + * G&D MobiCore Registry + * + * @file + * Mobicore Driver Registry. + */ + /* - * Copyright (c) 2013-2014 TRUSTONIC LIMITED + * Copyright (c) 2013 TRUSTONIC LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -118,16 +127,6 @@ extern "C" { */ mcResult_t mcRegistryCleanupTrustlet(const mcUuid_t *uuid, const mcSpid_t spid); - /** - * mcRegistryCleanupTA() - * - * Removes all associated data of a TA (when uninstalled) - * - * @param [in] uuid the UUID to clean up all files belonging too - * @retrurn MC_DRV_OK is successful, othwise an error code from mcResult_t - */ - mcResult_t mcRegistryCleanupTA(const mcUuid_t *uuid); - /** Deletes the root container and all of its associated service provider * containers. * @return MC_DRV_OK if successful, otherwise error code. @@ -148,3 +147,4 @@ extern "C" { #endif // MOBICORE_REGISTRY_H_ +/** @} */ diff --git a/mobicore/daemon/Registry/Registry.cpp b/mobicore/daemon/Registry/Registry.cpp new file mode 100644 index 0000000..bc7ab21 --- /dev/null +++ b/mobicore/daemon/Registry/Registry.cpp @@ -0,0 +1,398 @@ +/** Mobicore Driver Registry Interface + * + * Implements the MobiCore registry interface for the ROOT-PA + * + * @file + * @ingroup MCD_MCDIMPL_DAEMON_REG + */ + +/* + * Copyright (c) 2013 TRUSTONIC LIMITED + * All rights reserved. + * + * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER OR + * CONTRIBUTORS 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "mcLoadFormat.h" +#include "mcSpid.h" +#include "mcVersionHelper.h" + +#include "log.h" + +#include "MobiCoreRegistry.h" +#include "MobiCoreDriverCmd.h" + +#include "Connection.h" + +#define DAEMON_TIMEOUT 30000 + +using namespace std; + + +static mcResult_t writeBlobData(void *buff, uint32_t len) +{ + Connection con; +mcDrvResponseHeader_t rsp = { .responseId = + MC_DRV_ERR_INVALID_PARAMETER + }; + if (!con.connect(SOCK_PATH)) { + LOG_E("Failed to connect to daemon!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + if (con.writeData(buff, len) <= 0) { + LOG_E("Failed to send daemon to data!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + if (con.readData(&rsp, sizeof(rsp), DAEMON_TIMEOUT) <= 0) { + LOG_E("Failed to get answer from daemon!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + return rsp.responseId; +} + +static mcResult_t readBlobData(void *buff, uint32_t len, void *rbuff, uint32_t *rlen) +{ + Connection con; + int32_t size; +mcDrvResponseHeader_t rsp = { .responseId = + MC_DRV_ERR_INVALID_PARAMETER + }; + if (*rlen == 0) { + LOG_E("Invalid buffer length!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + if (!con.connect(SOCK_PATH)) { + LOG_E("Failed to connect to daemon!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + if (con.writeData(buff, len) <= 0) { + LOG_E("Failed to send daemon to data!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + // First read the response + if (con.readData(&rsp, sizeof(rsp), DAEMON_TIMEOUT) <= 0) { + LOG_E("Failed to get answer from daemon!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + + //Then read the actual data + size = con.readData(rbuff, *rlen, DAEMON_TIMEOUT); + if (size <= 0) { + LOG_E("Failed to get answer from daemon!"); + return MC_DRV_ERR_DAEMON_SOCKET; + } + // Return also the read buf size + *rlen = (uint32_t)size; + + return rsp.responseId; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryStoreAuthToken(void *so, uint32_t size) +{ + typedef struct { + uint32_t commandId; + uint32_t soSize; + uint8_t so; + } storeCmd; + + mcResult_t ret; + storeCmd *cmd = (storeCmd *)malloc(sizeof(storeCmd) + size - 1); + if (cmd == NULL) { + LOG_E("Allocation failure"); + return MC_DRV_ERR_NO_FREE_MEMORY; + } + + cmd->commandId = MC_DRV_REG_STORE_AUTH_TOKEN; + cmd->soSize = size; + memcpy(&cmd->so, so, size); + ret = writeBlobData(cmd, sizeof(storeCmd) + size - 1); + free(cmd); + return ret; +} + + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryReadAuthToken(void *so, uint32_t *size) +{ +mcDrvCommandHeader_t cmd = { .commandId = + MC_DRV_REG_READ_AUTH_TOKEN + }; + uint32_t rsize; + mcResult_t ret; + // we expect to max read what the user has allocated + rsize = *size; + ret = readBlobData(&cmd, sizeof(cmd), so, &rsize); + // return the actual read size + *size = rsize; + return ret; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryDeleteAuthToken(void) +{ +mcDrvCommandHeader_t cmd = { .commandId = + MC_DRV_REG_DELETE_AUTH_TOKEN + }; + return writeBlobData(&cmd, sizeof(cmd)); +} + + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryStoreRoot(void *so, uint32_t size) +{ + typedef struct { + uint32_t commandId; + uint32_t soSize; + uint8_t so; + } storeCmd; + mcResult_t ret; + storeCmd *cmd = (storeCmd *)malloc(sizeof(storeCmd) + size - 1); + if (cmd == NULL) { + LOG_E("Allocation failure"); + return MC_DRV_ERR_NO_FREE_MEMORY; + } + + cmd->commandId = MC_DRV_REG_WRITE_ROOT_CONT; + cmd->soSize = size; + memcpy(&cmd->so, so, size); + ret = writeBlobData(cmd, sizeof(storeCmd) + size - 1); + free(cmd); + return ret; +} + + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryReadRoot(void *so, uint32_t *size) +{ +mcDrvCommandHeader_t cmd = { .commandId = + MC_DRV_REG_READ_ROOT_CONT + }; + uint32_t rsize; + mcResult_t ret; + + rsize = *size; + ret = readBlobData(&cmd, sizeof(cmd), so, &rsize); + *size = rsize; + return ret; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryCleanupRoot(void) +{ +mcDrvCommandHeader_t cmd = { .commandId = + MC_DRV_REG_DELETE_ROOT_CONT + }; + return writeBlobData(&cmd, sizeof(cmd)); +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryStoreSp(mcSpid_t spid, void *so, uint32_t size) +{ + typedef struct { + uint32_t commandId; + uint32_t soSize; + mcSpid_t spid; + uint8_t so; + } storeCmd; + + mcResult_t ret; + storeCmd *cmd = (storeCmd *)malloc(sizeof(storeCmd) + size - 1); + if (cmd == NULL) { + LOG_E("Allocation failure"); + return MC_DRV_ERR_NO_FREE_MEMORY; + } + + cmd->commandId = MC_DRV_REG_WRITE_SP_CONT; + cmd->soSize = size; + cmd->spid = spid; + memcpy(&cmd->so, so, size); + + ret = writeBlobData(cmd, sizeof(storeCmd) + size - 1); + free(cmd); + return ret; +} + + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryReadSp(mcSpid_t spid, void *so, uint32_t *size) +{ + struct { + uint32_t commandId; + mcSpid_t spid; + } cmd; + uint32_t rsize; + mcResult_t ret; + cmd.commandId = MC_DRV_REG_READ_SP_CONT; + cmd.spid = spid; + + rsize = *size; + ret = readBlobData(&cmd, sizeof(cmd), so, &rsize); + *size = rsize; + + return ret; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryCleanupSp(mcSpid_t spid) +{ + struct { + uint32_t commandId; + mcSpid_t spid; + } cmd; + + cmd.commandId = MC_DRV_REG_DELETE_SP_CONT; + cmd.spid = spid; + + return writeBlobData(&cmd, sizeof(cmd)); +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryStoreTrustletCon(const mcUuid_t *uuid, mcSpid_t spid, void *so, uint32_t size) +{ + typedef struct { + uint32_t commandId; + uint32_t soSize; + mcUuid_t uuid; + mcSpid_t spid; + uint8_t so; + } storeCmd; + + mcResult_t ret; + storeCmd *cmd = (storeCmd *)malloc(sizeof(storeCmd) + size - 1); + if (cmd == NULL) { + LOG_E("Allocation failure"); + return MC_DRV_ERR_NO_FREE_MEMORY; + } + + cmd->commandId = MC_DRV_REG_WRITE_TL_CONT; + cmd->soSize = size; + cmd->spid = spid; + memcpy(&cmd->uuid, uuid, sizeof(mcUuid_t)); + memcpy(&cmd->so, so, size); + + ret = writeBlobData(cmd, sizeof(storeCmd) + size - 1); + free(cmd); + return ret; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryStoreTABlob(mcSpid_t spid, void *blob, uint32_t size) +{ + typedef struct { + uint32_t commandId; + uint32_t blobSize; + mcSpid_t spid; + uint8_t blob[]; + } storeCmd; + + mcResult_t ret; + storeCmd *cmd = (storeCmd *)malloc(sizeof(storeCmd) + size); + if (cmd == NULL) { + LOG_E("Allocation failure"); + return MC_DRV_ERR_NO_FREE_MEMORY; + } + + cmd->commandId = MC_DRV_REG_STORE_TA_BLOB; + cmd->blobSize = size; + cmd->spid = spid; + memcpy(&cmd->blob, blob, size); + + ret = writeBlobData(cmd, sizeof(storeCmd) + size); + free(cmd); + return ret; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryReadTrustletCon(const mcUuid_t *uuid, mcSpid_t spid, void *so, uint32_t *size) +{ + struct { + uint32_t commandId; + mcUuid_t uuid; + mcSpid_t spid; + } cmd; + mcResult_t ret; + uint32_t rsize; + cmd.commandId = MC_DRV_REG_READ_TL_CONT; + cmd.spid = spid; + memcpy(&cmd.uuid, uuid, sizeof(mcUuid_t)); + + rsize = *size; + ret = readBlobData(&cmd, sizeof(cmd), so, &rsize); + *size = rsize; + return ret; +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryCleanupTrustlet(const mcUuid_t *uuid, const mcSpid_t spid) +{ + struct { + uint32_t commandId; + mcUuid_t uuid; + mcSpid_t spid; + } cmd; + + if (uuid == NULL) { + return MC_DRV_ERR_INVALID_PARAMETER; + } + + cmd.commandId = MC_DRV_REG_DELETE_TL_CONT; + cmd.spid = spid; + memcpy(&cmd.uuid, uuid, sizeof(mcUuid_t)); + + return writeBlobData(&cmd, sizeof(cmd)); +} + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryStoreData(void *so __unused, uint32_t size __unused) +{ + return MC_DRV_ERR_INVALID_PARAMETER; +} + + +//------------------------------------------------------------------------------ +mcResult_t mcRegistryReadData(uint32_t context __unused, const mcCid_t *cid __unused, mcPid_t pid __unused, + mcSoDataCont_t *so __unused, uint32_t maxLen __unused) +{ + return MC_DRV_ERR_INVALID_PARAMETER; +} + +/** @} */ diff --git a/mobicore/daemon/build.sh b/mobicore/daemon/build.sh new file mode 100644 index 0000000..55a1593 --- /dev/null +++ b/mobicore/daemon/build.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +source ../../../../setup.sh +if [ $? -ne 0 ]; then + echo "Error: Could not source setup.sh!" + exit 1 +fi + +ROOT_PATH=$(dirname $(readlink -f $BASH_SOURCE)) + +### +### Android NDK path +### +PLATFORM=Generic +MODE=debug + +echo "Building + * + * 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. + */ +#define MOBICORE_COMPONENT_BUILD_TAG "*** t-base-300-Ares-2-Android-V001 ###" diff --git a/mobicore/include/Public/mc_linux.h b/mobicore/include/Public/mc_linux.h new file mode 100644 index 0000000..b9c4934 --- /dev/null +++ b/mobicore/include/Public/mc_linux.h @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2013-2014 TRUSTONIC LIMITED + * All Rights Reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ +/* + * The +#endif + +#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 { + /* 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 */ +}; + +/* + * Data exchange structure of the MC_IO_MAP_WSM and MC_IO_MAP_MCI commands. + * + * Allocate a contiguous memory buffer for a process. + * The physical address can be used as for later calls to mmap. + * The handle can be used to communicate about this buffer to the Daemon. + * For MC_IO_MAP_MCI command, the reused field indicates that MCI was set up + * already. I.e. Daemon was restarted. + */ +struct mc_ioctl_map { + uint32_t len; /* Buffer length */ + uint32_t handle; /* WSM handle */ + uint64_t phys_addr; /* physical address of WSM (or 0) */ + uint32_t rfu; + bool reused; /* if WSM memory was reused, or new allocated */ +}; + +/* + * Data exchange structure of the MC_IO_REG_WSM command. + * + * Allocates a physical MMU table and maps the buffer into this page. + * Returns the physical address of the MMU table. + * The page alignment will be created and the appropriated pSize and pOffsetMMU + * will be modified to the used values. + * + * We assume the 64 bit compatible one to be the default and the + * 32 bit one to be the compat one but we must serve both of them. + */ +struct mc_compat_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 */ + uint64_t table_phys; /* physical address of the MMU table */ +}; + +struct mc_ioctl_reg_wsm { + uint64_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 */ + uint64_t table_phys;/* physical address of the MMU table */ +}; + +/* + * Data exchange structure of the MC_IO_RESOLVE_CONT_WSM ioctl command. + */ +struct mc_ioctl_resolv_cont_wsm { + /* driver handle for buffer */ + uint32_t handle; + /* length memory */ + uint32_t length; + /* base address of memory */ + uint64_t phys; + /* fd to owner of the buffer */ + int32_t fd; +}; + +/* + * Data exchange structure of the MC_IO_RESOLVE_WSM ioctl command. + */ +struct mc_ioctl_resolv_wsm { + /* driver handle for buffer */ + uint32_t handle; + /* fd to owner of the buffer */ + int32_t fd; + /* base address of memory */ + uint64_t phys; +}; + + +/* + * 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 being of + * type long address + */ +#define MC_IO_FREE _IO(MC_IOC_MAGIC, 5) +/* + * Creates a MMU Table of the given base address and the size of the + * data. + * Parameter: mc_ioctl_reg_wsm + * + * Since the end ID is also based on the size of the structure it is + * safe to use the same ID(6) for both + */ +#define MC_IO_REG_WSM _IOWR(MC_IOC_MAGIC, 6, struct mc_ioctl_reg_wsm) +#define MC_COMPAT_REG_WSM _IOWR(MC_IOC_MAGIC, 6, \ + struct mc_compat_ioctl_reg_wsm) + +#define MC_IO_UNREG_WSM _IO(MC_IOC_MAGIC, 7) +#define MC_IO_LOCK_WSM _IO(MC_IOC_MAGIC, 8) +#define MC_IO_UNLOCK_WSM _IO(MC_IOC_MAGIC, 9) + +/* + * Allocate contiguous memory for a process for later mapping with mmap. + * MC_IO_MAP_WSM usual operation, pages are registered in + * device structure and freed later. + * MC_IO_MAP_MCI get Instance of MCI, allocates or mmaps + * the MCI to daemon + */ +#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) + +/* + * Clean orphaned WSM buffers. Only available to the daemon and should + * only be carried out if the TLC crashes or otherwise calls exit() in + * an unexpected manner. + * The clean is needed together with the lock/unlock mechanism so the daemon + * has clear control of the mapped buffers so it can close a Trustlet before + * release all the WSM buffers, otherwise the Trustlet would be able to write + * to possibly kernel memory areas + */ +#define MC_IO_CLEAN_WSM _IO(MC_IOC_MAGIC, 14) + +/* + * Get MMU phys address of a buffer handle allocated to the user. + * Only available to the daemon. + */ +#define MC_IO_RESOLVE_WSM _IOWR(MC_IOC_MAGIC, 15, \ + struct mc_ioctl_resolv_wsm) + +/* + * Get the phys address & length of a allocated contiguous buffer. + * Only available to the daemon */ +#define MC_IO_RESOLVE_CONT_WSM _IOWR(MC_IOC_MAGIC, 16, \ + struct mc_ioctl_resolv_cont_wsm) + +/* + * Setup the mem traces when called. + * Only available to the daemon */ +#define MC_IO_LOG_SETUP _IO(MC_IOC_MAGIC, 17) + +#endif /* _MC_LINUX_H_ */ diff --git a/mobicore/include/Public/version.h b/mobicore/include/Public/version.h new file mode 100644 index 0000000..591ca3d --- /dev/null +++ b/mobicore/include/Public/version.h @@ -0,0 +1,36 @@ +/* + * <-- Copyright Giesecke & Devrient GmbH 2010-2012 --> + * <-- Copyright Trustonic Limited 2013 --> + * + * 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_DRV_VERSION_H_ +#define _MC_DRV_VERSION_H_ + +#define MCDRVMODULEAPI_VERSION_MAJOR 1 +#define MCDRVMODULEAPI_VERSION_MINOR 1 + +#endif /* _MC_DRV_VERSION_H_ */ diff --git a/mobicore/provlib/Android.mk b/mobicore/provlib/Android.mk new file mode 100644 index 0000000..db3da67 --- /dev/null +++ b/mobicore/provlib/Android.mk @@ -0,0 +1,16 @@ +# ============================================================================= +# +# Makefile pointing to all makefiles within the project. +# +# ============================================================================= + +PROJECT_PATH := $(call my-dir) + +# adding the root folder to the search path appears to make absolute paths +# work for import-module - lets see how long this works and what surprises +# future developers get from this. +$(call import-add-path,/) +$(call import-module,$(COMP_PATH_MobiCoreDriverLib)) + +# Include the Scripts +include $(PROJECT_PATH)/jni/Android.mk diff --git a/mobicore/provlib/Application.mk b/mobicore/provlib/Application.mk new file mode 100644 index 0000000..fde1054 --- /dev/null +++ b/mobicore/provlib/Application.mk @@ -0,0 +1,23 @@ +# ============================================================================= +# +# 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_TlCm)/Public \ + $(COMP_PATH_TlCm)/Public/TlCm \ + $(COMP_PATH_TlCm)/Public/TlCm/2.0 \ + $(COMP_PATH_MobiCoreDriverLib)/Public +MC_DEBUG := _DEBUG +SYSTEM_LIB_DIR=/system/lib +GDM_PROVLIB_SHARED_LIBS=MobiCoreDriver diff --git a/mobicore/provlib/buildTag.h b/mobicore/provlib/buildTag.h new file mode 100644 index 0000000..928fb31 --- /dev/null +++ b/mobicore/provlib/buildTag.h @@ -0,0 +1,28 @@ +/* + * <-- Copyright Trustonic Limited 2013 --> + * + * 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. + */ +#define MOBICORE_COMPONENT_BUILD_TAG "*** t-base-300-Ares-2-Android-V001 ###" diff --git a/mobicore/provlib/inc_private/gdmcdevicebinding.h b/mobicore/provlib/inc_private/gdmcdevicebinding.h new file mode 100644 index 0000000..3b979b8 --- /dev/null +++ b/mobicore/provlib/inc_private/gdmcdevicebinding.h @@ -0,0 +1,101 @@ +#ifndef _INC_GDMCDEVICEBINDING_H +#define _INC_GDMCDEVICEBINDING_H + +#include +#include +#ifdef ARM +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _KSoCAuthSNTS KSoCAuthSNTS; + +struct _KSoCAuthSNTS +{ + mcSymmetricKey_t kSoCAuth; + _u64 serialNumber; + _u64 timeStamp; +}; + +#ifdef __cplusplus +} +#endif + +#ifdef ARM + +extern "C" void GDPROVAPI GDMCLog ( int prio, const char *tag, const char *fmt, ... ); + +#ifdef _DEBUG +extern "C" void GDMCHexDump ( const unsigned char *data, int size ); +#endif + +#define LOG_TAG "GDMCProvLib" + +#ifdef _DEBUG +#define LOG_d(...) do { GDMCLog(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__); } while(0) +#else +#define LOG_d(...) do { } while(0) +#endif +#define LOG_i(...) do { GDMCLog(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__); } while(0) +#define LOG_w(...) do { GDMCLog(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__); } while(0) +#define LOG_e(...) do { GDMCLog(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__); } while(0) + +#else + +#define LOG_d(...) do { } while(0) +#define LOG_i(...) do { } while(0) +#define LOG_w(...) do { } while(0) +#define LOG_e(...) do { } while(0) + +#endif // ARM + +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 new file mode 100644 index 0000000..0369f62 --- /dev/null +++ b/mobicore/provlib/inc_private/gdmcinstance.h @@ -0,0 +1,28 @@ +#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 new file mode 100644 index 0000000..bd2686d --- /dev/null +++ b/mobicore/provlib/inc_private/gdmcprovprotocol.h @@ -0,0 +1,127 @@ +#ifndef _INC_GDMCPROVPROTOCOL_H_ +#define _INC_GDMCPROVPROTOCOL_H_ + +#include +#include + +#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 new file mode 100644 index 0000000..1806f2b --- /dev/null +++ b/mobicore/provlib/inc_private/mobicore.h @@ -0,0 +1,174 @@ +/// @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 +#include +#include +#endif + +#include +#include +#include +#include +#include +#include + +#ifdef LINUX +#include +#endif + +#if defined(WIN32) && defined(_DEBUG) // enable memory leak detection +#define _CRTDBG_MAP_ALLOC +#define _CRTDBG_MAP_ALLOC_NEW +#include +#include +#define MYDEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__) +#define new MYDEBUG_NEW +#endif + +#ifndef _NO_OPENSSL_INCLUDES + +// OpenSSL stuff... + +#include +#include +#include +#include +#include +#include +#include + +#endif + +#ifdef WIN32 + +#define WIN32_LEAN_AND_MEAN +#include + +#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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef LINUX +#include +#else +#include +#endif + +#endif + +#include +#include + +// MobiCore stuff... + +#ifdef WIN32 +#undef UUID +#undef uuid_t +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include +#include + +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 + +#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 new file mode 100644 index 0000000..71196ca --- /dev/null +++ b/mobicore/provlib/inc_public/gdmcprovlib.h @@ -0,0 +1,424 @@ +/// +/// @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 + +#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/jni/Android.mk b/mobicore/provlib/jni/Android.mk new file mode 100644 index 0000000..07e077b --- /dev/null +++ b/mobicore/provlib/jni/Android.mk @@ -0,0 +1,37 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := libgdmcprov +LOCAL_MODULE_TAGS := debug eng optional + +LOCAL_ADDITIONAL_DEPENDENCIES += $(TARGET_OUT_INTERMEDIATES)/KERNEL_OBJ/usr + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../inc_private \ + $(LOCAL_PATH)/../inc_public \ + $(MC_INCLUDE_DIR) + +LOCAL_SRC_FILES := ../src/gdmcprovlib.cpp \ + ../src/crc32.c \ + ../src/mobicore.c \ + ../src/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_LDFLAGS := -Wl,-rpath-link,$(SYSTEM_LIB_DIR) \ + -L$(SYSTEM_LIB_DIR) -llog + +LOCAL_SHARED_LIBRARIES := $(GDM_PROVLIB_SHARED_LIBS) + +include $(BUILD_SHARED_LIBRARY) diff --git a/mobicore/provlib/src/crc32.c b/mobicore/provlib/src/crc32.c new file mode 100644 index 0000000..37ac0c6 --- /dev/null +++ b/mobicore/provlib/src/crc32.c @@ -0,0 +1,49 @@ +#include +#include + +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 new file mode 100644 index 0000000..e97fefa --- /dev/null +++ b/mobicore/provlib/src/gdmcdevicebinding.cpp @@ -0,0 +1,533 @@ +/// +/// @file gdmcdevicebinding.cpp +/// @author Giesecke & Devrient GmbH, Munich, Germany +/// +/// Implementation of the (internal) device binding +/// + +#include +#include +#include +#include +#include +#include + +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 + +#ifdef _DEBUG +#include +#endif + +////////////////////////////////////////////////////////////////////////////// +// Linux-specific includes +////////////////////////////////////////////////////////////////////////////// + +#elif defined(LINUX) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +////////////////////////////////////////////////////////////////////////////// +// ARM-specific includes +////////////////////////////////////////////////////////////////////////////// + +#else // ARM + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif + +#include +#include +#include + +#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 + +#ifdef ARM + +extern "C" void GDMCLog ( int prio, const char *tag, const char *fmt, ... ) +{ + va_list ap; + + va_start(ap,fmt); +#if defined(WIN32) || defined(LINUX) + { + char buffer[1024]; + FILE *f = fopen("libMcClient.log","at"); + if (likely(NULL!=f)) + { + vsprintf(buffer,fmt,ap); + fprintf(f,"[%i][%s] %s\n",prio,tag,buffer); + fclose(f); + } + } +#else + __android_log_vprint(prio,tag,fmt,ap); +#endif + va_end(ap); +} + +#ifdef _DEBUG +extern "C" void GDMCHexDump ( const unsigned char *data, int size ) +{ + static char szHexLine[80], szHex[12]; + unsigned char x, h, l; + int i,j; + + if (!size) + return; + + while (size>0) + { + memset(szHexLine,0x20,sizeof(szHexLine)); + szHexLine[77] = 0x00; + szHexLine[78] = 0x00; + if (size>8) + szHexLine[34] = '-'; + + snprintf(szHex, 8 + 1, "%08X",(uintptr_t)data); + memcpy(szHexLine,szHex,8); + + i=0;j=0; + while (size>0) + { + x = *(data++); + size--; + h = (x>>4)+0x30; + l = (x&15)+0x30; + if (h>0x39) h+=7; + if (l>0x39) l+=7; + szHexLine[i*3+10+j] = (char)h; + szHexLine[i*3+11+j] = (char)l; + + if ((x<32) || (x>=127)) x = '.'; + + szHexLine[i+61] = (char)x; + + i++; + if (8==i) + j = 2; + if (16==i) + break; + } + + LOG_d("%s",szHexLine); + } +} + +#endif // _DEBUG + +#endif // ARM + +gderror GDMCComposeErrorMessage ( gdmcinst *inst __unused, 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_sizebody_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->statesuid); + + 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->statestate = 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 new file mode 100644 index 0000000..9ac452d --- /dev/null +++ b/mobicore/provlib/src/gdmcprovlib.cpp @@ -0,0 +1,408 @@ +/// +/// @file gdmcprovlib.cpp +/// @author Giesecke & Devrient GmbH, Munich, Germany +/// +/// Implementation of the API functions (Provisioning +/// Library) +/// + +#include +#include +#include +#include + +////////////////////////////////////////////////////////////////////////////// +// MS Windows-specific includes +////////////////////////////////////////////////////////////////////////////// + +#if defined(WIN32) + +#define WIN32_LEAN_AND_MEAN +#include +static HMODULE g_hInstance = NULL; + +////////////////////////////////////////////////////////////////////////////// +// Linux-specific includes +////////////////////////////////////////////////////////////////////////////// + +#elif defined(LINUX) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +////////////////////////////////////////////////////////////////////////////// +// ARM-specific includes +////////////////////////////////////////////////////////////////////////////// + +#else // ARM + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif + +#include +#include +#include + +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 __unused, + gderror errorcode __unused, + char *msgbuf __unused, + _u32 *size __unused ) +{ + LOG_d("++++ ENTERED GDMCProvFormatErrorMessage: NOT IMPLEMENTED."); + return GDERROR_NOT_IMPLEMENTED; +} + +static gderror GDPROVAPI _GDMCProvInitializeLibrary ( void ) +{ + LOG_d("++++ ENTERED GDMCProvInitializeLibrary."); + + if (unlikely( !mccmOpen() )) + { + LOG_e("CMTL open FAILED."); + LOG_d("++++ LEFT GDMCProvInitializeLibrary."); + return GDERROR_MOBICORE_LIBRARY; + } + + LOG_i("CMTL open successful."); + + LOG_d("++++ LEFT GDMCProvInitializeLibrary."); + + 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)(uintptr_t)inst; + + return GDERROR_OK; +} + +static gderror GDPROVAPI _GDMCProvEndProvisioning ( gdhandle provhandle ) +{ + gdmcinst *inst = (gdmcinst*)(uintptr_t)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*)(uintptr_t)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 __unused, + _u32 receipt_size __unused, + _u8 *fmt_receipt __unused, + _u32 *fmt_receipt_size __unused ) +{ + return GDERROR_NOT_IMPLEMENTED; +} + +extern "C" gderror GDPROVAPI GDMCProvGetSUID ( + gdhandle provhandle __unused, + _u8 *suid __unused ) +{ + 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 __unused ) +{ +#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 new file mode 100644 index 0000000..85ab5c4 --- /dev/null +++ b/mobicore/provlib/src/mobicore.c @@ -0,0 +1,294 @@ +#include +#include +#include +#include +#include +#include + +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; + +#ifdef ARM + +extern void GDMCLog ( int prio, const char *tag, const char *fmt, ... ); + +#ifdef _DEBUG +extern void GDMCHexDump ( const unsigned char *data, int size ); +#else +#define GDMCHexDump(...) do { } while(0) +#endif + +#define LOG_TAG "GDMCProvLib" + +#ifdef _DEBUG +#define LOG_d(...) do { GDMCLog(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__); } while(0) +#else +#define LOG_d(...) do { } while(0) +#endif +#define LOG_i(...) do { GDMCLog(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__); } while(0) +#define LOG_w(...) do { GDMCLog(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__); } while(0) +#define LOG_e(...) do { GDMCLog(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__); } while(0) + +#else + +#define LOG_d(...) do { } while(0) +#define LOG_i(...) do { } while(0) +#define LOG_w(...) do { } while(0) +#define LOG_e(...) do { } while(0) + +#endif // ARM + +static void dumpErrorInformation ( const char *function, mcResult_t result ) +{ + int32_t lastErr = -1; + + LOG_e("%s returned error %u (0x%08X)",function,result,result); + + if (MC_DRV_OK==mcGetSessionErrorCode(&g_mccm.sess,&lastErr)) + { + LOG_e("mcGetSessionErrorCode for %s returned %i (0x%08X)",function,lastErr,lastErr); + } + else + { + LOG_i("No additional error code for %s from mcGetSessionErrorCode available.",function); + } +} + +// 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; + + LOG_d("++++ ENTERED mccmOpen."); + + memset(&g_mccm,0,sizeof(MCCM)); + + result = mcOpenDevice(MC_DEVICE_ID_DEFAULT); + + if (MC_DRV_OK != result) + { + LOG_e("mcOpenDevice returned error %u",result); + LOG_d("++++ LEFT mccmOpen."); + return false; + } + + result = mcMallocWsm(MC_DEVICE_ID_DEFAULT, 0, sizeof(cmp_t), (uint8_t **)&g_mccm.cmp, 0); + if (MC_DRV_OK != result) + { + LOG_e("mcMallocWsm returned error %u",result); + mcCloseDevice(MC_DEVICE_ID_DEFAULT); + LOG_d("++++ LEFT mccmOpen."); + 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) + { + LOG_e("mcOpenSession returned error %u",result); + mcFreeWsm(MC_DEVICE_ID_DEFAULT,(uint8_t*)g_mccm.cmp); + mcCloseDevice(MC_DEVICE_ID_DEFAULT); + LOG_d("++++ LEFT mccmOpen."); + return false; + } + + LOG_d("++++ LEFT mccmOpen."); + return true; +} + +void mccmClose ( void ) +{ + mcResult_t result; + LOG_d("++++ ENTERED mccmClose."); + + result = mcCloseSession(&g_mccm.sess); + if (MC_DRV_OK != result) + { + LOG_e("mcCloseSession returned error %u",result); + } + + 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)); + + LOG_d("++++ LEFT mccmClose."); +} + +static bool mccmTransmit ( int32_t timeout ) +{ + LOG_d("++++ ENTERED mccmTransmit."); + + // Send CMP message to content management trustlet. + + g_mccm.lasterror = mcNotify(&g_mccm.sess); + + if (unlikely( MC_DRV_OK!=g_mccm.lasterror )) + { + dumpErrorInformation("mcNotify",g_mccm.lasterror); + LOG_d("++++ LEFT mccmTransmit."); + return false; + } + + // Wait for trustlet response. + + g_mccm.lasterror = mcWaitNotification(&g_mccm.sess, timeout); + + if (unlikely( MC_DRV_OK!=g_mccm.lasterror )) + { + dumpErrorInformation("mcWaitNotification",g_mccm.lasterror); + LOG_d("++++ LEFT mccmTransmit."); + return false; + } + + LOG_d("++++ LEFT mccmTransmit."); + + return true; +} + +static bool mccmGetSuid ( mcSuid_t *suid ) +{ + LOG_d("++++ ENTERED mccmGetSuid."); + + 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) )) + { + LOG_d("++++ LEFT mccmGetSuid."); + return false; + } + + if (unlikely( (MC_CMP_CMD_GET_SUID|RSP_ID_MASK)!=g_mccm.cmp->msg.cmpRspGetSuid.rspHeader.responseId )) + { + LOG_e("Bad response ID of GET_SUID response."); + g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; + LOG_d("++++ LEFT mccmGetSuid."); + return false; + } + + g_mccm.lastcmperr = g_mccm.cmp->msg.cmpRspGetSuid.rspHeader.returnCode; + + if (unlikely( SUCCESSFUL!=g_mccm.lastcmperr )) + { + LOG_e("CMP error occurred, code: %u (0x%08X).",g_mccm.lastcmperr,g_mccm.lastcmperr); + g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; + LOG_d("++++ LEFT mccmGetSuid."); + return false; + } + + memcpy(suid,&g_mccm.cmp->msg.cmpRspGetSuid.suid,sizeof(mcSuid_t)); + +#ifdef _DEBUG + LOG_d("SUID returned is:"); + GDMCHexDump((const unsigned char*)suid,sizeof(*suid)); +#endif + + LOG_d("++++ LEFT mccmGetSuid."); + return true; +} + +static bool mccmGenerateAuthToken ( + const cmpCmdGenAuthToken_t *cmd, + cmpRspGenAuthToken_t *rsp ) +{ + LOG_d("++++ ENTERED mccmGenerateAuthToken."); + +#ifdef _DEBUG + LOG_d("CMP request is (hexdump):"); + GDMCHexDump((const unsigned char*)cmd,sizeof(*cmd)); +#endif + + 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) )) + { + LOG_d("++++ LEFT mccmGenerateAuthToken."); + return false; + } + + if (unlikely( (cmd->cmd.sdata.cmdHeader.commandId|RSP_ID_MASK)!=g_mccm.cmp->msg.cmpRspGenAuthToken.rsp.rspHeader.responseId )) + { + LOG_e("Bad response ID of GENERATE_AUTH_TOKEN response."); + g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; + LOG_d("++++ LEFT mccmGenerateAuthToken."); + return false; + } + + g_mccm.lastcmperr = g_mccm.cmp->msg.cmpRspGenAuthToken.rsp.rspHeader.returnCode; + + if (unlikely( SUCCESSFUL!=g_mccm.lastcmperr )) + { + LOG_e("CMP error occurred, code: %u (0x%08X).",g_mccm.lastcmperr,g_mccm.lastcmperr); + g_mccm.lasterror = MC_DRV_ERR_UNKNOWN; + LOG_d("++++ LEFT mccmGenerateAuthToken."); + return false; + } + + memcpy(rsp,g_mccm.cmp,sizeof(*rsp)); + +#ifdef _DEBUG + LOG_d("CMP response is (hexdump):"); + GDMCHexDump((const unsigned char*)rsp,sizeof(*rsp)); +#endif + + LOG_d("++++ LEFT mccmGenerateAuthToken."); + 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; +} diff --git a/mobicore/rootpa/Android.mk b/mobicore/rootpa/Android.mk deleted file mode 100644 index 6331641..0000000 --- a/mobicore/rootpa/Android.mk +++ /dev/null @@ -1,7 +0,0 @@ -LOCAL_ROOT_PATH := $(call my-dir) - -MOBICORE_DIR_INC := $(LOCAL_ROOT_PATH)/../curl/include -include $(LOCAL_ROOT_PATH)/Code/Common/Android.mk -include $(LOCAL_ROOT_PATH)/Code/Android/app/jni/Android.mk -include $(LOCAL_ROOT_PATH)/Code/Android/lib/Android.mk -include $(LOCAL_ROOT_PATH)/Code/Android/app/Android.mk \ No newline at end of file diff --git a/mobicore/rootpa/Code/Android/app/Android.mk b/mobicore/rootpa/Code/Android/app/Android.mk index 73b7525..b98b75f 100644 --- a/mobicore/rootpa/Code/Android/app/Android.mk +++ b/mobicore/rootpa/Code/Android/app/Android.mk @@ -11,15 +11,11 @@ LOCAL_JNI_SHARED_LIBRARIES := libcommonpawrapper LOCAL_PRIVATE_PLATFORM_APIS := true LOCAL_PACKAGE_NAME := RootPA -LOCAL_MODULE_TAGS := debug eng optional +LOCAL_MODULE_TAGS := eng optional LOCAL_CERTIFICATE := platform LOCAL_PROGUARD_FLAGS := -include $(LOCAL_PATH)/proguard-project.txt -APP_PIE := true -LOCAL_32_BIT_ONLY := true -LOCAL_DEX_PREOPT := false - include $(BUILD_PACKAGE) include $(CLEAR_VARS) diff --git a/mobicore/rootpa/Code/Android/app/AndroidManifest.xml b/mobicore/rootpa/Code/Android/app/AndroidManifest.xml index 02cf95e..7ffb326 100644 --- a/mobicore/rootpa/Code/Android/app/AndroidManifest.xml +++ b/mobicore/rootpa/Code/Android/app/AndroidManifest.xml @@ -6,12 +6,12 @@ android:versionName="@string/name" > + android:targetSdkVersion="17" /> - - + + + - - - - - - - - - - - - - @@ -62,50 +48,12 @@ application and should be checked into Version Control Systems. --> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 30x0.3 = 9 seconds rootpaerror_t httpCommunicate(const char* const inputP, const char** linkP, const char** relP, const char** commandP, httpMethod_t method); -#ifdef WIN32 - - char* strcasestr(char const *s, char const *find) - { - char* pos; - char* ret; - char* ls=_strdup(s); - char* lfind=_strdup(find); - - ls=_strlwr(ls); - lfind=_strlwr(lfind); - pos = strstr(ls, lfind); - ret = pos == NULL ? NULL : (char *)(s + (pos-ls)); - free(ls); - free(lfind); - return ret; - } - - -#endif - -#ifdef TIZEN -#include -#include -#include -/* - * Find the first occurrence of find in s, ignore case. - */ -char * -strcasestr(s, find) - const char *s, *find; -{ - char c, sc; - size_t len; - - if ((c = *find++) != 0) { - c = tolower((unsigned char)c); - len = strlen(find); - do { - do { - if ((sc = *s++) == 0) - return (NULL); - } while ((char)tolower((unsigned char)sc) != c); - } while (strncasecmp(s, find, len) != 0); - s--; - } - return ((char *)s); -} - -/* - * Appends src to string dst of size siz (unlike strncat, siz is the - * full size of dst, not space left). At most siz-1 characters - * will be copied. Always NUL terminates (unless siz <= strlen(dst)). - * Returns strlen(src) + MIN(siz, strlen(initial dst)). - * If retval >= siz, truncation occurred. - */ -size_t -strlcat(char *dst, const char *src, size_t siz) -{ - register char *d = dst; - register const char *s = src; - register size_t n = siz; - size_t dlen; - - /* Find the end of dst and adjust bytes left but don't go past end */ - while (n-- != 0 && *d != '\0') - d++; - dlen = d - dst; - n = siz - dlen; - - if (n == 0) - return(dlen + strlen(s)); - while (*s != '\0') { - if (n != 1) { - *d++ = *s; - n--; - } - s++; - } - *d = '\0'; - - return(dlen + (s - src)); /* count does not include NUL */ -} - -/* - * Copy src to string dst of size siz. At most siz-1 characters - * will be copied. Always NUL terminates (unless siz == 0). - * Returns strlen(src); if retval >= siz, truncation occurred. - */ -size_t -strlcpy(char *dst, const char *src, size_t siz) -{ - register char *d = dst; - register const char *s = src; - register size_t n = siz; - - /* Copy as many bytes as will fit */ - if (n != 0 && --n != 0) { - do { - if ((*d++ = *s++) == 0) - break; - } while (--n != 0); - } - - /* Not enough room in dst, add NUL and traverse rest of src */ - if (n == 0) { - if (siz != 0) - *d = '\0'; /* NUL-terminate dst */ - while (*s++) - ; - } - - return(s - src - 1); /* count does not include NUL */ -} -#endif - rootpaerror_t httpPostAndReceiveCommand(const char* const inputP, const char** linkP, const char** relP, const char** commandP) { LOGD("httpPostAndReceiveCommand %ld", (long int) inputP); @@ -280,7 +157,8 @@ static size_t writeMemoryCallback(void *contents, size_t size, size_t nmemb, voi { size_t realsize = size * nmemb; MemoryStruct* mem = (MemoryStruct *)userp; - mem->memoryP = (char*)realloc(mem->memoryP, mem->size + realsize + 1); + + mem->memoryP = realloc(mem->memoryP, mem->size + realsize + 1); if (mem->memoryP == NULL) { /* out of memory! */ LOGE("not enough memory (realloc returned NULL)\n"); @@ -299,8 +177,7 @@ int debug_function (CURL * curl_handle, curl_infotype info, char* debugMessageP, { if(debugMessageP!=NULL && debugMessageSize!=0) { - char* msgP=(char*)malloc(debugMessageSize+1); - if(NULL==msgP)return 0; + char* msgP=malloc(debugMessageSize+1); memcpy(msgP, debugMessageP, debugMessageSize); msgP[debugMessageSize]=0; LOGD("curl: %d %s",info, msgP); @@ -316,7 +193,7 @@ int debug_function (CURL * curl_handle, curl_infotype info, char* debugMessageP, bool copyHeader(void *contents, size_t length, char** headerP) { - *headerP = (char *)malloc(length + 1); + *headerP = malloc(length + 1); if (*headerP == NULL) { /* out of memory! */ LOGE("not enough memory (malloc returned NULL)\n"); @@ -407,42 +284,23 @@ void setCertPath(const char* localPathP, const char* certPathP) if (certPathP!=NULL && (strlen(certPathP)+1)>saveCertFile %s", filePath); + FILE* fh; if ((fh = fopen(filePath, "w")) != NULL) // recreating the file every time, this is not the most efficient way, but ensures { // the file is updated in case rootpa and the required content is updated fprintf(fh, "%s", fileContent); @@ -457,8 +315,6 @@ void saveCertFile(char* filePath, char* fileContent) bool setBasicOpt(CURL* curl_handle, MemoryStruct* chunkP, HeaderStruct* headerChunkP, const char* linkP, struct curl_slist* headerListP) { - long int se_connection_timeout=SE_CONNECTION_DEFAULT_TIMEOUT; - if(curl_easy_setopt(curl_handle, CURLOPT_URL, linkP)!=CURLE_OK) { LOGE("curl_easy_setopt CURLOPT_URL failed"); @@ -528,6 +384,7 @@ bool setBasicOpt(CURL* curl_handle, MemoryStruct* chunkP, HeaderStruct* headerCh return false; } + long int se_connection_timeout=SE_CONNECTION_DEFAULT_TIMEOUT; #ifdef __DEBUG curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L); curl_easy_setopt(curl_handle, CURLOPT_DEBUGFUNCTION, debug_function); @@ -563,7 +420,6 @@ bool setBasicOpt(CURL* curl_handle, MemoryStruct* chunkP, HeaderStruct* headerCh bool setPutOpt(CURL* curl_handle, ResponseStruct* responseChunk) { - long chunkSize=responseChunk->size; LOGD(">>setPutOpt"); if (curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, readResponseCallback)!=CURLE_OK) { @@ -589,8 +445,8 @@ bool setPutOpt(CURL* curl_handle, ResponseStruct* responseChunk) return false; } - - if (curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE, chunkSize)!=CURLE_OK) + long s=responseChunk->size; + if (curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE, s)!=CURLE_OK) { LOGE("curl_easy_setopt CURLOPT_INFILESIZE_LARGE failed"); return false; @@ -631,7 +487,6 @@ bool setPostOpt(CURL* curl_handle, const char* inputP) bool setDeleteOpt(CURL* curl_handle, const char* inputP) { - (void) inputP; LOGD(">>setDeleteOpt %s", inputP); if (curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "DELETE")!=CURLE_OK) { @@ -684,14 +539,6 @@ rootpaerror_t httpCommunicate(const char * const inputP, const char** linkP, con time_t endtime=0; int timediff=0; - ResponseStruct responseChunk; - MemoryStruct chunk; - HeaderStruct headerChunk; - headerChunk.linkSize = 0; - headerChunk.relSize = 0; - headerChunk.linkP = NULL; - headerChunk.relP = NULL; - LOGD(">>httpCommunicate"); if(NULL==linkP || NULL==relP || NULL==commandP || NULL==*linkP) { @@ -701,8 +548,17 @@ rootpaerror_t httpCommunicate(const char * const inputP, const char** linkP, con *commandP=NULL; *relP=NULL; + ResponseStruct responseChunk; + + HeaderStruct headerChunk; + headerChunk.linkSize = 0; + headerChunk.relSize = 0; + headerChunk.linkP = NULL; + headerChunk.relP = NULL; + + MemoryStruct chunk; chunk.size = 0; /* no data at this point */ - chunk.memoryP = (char *)malloc(1); /* will be grown as needed by the realloc above */ + chunk.memoryP = malloc(1); /* will be grown as needed by the realloc above */ if(NULL==chunk.memoryP) { return ROOTPA_ERROR_OUT_OF_MEMORY; @@ -770,11 +626,7 @@ rootpaerror_t httpCommunicate(const char * const inputP, const char** linkP, con curlRet=curl_easy_perform(curl_handle_); LOGD("curl_easy_perform %ld %d", curlRet, attempts ); if(CURLE_OK==curlRet) break; -#ifdef WIN32 - Sleep(SLEEPTIME_MS); -#else nanosleep(&SLEEPTIME,NULL); -#endif endtime=time(NULL); timediff=(int)ceil(difftime(endtime, begintime)); LOGD("timediff (ceil) %d", timediff); @@ -858,4 +710,3 @@ rootpaerror_t httpCommunicate(const char * const inputP, const char** linkP, con LOGD("< + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. -#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)) + 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. -#else + 3. Neither the name of the Trustonic Limited nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 OWNTOOLS_H +#define OWNTOOLS_H #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)) -#endif - #endif // OWNTOOLS_H diff --git a/mobicore/rootpa/Code/Common/trustletchannel.c b/mobicore/rootpa/Code/Common/trustletchannel.c index 1d1e60f..ae1f957 100644 --- a/mobicore/rootpa/Code/Common/trustletchannel.c +++ b/mobicore/rootpa/Code/Common/trustletchannel.c @@ -1,40 +1,35 @@ /* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ +Copyright © Trustonic Limited 2013 + +All rights reserved. + +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. Neither the name of the Trustonic Limited nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. +*/ #include -#ifdef WIN32 - #include - #include -#endif -#include #include #include #include "tools.h" @@ -47,96 +42,13 @@ start using other than default device id if need arises */ static uint32_t tltChannelDeviceId=MC_DEVICE_ID_DEFAULT; -#ifdef WIN32 - -#define MAX_TL_FILENAME 1024 - -/** -Since Windows version of "mcDaemon" does not access registry, this function is used to load system TA and open session to it. -*/ -mcResult_t OpenSysTaFromRegistry( - mcSessionHandle_t * session, - const mcUuid_t * uuid, - uint8_t * tci, - uint32_t tciLen) - { - - - size_t taSize; - int result; - struct stat fstat; - mcResult_t status = MC_DRV_ERR_UNKNOWN; - uint8_t * taBlob; - int lastErr; - - - // get registry path - // TODO-2013-07-17-jearig01 import registry from global variable - - char registryPath[MAX_TL_FILENAME] = "C:\\Windows\\tbaseregistry\\"; - char trustedAppPath[MAX_TL_FILENAME]; - char hx[MAX_TL_FILENAME]; - - for (size_t i = 0; i < sizeof(*uuid); i++) { - sprintf(&hx[i * 2], "%02x", ((uint8_t *)uuid)[i]); - } - - snprintf(trustedAppPath, sizeof(trustedAppPath), "%s%s%s", registryPath,hx, ".tlbin"); - - printf("app path--> %s\n",trustedAppPath); - printf("registryPath path--> %s\n",registryPath); - printf("hx--> %s\n",hx); - - //check file - result = stat(trustedAppPath, &fstat); - if (result!=0) return MC_DRV_ERR_TRUSTLET_NOT_FOUND; - taSize = fstat.st_size; - - // import file in a blob - FILE *infile = fopen(trustedAppPath, "rb"); - - if (infile == NULL) return MC_DRV_ERR_TRUSTLET_NOT_FOUND; - - taBlob = (uint8_t *) malloc(taSize); - if (taBlob == NULL) - { - fclose(infile); - return MC_DRV_ERR_NO_FREE_MEMORY; - } - - result = fread (taBlob, 1, taSize, infile); - - printf("FREAD--> %d - %d\n",result, taSize); - if (result == taSize) - { - // Call OpenTrustlet - printf("app path--> %d - %d\n",tciLen, taSize); - status = mcOpenTrustlet(session, 0, taBlob, taSize, tci, tciLen); - } - - // free blobs, necessary data are supposed to have been sent to SWd and are now useless in NWd - fclose(infile); - free(taBlob); - - return status; - } -#endif - /* Open session to content management trustlet and allocate enough memory for communication */ -CMTHANDLE tltChannelOpen(int sizeOfWsmBuffer, mcResult_t* result) -{ +CMTHANDLE tltChannelOpen(int sizeOfWsmBuffer, mcResult_t* result){ + CMTHANDLE handle = (CMTHANDLE)malloc(sizeof(CMTSTRUCT)); const mcUuid_t UUID = TL_CM_UUID; - return taChannelOpen(sizeOfWsmBuffer, result, &UUID, NULL, 0,0); -} - -/* -*/ -CMTHANDLE taChannelOpen(int sizeOfWsmBuffer, mcResult_t* result, const mcUuid_t* uuidP, uint8_t* taBinaryP, uint32_t taLength, mcSpid_t spid) -{ - CMTHANDLE handle = (CMTHANDLE)malloc(sizeof(CMTSTRUCT)); if (unlikely( NULL==handle )) { @@ -146,42 +58,33 @@ CMTHANDLE taChannelOpen(int sizeOfWsmBuffer, mcResult_t* result, const mcUuid_t memset(handle,0,sizeof(CMTSTRUCT)); +#if ! ( defined(LINUX) || (defined(WIN32) && defined(_TEST_SUITE)) ) + *result = mcOpenDevice(tltChannelDeviceId); if (MC_DRV_OK != *result) { - LOGE("taChannelOpen: Unable to open device, error: %d", *result); + LOGE("tltChannelOpen: Unable to open device, error: %d", *result); free(handle); return NULL; } +#endif *result = mcMallocWsm(tltChannelDeviceId, 0, sizeOfWsmBuffer, &handle->wsmP, 0); if (MC_DRV_OK != *result) { - LOGE("taChannelOpen: Allocation of CMP WSM failed, error: %d", *result); + LOGE("tltChannelOpen: Allocation of CMP WSM failed, error: %d", *result); mcCloseDevice(tltChannelDeviceId); free(handle); return NULL; } - if(taBinaryP!=NULL && taLength!=0) - { - *result = mcOpenTrustlet(&handle->session, spid, taBinaryP, taLength, handle->wsmP,(uint32_t)sizeOfWsmBuffer); - } - else - { -#ifdef WIN32 - *result = OpenSysTaFromRegistry(&handle->session,uuidP,handle->wsmP,(uint32_t)sizeOfWsmBuffer); -#else - *result = mcOpenSession(&handle->session,uuidP, handle->wsmP,(uint32_t)sizeOfWsmBuffer); -#endif - } - + *result = mcOpenSession(&handle->session,(const mcUuid_t *)&UUID,handle->wsmP,(uint32_t)sizeOfWsmBuffer); if (MC_DRV_OK != *result) { - LOGE("taChannelOpen: Open session failed, error: %d", *result); + LOGE("tltChannelOpen: Open session failed, error: %d", *result); mcFreeWsm(tltChannelDeviceId,handle->wsmP); mcCloseDevice(tltChannelDeviceId); free(handle); @@ -190,7 +93,6 @@ CMTHANDLE taChannelOpen(int sizeOfWsmBuffer, mcResult_t* result, const mcUuid_t return handle; } - /* Close the communication channel and free resources */ @@ -207,11 +109,13 @@ void tltChannelClose(CMTHANDLE handle){ if (NULL!=handle->wsmP) mcFreeWsm(tltChannelDeviceId, handle->wsmP); +#if ! ( defined(LINUX) || (defined(WIN32) && defined(_TEST_SUITE)) ) result = mcCloseDevice(tltChannelDeviceId); if (MC_DRV_OK != result) { LOGE("tltChannelClose: Closing MobiCore device failed, error: %d", result); } +#endif free(handle); } } diff --git a/mobicore/rootpa/Code/Common/trustletchannel.h b/mobicore/rootpa/Code/Common/trustletchannel.h index e1c5333..bec2961 100644 --- a/mobicore/rootpa/Code/Common/trustletchannel.h +++ b/mobicore/rootpa/Code/Common/trustletchannel.h @@ -1,39 +1,38 @@ /* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ +Copyright © Trustonic Limited 2013 + +All rights reserved. + +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. Neither the name of the Trustonic Limited nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 TRUSTLETCHANNEL_H #define TRUSTLETCHANNEL_H -#include - +#include #include typedef struct cmtstruct CMTSTRUCT; @@ -55,11 +54,6 @@ Open session to content management trustlet and allocate enough memory for commu */ CMTHANDLE tltChannelOpen(int sizeOfWsmBuffer, mcResult_t* result); -/** -Open session to TA and allocate enough memory for communication. There are two way to do this, give TA uuid or TA binary, binary length and spid. -The former works with system TA's the latter with SP TA's. -*/ -CMTHANDLE taChannelOpen(int sizeOfWsmBuffer, mcResult_t* result, const mcUuid_t* uuidP, uint8_t* taBinaryP, uint32_t taLength, mcSpid_t spid); /** */ void tltChannelClose(CMTHANDLE handle); diff --git a/mobicore/rootpa/Code/Common/xmlmessagehandler.c b/mobicore/rootpa/Code/Common/xmlmessagehandler.c index b74cb0b..136e3e7 100644 --- a/mobicore/rootpa/Code/Common/xmlmessagehandler.c +++ b/mobicore/rootpa/Code/Common/xmlmessagehandler.c @@ -1,46 +1,39 @@ /* - * Copyright (c) 2013 TRUSTONIC LIMITED - * All rights reserved. - * - * 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. Neither the name of the TRUSTONIC LIMITED nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "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 COPYRIGHT HOLDER OR - * CONTRIBUTORS 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. - */ +Copyright © Trustonic Limited 2013 + +All rights reserved. + +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. Neither the name of the Trustonic Limited nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. +*/ #include #include #include -#include +#include #include -#ifdef TIZEN -#include -extern int asprintf (char **result, const char *format, ...) - __attribute__ ((__format__ (__printf__, 2, 3))); -extern int vasprintf (char **result, const char *format, va_list args) - __attribute__ ((__format__ (__printf__, 2, 0))); -#endif #include #include @@ -61,7 +54,7 @@ extern int vasprintf (char **result, const char *format, va_list args) #define PLATFORM_TYPES_NS_PREFIX "mcpt" #define PLATFORM_TYPES_NAMESPACE "http://www.mcore.gi-de.com/2012/02/schema/MCPlatformTypes" -#define XSD_PATH_MAX_LEN 1024 +#define XSD_PATH_MAX_LEN 256 #define INT_BUFFER_LENGTH 11 #define UNKNOWN_ID 0xFFFFFFFF @@ -82,6 +75,7 @@ static char enrollmentServiceFullPath_[XSD_PATH_MAX_LEN]; static char platformTypesFullPath_[XSD_PATH_MAX_LEN]; static xmlNsPtr nameSpace_=NULL; static xmlNsPtr typesNameSpace_=NULL; + // file internal functions xmlDocPtr createXmlResponse() @@ -102,10 +96,9 @@ xmlDocPtr createXmlResponse() bool addTrustletData(xmlNodePtr rootNode, bool tltBin, char* contentP) { - char* element; xmlNodePtr trustletDataNode=xmlNewChild(rootNode, nameSpace_, BAD_CAST "trustletData", NULL); if(NULL==trustletDataNode) return false; - element ="encryptedKey"; + char* element="encryptedKey"; if(tltBin) { element="tltBin"; @@ -118,63 +111,51 @@ bool addTrustletData(xmlNodePtr rootNode, bool tltBin, char* contentP) char* errorCodeToString(rootpaerror_t errorCode) { - char* returnErrorCode = STRING_ROOTPA_ERROR_INTERNAL; - switch(errorCode) { case ROOTPA_COMMAND_NOT_SUPPORTED: - returnErrorCode = STRING_ROOTPA_COMMAND_NOT_SUPPORTED; - break; + return STRING_ROOTPA_COMMAND_NOT_SUPPORTED; case ROOTPA_ERROR_LOCK: - returnErrorCode = STRING_ROOTPA_ERROR_LOCK; - break; + return STRING_ROOTPA_ERROR_LOCK; // // this is not currently understood by SE // // case ROOTPA_ERROR_COMMAND_EXECUTION: -// returnErrorCode = STRING_ROOTPA_ERROR_COMMAND_EXECUTION; -// break; +// return STRING_ROOTPA_ERROR_COMMAND_EXECUTION; case ROOTPA_ERROR_REGISTRY: - returnErrorCode = STRING_ROOTPA_ERROR_REGISTRY; - break; + return STRING_ROOTPA_ERROR_REGISTRY; case ROOTPA_ERROR_MOBICORE_CONNECTION: - returnErrorCode = STRING_ROOTPA_ERROR_MOBICORE_CONNECTION; - break; + return STRING_ROOTPA_ERROR_MOBICORE_CONNECTION; case ROOTPA_ERROR_OUT_OF_MEMORY: - returnErrorCode = STRING_ROOTPA_ERROR_OUT_OF_MEMORY; - break; + return STRING_ROOTPA_ERROR_OUT_OF_MEMORY; case ROOTPA_ERROR_INTERNAL: - returnErrorCode = STRING_ROOTPA_ERROR_INTERNAL; - break; + return STRING_ROOTPA_ERROR_INTERNAL; case ROOTPA_ERROR_XML: - returnErrorCode = STRING_ROOTPA_ERROR_XML; - break; + return STRING_ROOTPA_ERROR_XML; case ROOTPA_ERROR_REGISTRY_OBJECT_NOT_AVAILABLE: - returnErrorCode = STRING_ROOTPA_ERROR_REGISTRY_OBJECT_NOT_AVAILABLE; - break; + return STRING_ROOTPA_ERROR_REGISTRY_OBJECT_NOT_AVAILABLE; + } LOGD("errorCodeToString: unknown error code %d", errorCode); - - return returnErrorCode; + return STRING_ROOTPA_ERROR_INTERNAL; } bool addCommandResultData(xmlNodePtr resultListNode, int id, char* commandResultP, rootpaerror_t errorCode, uint32_t errorDetail ) { - bool retValue; - char intBuffer[INT_BUFFER_LENGTH]; - xmlNodePtr commandResultNode=xmlNewChild(resultListNode, nameSpace_, BAD_CAST "commandResult", NULL); if(NULL==commandResultNode) return false; - retValue=true; + bool retValue=true; + char intBuffer[INT_BUFFER_LENGTH]; + snprintf(intBuffer,INT_BUFFER_LENGTH,"%u",(uint32_t) id); if(xmlNewProp(commandResultNode, BAD_CAST "id", BAD_CAST intBuffer)==NULL) return false; @@ -209,13 +190,10 @@ bool addCommandResultData(xmlNodePtr resultListNode, int id, char* commandResul xmlNodePtr findFirstCommandNode(xmlDocPtr xmlDocP) { - xmlNodePtr commandsNodeP; - xmlNodePtr rootElementP; - - rootElementP = xmlDocGetRootElement(xmlDocP); + xmlNodePtr rootElementP = xmlDocGetRootElement(xmlDocP); if(NULL==rootElementP) return NULL; - commandsNodeP=rootElementP->children; + xmlNodePtr commandsNodeP=rootElementP->children; for (; commandsNodeP; commandsNodeP = commandsNodeP->next) { if (commandsNodeP->type == XML_ELEMENT_NODE && strcmp((char*)commandsNodeP->name, "commands")==0) @@ -229,9 +207,8 @@ xmlNodePtr findFirstCommandNode(xmlDocPtr xmlDocP) xmlNodePtr getNextCommand(xmlDocPtr xmlDocP, xmlNodePtr prevNode) { - xmlNodePtr firstNode; - xmlNodePtr commandNode; LOGD(">> getNextCommand %ld %ld", (long int) xmlDocP, (long int) prevNode); + xmlNodePtr firstNode; if(NULL==prevNode) { firstNode=findFirstCommandNode(xmlDocP); @@ -241,6 +218,7 @@ xmlNodePtr getNextCommand(xmlDocPtr xmlDocP, xmlNodePtr prevNode) firstNode=prevNode->next; } + xmlNodePtr commandNode; for (commandNode = firstNode; commandNode; commandNode = commandNode->next) { if (commandNode->type == XML_ELEMENT_NODE && strcmp((char*)commandNode->name, "command")==0) @@ -255,25 +233,21 @@ xmlNodePtr getNextCommand(xmlDocPtr xmlDocP, xmlNodePtr prevNode) int getCommandId(xmlNodePtr commandNode) { - int id; - xmlChar* idP; - idP=xmlGetProp(commandNode, BAD_CAST "id"); + xmlChar* idP=xmlGetProp(commandNode, BAD_CAST "id"); if(NULL==idP) { return UNKNOWN_ID; } - id=atoi((char*)idP); + int id=atoi((char*)idP); xmlFree(idP); return id; } commandtype_t getCommandType(xmlNodePtr commandNode) { - xmlChar* typeP; - commandtype_t type; if(NULL==commandNode) return UNKNOWN_TYPE; - typeP=xmlGetProp(commandNode, BAD_CAST "type"); - type=UNKNOWN_TYPE; + xmlChar* typeP=xmlGetProp(commandNode, BAD_CAST "type"); + commandtype_t type=UNKNOWN_TYPE; if(typeP!=NULL) { if(strcmp((char*)typeP,"CMP")==0) type=CMP; @@ -335,7 +309,7 @@ void getValues(xmlNodePtr commandNodeP, commandtype_t* commandTypeP, uint32_t* i uint32_t extractCmpCommand(CmpMessage** cmpCommandsP, uint32_t numberOfCmpCommands, uint32_t id, char* commandValueP, bool ignoreError) { CmpMessage* localCommandsP=*cmpCommandsP; // localCommandsP is just to make the code a bit more readable - CmpMessage* tmpCommandsP=(CmpMessage*)realloc(localCommandsP, sizeof(CmpMessage)*(numberOfCmpCommands+1)); + CmpMessage* tmpCommandsP=realloc(localCommandsP, sizeof(CmpMessage)*(numberOfCmpCommands+1)); if(tmpCommandsP!=NULL) { @@ -376,11 +350,10 @@ uint32_t extractCmpCommand(CmpMessage** cmpCommandsP, uint32_t numberOfCmpComman rootpaerror_t handleCmpResponses(uint32_t maxNumberOfCmpResponses, CmpMessage* cmpResponsesP, xmlNodePtr rspResultElementP) { + LOGD(">>handleCmpResponses %d", maxNumberOfCmpResponses); rootpaerror_t ret=ROOTPA_OK; uint32_t i; - LOGD(">>handleCmpResponses %d", maxNumberOfCmpResponses); - - if(cmpResponsesP == NULL) + if(cmpResponsesP == NULL) { if(maxNumberOfCmpResponses>0) { @@ -428,11 +401,10 @@ uint32_t handleUploadCommand(commandtype_t commandType, char* commandValueP, bool ignoreError) { - uint8_t* containerDataP = NULL; - int containerLength; - CommonMessage* localCommandsP=*uploadCommandsP; // localCommandsP is just to make the code a bit more readable - CommonMessage* tmpCommandsP=(CommonMessage*)realloc(localCommandsP, sizeof(CommonMessage)*(numberOfUploadCommands+1)); LOGD(">>handleUploadCommand %d %lx %lx", commandType, (long int) uploadCommandsP, (long int) *uploadCommandsP); + CommonMessage* localCommandsP=*uploadCommandsP; // localCommandsP is just to make the code a bit more readable + CommonMessage* tmpCommandsP=realloc(localCommandsP, sizeof(CommonMessage)*(numberOfUploadCommands+1)); + if(NULL == tmpCommandsP) { LOGE("handleUploadCommand: was not able to realloc, returning %d", ignoreError); @@ -457,8 +429,8 @@ uint32_t handleUploadCommand(commandtype_t commandType, } localCommandsP[numberOfUploadCommands].ret=ROOTPA_OK; - - containerLength= base64DecodeStringRemoveEndZero(commandValueP, (char**) &(containerDataP)); + uint8_t* containerDataP = NULL; + int containerLength= base64DecodeStringRemoveEndZero(commandValueP, (char**) &(containerDataP)); if(0 == containerLength) { @@ -492,12 +464,11 @@ uint32_t handleUploadCommand(commandtype_t commandType, rootpaerror_t handleUploadResponses(uint32_t numberOfUploadResponses, CommonMessage* uploadResponsesP, xmlNodePtr rspResultElementP) { + LOGD(">>handleUploadResponses %d", numberOfUploadResponses); rootpaerror_t ret=ROOTPA_OK; char zero=0; uint32_t i; - LOGD(">>handleUploadResponses %d", numberOfUploadResponses); - - if(uploadResponsesP == NULL) + if(uploadResponsesP == NULL) { if(numberOfUploadResponses>0) { @@ -536,9 +507,12 @@ rootpaerror_t handleUploadResponses(uint32_t numberOfUploadResponses, CommonMess rootpaerror_t handleCommandAndFillResponse(xmlDocPtr xmlCommandP, xmlDocPtr xmlResponseP) { + LOGD(">>handleCommandAndFillResponse"); rootpaerror_t ret=ROOTPA_OK; rootpaerror_t tmpRet=ROOTPA_OK; - xmlNodePtr rspRootElementP; + + xmlNodePtr rspRootElementP = xmlDocGetRootElement(xmlResponseP); + if(NULL==rspRootElementP) return ROOTPA_ERROR_XML; CmpMessage* cmpCommandsP=NULL; CommonMessage* uploadCommandsP=NULL; @@ -549,15 +523,8 @@ rootpaerror_t handleCommandAndFillResponse(xmlDocPtr xmlCommandP, xmlDocPtr xmlR commandtype_t commandType=UNKNOWN_TYPE; uint32_t id=0; char* commandValueP=NULL; - CmpMessage* cmpResponsesP=NULL; bool ignoreError=0; xmlNodePtr commandNode=NULL; - int i; - - LOGD(">>handleCommandAndFillResponse"); - - rspRootElementP = xmlDocGetRootElement(xmlResponseP); - if(NULL==rspRootElementP) return ROOTPA_ERROR_XML; // parse command data out of xml, upload commands will also be executed @@ -600,10 +567,13 @@ rootpaerror_t handleCommandAndFillResponse(xmlDocPtr xmlCommandP, xmlDocPtr xmlR } // execute the actual content management protocol commands, if there are any + + CmpMessage* cmpResponsesP=NULL; if(cmpCommandsP) { uint32_t internalError; - cmpResponsesP=(CmpMessage *)malloc(sizeof(CmpMessage)*numberOfCmpCommands); + cmpResponsesP=malloc(sizeof(CmpMessage)*numberOfCmpCommands); + memset(cmpResponsesP, 0, sizeof(CmpMessage)*numberOfCmpCommands); if(NULL==cmpResponsesP) { @@ -611,7 +581,6 @@ rootpaerror_t handleCommandAndFillResponse(xmlDocPtr xmlCommandP, xmlDocPtr xmlR } else { - memset(cmpResponsesP, 0, sizeof(CmpMessage)*numberOfCmpCommands); tmpRet=executeContentManagementCommands(numberOfCmpCommands, cmpCommandsP, cmpResponsesP, &internalError); if(ROOTPA_OK!=tmpRet) { @@ -643,6 +612,7 @@ rootpaerror_t handleCommandAndFillResponse(xmlDocPtr xmlCommandP, xmlDocPtr xmlR } // cleanup what has not yet been cleaned + int i; for(i=0; i>saveFile %s", filePath); + FILE* fh; + if ((fh = fopen(filePath, "w")) != NULL) { fprintf(fh, "%s", fileContent); @@ -707,6 +662,7 @@ void saveFile(char* filePath, char* fileContent) bool validXmlMessage(xmlDocPtr xmlDocP) { + LOGD(">>validXmlMessage %s", enrollmentServiceFullPath_); int result=-2; @@ -715,7 +671,7 @@ bool validXmlMessage(xmlDocPtr xmlDocP) xmlSchemaParserCtxtPtr parserCtxtP = NULL; xmlSchemaPtr schemaP = NULL; xmlSchemaValidCtxtPtr validCtxtP = NULL; - LOGD(">>validXmlMessage %s", enrollmentServiceFullPath_); + // Here we store the schemas if they are not already on "disk". It seems // xmlSchemaNewParserCtxt succeeds even if the file does not exists and it is // xmlSchemaParse that requires the file to exists. That is why the files are @@ -757,19 +713,20 @@ cleanup: LOGD("<>handleXmlMessage"); rootpaerror_t ret=ROOTPA_OK; rootpaerror_t tmpRet=ROOTPA_OK; - xmlDocPtr xmlDocP; - xmlDocPtr xmlResponseP; - *responseP=NULL; - LOGD(">>handleXmlMessage"); if (NULL==messageP) { @@ -817,7 +767,7 @@ rootpaerror_t handleXmlMessage(const char* messageP, const char** responseP) xmlThrDefSetStructuredErrorFunc(NULL, NULL); xmlThrDefSetGenericErrorFunc(NULL, handleError); - xmlDocP= xmlParseMemory(messageP, strlen(messageP)); + xmlDocPtr xmlDocP= xmlParseMemory(messageP, strlen(messageP)); if(NULL==xmlDocP) { LOGE("handleXmlMessage, can not parse xmlMessageP %s", messageP); @@ -831,7 +781,7 @@ rootpaerror_t handleXmlMessage(const char* messageP, const char** responseP) // attempting to parse the message anyway. } - xmlResponseP=createXmlResponse(); + xmlDocPtr xmlResponseP=createXmlResponse(); // parse received command @@ -912,9 +862,9 @@ rootpaerror_t fillSystemInfo(xmlNodePtr systemInfoNode, const osInfo_t* osSpecif rootpaerror_t fillMcVersion(xmlNodePtr mcVersionNode, int mcVersionTag, const mcVersionInfo_t* mcVersionP) { - (void) mcVersionTag; - char intBuffer[INT_BUFFER_LENGTH]; LOGD(">>fillMcVersion"); + char intBuffer[INT_BUFFER_LENGTH]; + xmlSetStructuredErrorFunc(NULL, NULL); xmlSetGenericErrorFunc(NULL, handleError); xmlThrDefSetStructuredErrorFunc(NULL, NULL); @@ -953,24 +903,19 @@ rootpaerror_t fillMcVersion(xmlNodePtr mcVersionNode, int mcVersionTag, const mc rootpaerror_t buildXmlTrustletInstallationRequest(const char** responseP, trustletInstallationData_t data ) { char intBuffer[INT_BUFFER_LENGTH]; - rootpaerror_t ret=ROOTPA_OK; - xmlDocPtr xmlResponseDocP; - xmlNodePtr rspRootElementP; - xmlNodePtr systemInfoNode; - xmlNodePtr mcDataNode=NULL; - char* encodedDataP; - char* pukHashStringP; LOGD(">>buildXmlTrustletInstallationRequest %ld (%ld %d %d)", (long int) responseP, (long int) data.dataP, data.dataLength, data.dataType); + rootpaerror_t ret=ROOTPA_OK; if(NULL == responseP) return ROOTPA_ERROR_ILLEGAL_ARGUMENT; // data content checked earlier in commandhandler.c - xmlResponseDocP=createXmlResponse(); - rspRootElementP = xmlDocGetRootElement(xmlResponseDocP); + xmlDocPtr xmlResponseDocP=createXmlResponse(); + xmlNodePtr rspRootElementP = xmlDocGetRootElement(xmlResponseDocP); if(NULL==rspRootElementP) return ROOTPA_ERROR_XML; - systemInfoNode=xmlNewChild(rspRootElementP, nameSpace_, BAD_CAST "tltInstallationRequest", NULL); + xmlNodePtr systemInfoNode=xmlNewChild(rspRootElementP, nameSpace_, BAD_CAST "tltInstallationRequest", NULL); if(NULL==systemInfoNode) return ROOTPA_ERROR_XML; - encodedDataP=base64EncodeAddEndZero((char*) data.dataP, data.dataLength); + xmlNodePtr mcDataNode=NULL; + char* encodedDataP=base64EncodeAddEndZero((char*) data.dataP, data.dataLength); if(NULL==encodedDataP) { LOGE("buildXmlTrustletInstallationRequest: base64 encoding of data failed"); @@ -1022,7 +967,7 @@ rootpaerror_t buildXmlTrustletInstallationRequest(const char** responseP, trustl return ROOTPA_ERROR_XML; } - pukHashStringP=base64EncodeAddEndZero((char*) data.tltPukHashP, data.tltPukHashLength); + char* pukHashStringP=base64EncodeAddEndZero((char*) data.tltPukHashP, data.tltPukHashLength); if(NULL==pukHashStringP) { LOGE("buildXmlTrustletInstallationRequest: base64 encoding of PukHash failed"); @@ -1056,28 +1001,23 @@ in case an error is returned *responseP is set to NULL */ rootpaerror_t buildXmlSystemInfo(const char** responseP, int mcVersionTag, const mcVersionInfo_t* mcVersionP, const osInfo_t* osSpecificInfoP) { - + LOGD(">>buildXmlSystemInfo %ld %ld %ld", ( long int ) responseP, ( long int ) mcVersionP, ( long int ) osSpecificInfoP); rootpaerror_t ret=ROOTPA_OK; - xmlDocPtr xmlResponseDocP; - xmlNodePtr rspRootElementP; - xmlNodePtr systemInfoNode; - xmlNodePtr mcVersionNode; if(NULL == responseP || NULL == mcVersionP || NULL == osSpecificInfoP) return ROOTPA_ERROR_INTERNAL; - LOGD(">>buildXmlSystemInfo %ld %ld %ld", ( long int ) responseP, ( long int ) mcVersionP, ( long int ) osSpecificInfoP); xmlSetStructuredErrorFunc(NULL, NULL); xmlSetGenericErrorFunc(NULL, handleError); xmlThrDefSetStructuredErrorFunc(NULL, NULL); xmlThrDefSetGenericErrorFunc(NULL, handleError); - xmlResponseDocP=createXmlResponse(); - rspRootElementP= xmlDocGetRootElement(xmlResponseDocP); + xmlDocPtr xmlResponseDocP=createXmlResponse(); + xmlNodePtr rspRootElementP = xmlDocGetRootElement(xmlResponseDocP); if(NULL==rspRootElementP) return ROOTPA_ERROR_XML; - systemInfoNode=xmlNewChild(rspRootElementP, nameSpace_, BAD_CAST "systemInformation", NULL); + xmlNodePtr systemInfoNode=xmlNewChild(rspRootElementP, nameSpace_, BAD_CAST "systemInformation", NULL); if(NULL==systemInfoNode) return ROOTPA_ERROR_XML; - mcVersionNode=xmlNewChild(systemInfoNode, typesNameSpace_, BAD_CAST "mcVersion", NULL); + xmlNodePtr mcVersionNode=xmlNewChild(systemInfoNode, typesNameSpace_, BAD_CAST "mcVersion", NULL); if(NULL==mcVersionNode) return ROOTPA_ERROR_XML; ret=fillSystemInfo(systemInfoNode, osSpecificInfoP); @@ -1113,11 +1053,8 @@ void setXsdPaths(const char* xsdpathP) if (xsdpathP!=NULL && strlen(xsdpathP)+1+sizeof(ENROLLMENT_SERVICE_XSD_NAME)