/*
 * =====================================================================================
 *
 *       Filename:  teeCmdExecuter.c
 *
 *    Description:  Parsing data and execute command.
 *
 *        Version:  1.0
 *        Created:  03/28/2017 03:40:48 PM
 *       Compiler:  armcc
 *
 *         Author:  Dongwook Shim (), dw.shim@samsung.com
 *        Company:  Samsung Electronics
 *
 *        Copyright (c) 2017 by Samsung Electronics, All rights reserved.
 *
 * =====================================================================================
 */

#include "commonConfig.h"
#include "TLV.h"
#include "cryptoPlatform.h"
#include "log.h"

int32_t taCmdExecute(uint32_t cmdId, const uint8_t *inData, uint32_t inDataLen,
                     uint8_t *outData, uint32_t *outDataLen)
{
    uint8_t *pData = NULL;
    uint16_t dataLen = 0;
    TlvTag_t tlvTag;
    int32_t ret = NOT_ERROR;
    int32_t (*pFunc)(const uint8_t *, const uint32_t, uint8_t *, uint32_t *) = NULL;

    switch(cmdId) {
    case CMD_IS_SUPPORTED_DRK_V2 :
        LOGI("This TA supports DRK v2.");
        *outDataLen = 0;
        return NOT_ERROR;    // Always return true;

    case CMD_ENCRYPT_DRK_CSR :
        tlvTag = TLV_CSR;
        pFunc = encryptDrkCertificateSigningRequest;
        break;

// GAK / SAK are not supported on Tizen.
// Block old commands in Tizen.
#if !(defined USE_TIZEN)

    case CMD_UNWRAP_GAK_BLOB :
        tlvTag = TLV_WRAPPED_KEY;
        pFunc = unwrapGakBlob;
        break;

    case CMD_ENCRYPT_SAK_CSR :
        tlvTag = TLV_CSR;
        pFunc = encryptSakCertificateSigningRequest;
        break;

#if (defined USE_QSEE) && (defined USE_QSEE_SFS)

    case CMD_SHARE_DRK_KEY :
    case CMD_SHARE_DRK_KEY_V1 :
    case CMD_SHARE_DRK_KEY_V0 :
        return getDrkV1ForSkm(outData, outDataLen);
#endif // End of USE_QSEE && USE_QSEE_SFS
#endif  // End of !USE_TIZEN

#if (defined DRK_TEST_API_ENABLED)
    case CMD_VERIFY_SERVICE_KEY :
        tlvTag = TLV_WRAPPED_KEY;
        pFunc = verifyServiceKey;
        break;
#endif // End of DRK_TEST_API_ENABLED

    default :
        LOGE("Not supported command : 0x%X", cmdId);
        return ERR_TA_UNSUPPORTED_CMD;
    }

    if((ret = tlvGet(inData, inDataLen, tlvTag, &dataLen, &pData)) != NOT_ERROR) {
        LOGE("Failed to get blob with error %d.", ret);
        return ERR_TA_BASE + ret;
    }

    if(pFunc != NULL) {
        return pFunc(pData, dataLen, outData, outDataLen);
    } else {
        return ERR_TA_UNSUPPORTED_CMD;
    }
}
