diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 37cbf1a..e390569 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,7 +1,7 @@ # Add library targets ##################### SET(SOURCES device_manager.c fdm_register.c fdm_subscribe.c fdm_licensee_verification.c - fdm_hmac.c fdm_server_session.c fdm_get_client_list.c fdm_provision_constrained.c) + fdm_hmac.c fdm_server_session.c fdm_get_client_list.c fdm_provision_constrained.c) ADD_LIBRARY(devicemanager SHARED ${SOURCES}) INCLUDE(FindPkgConfig) diff --git a/src/device_manager.c b/src/device_manager.c index fe9a002..89e77fc 100644 --- a/src/device_manager.c +++ b/src/device_manager.c @@ -71,22 +71,20 @@ */ const OBJECT_T flowObject = { "FlowObject", Lwm2mObjectId_FlowObject, 11, - (RESOURCE_T []) - { - { FlowObjectResourceId_DeviceId, "DeviceID", AwaResourceType_Opaque, true, true }, - { FlowObjectResourceId_ParentId, "ParentID", AwaResourceType_Opaque, false, false }, - { FlowObjectResourceId_DeviceType, "DeviceType", AwaResourceType_String, true, true }, - { FlowObjectResourceId_DeviceName, "Name", AwaResourceType_String, false, false }, - { FlowObjectResourceId_Description, "Description", AwaResourceType_String, false, false }, - { FlowObjectResourceId_Fcap, "FCAP", AwaResourceType_String, true, true }, - { FlowObjectResourceId_LicenseeId, "LicenseeID", AwaResourceType_Integer, true, true }, - { FlowObjectResourceId_LicenseeChallenge, "LicenseeChallenge", - AwaResourceType_Opaque, false, false }, - { FlowObjectResourceId_HashIterations, "HashIterations", AwaResourceType_Integer, false, - false }, - { FlowObjectResourceId_LicenseeHash, "LicenseeHash", AwaResourceType_Opaque, false, false }, - { FlowObjectResourceId_Status, "Status", AwaResourceType_Integer, false, false } - } + (RESOURCE_T []) + { + { FlowObjectResourceId_DeviceId, "DeviceID", AwaResourceType_Opaque, true, true }, + { FlowObjectResourceId_ParentId, "ParentID", AwaResourceType_Opaque, false, false }, + { FlowObjectResourceId_DeviceType, "DeviceType", AwaResourceType_String, true, true }, + { FlowObjectResourceId_DeviceName, "Name", AwaResourceType_String, false, false }, + { FlowObjectResourceId_Description, "Description", AwaResourceType_String, false, false }, + { FlowObjectResourceId_Fcap, "FCAP", AwaResourceType_String, true, true }, + { FlowObjectResourceId_LicenseeId, "LicenseeID", AwaResourceType_Integer, true, true }, + { FlowObjectResourceId_LicenseeChallenge, "LicenseeChallenge", AwaResourceType_Opaque, false, false }, + { FlowObjectResourceId_HashIterations, "HashIterations", AwaResourceType_Integer, false, false }, + { FlowObjectResourceId_LicenseeHash, "LicenseeHash", AwaResourceType_Opaque, false, false }, + { FlowObjectResourceId_Status, "Status", AwaResourceType_Integer, false, false } + } }; /** @@ -94,17 +92,14 @@ const OBJECT_T flowObject = */ const OBJECT_T flowAccessObject = { "FlowAccess", Lwm2mObjectId_FlowAccess, 5, - (RESOURCE_T []) - { - { FlowAccessResourceId_Url, "URL", AwaResourceType_String, false, true }, - { FlowAccessResourceId_CustomerKey, "CustomerKey", AwaResourceType_String, false, true }, - { FlowAccessResourceId_CustomerSecret, "CustomerSecret", AwaResourceType_String, false, - true }, - { FlowAccessResourceId_RememberMeToken, "RememberMeToken", AwaResourceType_String, false, - true }, - { FlowAccessResourceId_RememberMeTokenExpiry, "RememberMeTokenExpiry", - AwaResourceType_Time, false, true } - } + (RESOURCE_T []) + { + { FlowAccessResourceId_Url, "URL", AwaResourceType_String, false, true }, + { FlowAccessResourceId_CustomerKey, "CustomerKey", AwaResourceType_String, false, true }, + { FlowAccessResourceId_CustomerSecret, "CustomerSecret", AwaResourceType_String, false, true }, + { FlowAccessResourceId_RememberMeToken, "RememberMeToken", AwaResourceType_String, false, true }, + { FlowAccessResourceId_RememberMeTokenExpiry, "RememberMeTokenExpiry", AwaResourceType_Time, false, true } + } }; /** @@ -113,13 +108,11 @@ const OBJECT_T flowAccessObject = */ static const OBJECT_T deviceObject = { "DeviceObject", Lwm2mObjectId_DeviceObject, 2, - (RESOURCE_T []) - { - { DeviceObjectResourceId_SerialNumber, "SerialNumber", AwaResourceType_String, false, - true }, - { DeviceObjectResourceId_SoftwareVersion, "SoftwareVersion", AwaResourceType_String, false, - true } - } + (RESOURCE_T []) + { + { DeviceObjectResourceId_SerialNumber, "SerialNumber", AwaResourceType_String, false, true }, + { DeviceObjectResourceId_SoftwareVersion, "SoftwareVersion", AwaResourceType_String, false, true } + } }; /** @@ -138,58 +131,56 @@ FILE *debugStream = NULL; FILE* SetLogFile(const char *file) { - FILE *logFile = NULL; - logFile = fopen(file, "w"); - if (logFile != NULL) - { - LOG(LOG_DBG, "Log file set to %s", file); - debugStream = logFile; - } - else - { - LOG(LOG_ERR, "Failed to create or open %s file", file); - } - return logFile; + FILE *logFile = NULL; + logFile = fopen(file, "w"); + if (logFile != NULL) + { + LOG(LOG_DBG, "Log file set to %s", file); + debugStream = logFile; + } + else + { + LOG(LOG_ERR, "Failed to create or open %s file", file); + } + return logFile; } void SetDebugLevel(unsigned int level) { - LOG(LOG_DBG, "Set debug level to %u", level); - debugLevel = level; + LOG(LOG_DBG, "Set debug level to %u", level); + debugLevel = level; } bool EstablishSession(void) { - AwaError error; - bool success = false; - - LOG(LOG_INFO, "Establish session with lwm2m client"); - - session = AwaClientSession_New(); - if (session == NULL) - { - LOG(LOG_ERR, "Failed to create session"); - return false; - } - - if ((error = AwaClientSession_SetIPCAsUDP(session, IPC_ADDRESS, IPC_PORT)) - == AwaError_Success) - { - if ((error = AwaClientSession_Connect(session)) == AwaError_Success) - { - success = true; - } - else - { - LOG(LOG_ERR, "Failed to connect session with lwm2m client\n" - "error: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to set IPC as UDP\nerror: %s", AwaError_ToString(error)); - } - return success; + AwaError error; + bool result = false; + + LOG(LOG_INFO, "Establish session with lwm2m client"); + + session = AwaClientSession_New(); + if (session == NULL) + { + LOG(LOG_ERR, "Failed to create session"); + return false; + } + + if ((error = AwaClientSession_SetIPCAsUDP(session, IPC_ADDRESS, IPC_PORT)) == AwaError_Success) + { + if ((error = AwaClientSession_Connect(session)) == AwaError_Success) + { + result = true; + } + else + { + LOG(LOG_ERR, "Failed to connect session with lwm2m client\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to set IPC as UDP\nerror: %s", AwaError_ToString(error)); + } + return result; } /** @@ -199,181 +190,181 @@ bool EstablishSession(void) */ static bool SaveFlowCloudAccessDetails() { - char strings[MAX_STRINGS][MAX_STR_SIZE] = {{0}}; - unsigned int i, resCount = 0; - OBJECT_T objects[] = - { - flowObject, - flowAccessObject, - deviceObject - }; - LOG(LOG_INFO, "Saving flow cloud access details..."); - - if (!(resCount = GetResources(session, objects, ARRAY_SIZE(objects), strings))) - { - LOG(LOG_ERR, "Failed to get objects resource values"); - return false; - } - - FILE *configFile = fopen(FLOW_ACCESS_CFG, "w"); - if (configFile == NULL) - { - LOG(LOG_ERR, "Failed to create or open "FLOW_ACCESS_CFG); - return false; - } - for (i = 0; i < resCount; i++) - { - fprintf(configFile, "%s\n", strings[i]); - } - if (fclose(configFile)) - { - LOG(LOG_ERR, "Failed to close "FLOW_ACCESS_CFG); - } - return true; + char strings[MAX_STRINGS][MAX_STR_SIZE] = {{0}}; + unsigned int i, resCount = 0; + OBJECT_T objects[] = + { + flowObject, + flowAccessObject, + deviceObject + }; + LOG(LOG_INFO, "Saving flow cloud access details..."); + + if (!(resCount = GetResources(session, objects, ARRAY_SIZE(objects), strings))) + { + LOG(LOG_ERR, "Failed to get objects resource values"); + return false; + } + + FILE *configFile = fopen(FLOW_ACCESS_CFG, "w"); + if (configFile == NULL) + { + LOG(LOG_ERR, "Failed to create or open "FLOW_ACCESS_CFG); + return false; + } + for (i = 0; i < resCount; i++) + { + fprintf(configFile, "%s\n", strings[i]); + } + if (fclose(configFile)) + { + LOG(LOG_ERR, "Failed to close "FLOW_ACCESS_CFG); + } + return true; } -ProvisionStatus ProvisionGatewayDevice(const char *deviceName, const char *deviceType, - int licenseeID, const char *fcap, const char *licenseeSecret) +ProvisionStatus ProvisionGatewayDevice(const char *deviceName, const char *deviceType, int licenseeID, const char *fcap, const char *licenseeSecret) { - FlowSubscriptions subscriptions = {0}; - Verification verificationData; - unsigned int timeout = SERVER_RESPONSE_TIMEOUT; - unsigned int sleepTime = SLEEP_COUNT; - OBJECT_T flowObjects[] = - { - flowObject, - flowAccessObject, - }; - - if (deviceName == NULL || deviceType == NULL || fcap == NULL || licenseeSecret == NULL) - { - LOG(LOG_ERR, "Null parameters passed to %s()", __func__); - return PROVISION_FAIL; - } - - LOG(LOG_INFO, "Provisioning device with following details:\n" - "\n%-15s\t = %s\n%-15s\t = %s\n%-15s\t = %d\n%-15s\t = %s\n%-15s\t = %s", "Device Name", - deviceName, "Device Type", deviceType, "Licensee ID", licenseeID, "FCAP", fcap, - "Licensee Secret", licenseeSecret); - - if (!DefineObjectsAtClient(session, flowObjects, ARRAY_SIZE(flowObjects))) - { - LOG(LOG_ERR, "Failed to define Flow objects"); - return PROVISION_FAIL; - } - - if(IsGatewayDeviceProvisioned()) - { - return ALREADY_PROVISIONED; - } - - if (!PopulateFlowObject(session, deviceName, deviceType, licenseeID, fcap)) - { - LOG(LOG_ERR, "Failed to populate flow object with device type, licensee id and fcap"); - return PROVISION_FAIL; - } - - memset(&verificationData, 0, sizeof(Verification)); - verificationData.waitForServerResponse = true; - verificationData.hasChallenge = false; - verificationData.hasIterations = false; - verificationData.verifyLicensee = false; - verificationData.isProvisionSuccess = false; - - if (!SubscribeToFlowObjects(session, &subscriptions, &verificationData)) - { - LOG(LOG_ERR, "Failed to subscribe flow and flow access objects"); - return PROVISION_FAIL; - } - - LOG(LOG_INFO, "Waiting for responses from FlowCloud server..."); - - while(verificationData.waitForServerResponse && --timeout) - { - AwaClientSession_Process(session, IPC_TIMEOUT); - AwaClientSession_DispatchCallbacks(session); - - if (verificationData.verifyLicensee) - { - if (PerformFlowLicenseeVerification(session, &verificationData, licenseeSecret)) - { - verificationData.verifyLicensee = false; - } - } - sleep(1); - } - - if (!timeout) - { - LOG(LOG_INFO, "No response within timeout"); - } - - // FIXME: Temporary code until status resource is removed from FlowObject so we only get one - // change notification before canceling the subscription. - // Right now Message IDs aren't used in IPC, so it is possible to get messages out of order, - // causing the application to parse a response it is not expecting. - LOG(LOG_INFO, "Waiting for any residual notifications..."); - while(sleepTime-- > 0) - { - AwaClientSession_Process(session, IPC_TIMEOUT); - AwaClientSession_DispatchCallbacks(session); - sleep(1); - } - - // Clean up - UnSubscribeFromFlowObjects(session, &subscriptions); - if (verificationData.challenge.Data != NULL) - { - free(verificationData.challenge.Data); - } - if (verificationData.licenseeHash.Data != NULL) - { - free(verificationData.licenseeHash.Data); - } - - if (!verificationData.isProvisionSuccess) - { - return PROVISION_FAIL; - } - - if (!SaveFlowCloudAccessDetails()) - { - LOG(LOG_ERR, "Failed to save flow cloud access details"); - } - return PROVISION_OK; + FlowSubscriptions subscriptions = {0}; + Verification verificationData; + unsigned int timeout = SERVER_RESPONSE_TIMEOUT; + unsigned int sleepTime = SLEEP_COUNT; + OBJECT_T flowObjects[] = + { + flowObject, + flowAccessObject, + }; + + if (deviceName == NULL || deviceType == NULL || fcap == NULL || licenseeSecret == NULL) + { + LOG(LOG_ERR, "Null parameters passed to %s()", __func__); + return PROVISION_FAIL; + } + + LOG(LOG_INFO, "Provisioning device with following details:\n" + "\n%-15s\t = %s\n%-15s\t = %s\n%-15s\t = %d\n%-15s\t = %s\n%-15s\t = %s", "Device Name", + deviceName, "Device Type", deviceType, "Licensee ID", licenseeID, "FCAP", fcap, + "Licensee Secret", licenseeSecret); + + if (!DefineObjectsAtClient(session, flowObjects, ARRAY_SIZE(flowObjects))) + { + LOG(LOG_ERR, "Failed to define Flow objects"); + return PROVISION_FAIL; + } + + if(IsGatewayDeviceProvisioned()) + { + return ALREADY_PROVISIONED; + } + + if (!PopulateFlowObject(session, deviceName, deviceType, licenseeID, fcap)) + { + LOG(LOG_ERR, "Failed to populate flow object with device type, licensee id and fcap"); + return PROVISION_FAIL; + } + + memset(&verificationData, 0, sizeof(Verification)); + verificationData.waitForServerResponse = true; + verificationData.hasChallenge = false; + verificationData.hasIterations = false; + verificationData.verifyLicensee = false; + verificationData.isProvisionSuccess = false; + + if (!SubscribeToFlowObjects(session, &subscriptions, &verificationData)) + { + LOG(LOG_ERR, "Failed to subscribe flow and flow access objects"); + return PROVISION_FAIL; + } + + LOG(LOG_INFO, "Waiting for responses from FlowCloud server..."); + + while(verificationData.waitForServerResponse && --timeout) + { + AwaClientSession_Process(session, IPC_TIMEOUT); + AwaClientSession_DispatchCallbacks(session); + + if (verificationData.verifyLicensee) + { + if (PerformFlowLicenseeVerification(session, &verificationData, licenseeSecret)) + { + verificationData.verifyLicensee = false; + } + } + sleep(1); + } + + if (!timeout) + { + LOG(LOG_ERR, "No response within timeout"); + } + + // FIXME: Temporary code until status resource is removed from FlowObject so we only get one + // change notification before canceling the subscription. + // Right now Message IDs aren't used in IPC, so it is possible to get messages out of order, + // causing the application to parse a response it is not expecting. + LOG(LOG_INFO, "Waiting for any residual notifications..."); + while(sleepTime-- > 0) + { + AwaClientSession_Process(session, IPC_TIMEOUT); + AwaClientSession_DispatchCallbacks(session); + sleep(1); + } + + // Clean up + UnSubscribeFromFlowObjects(session, &subscriptions); + if (verificationData.challenge.Data != NULL) + { + free(verificationData.challenge.Data); + } + + if (verificationData.licenseeHash.Data != NULL) + { + free(verificationData.licenseeHash.Data); + } + + if (!verificationData.isProvisionSuccess) + { + return PROVISION_FAIL; + } + + if (!SaveFlowCloudAccessDetails()) + { + LOG(LOG_ERR, "Failed to save flow cloud access details"); + } + return PROVISION_OK; } bool IsGatewayDeviceProvisioned(void) { - LOG(LOG_INFO, "Checking whether Gateway device is provisioned"); - if (DoesObjectExist(session, Lwm2mObjectId_FlowAccess, OBJECT_INSTANCE_ID)) - { - LOG(LOG_INFO, "Provisioned"); - return true; - } - else - { - LOG(LOG_INFO, "Not Provisioned"); - return false; - } + LOG(LOG_INFO, "Checking whether Gateway device is provisioned"); + if (DoesObjectExist(session, Lwm2mObjectId_FlowAccess, OBJECT_INSTANCE_ID)) + { + LOG(LOG_INFO, "Provisioned"); + return true; + } + else + { + LOG(LOG_INFO, "Not Provisioned"); + return false; + } } void ReleaseSession() { - LOG(LOG_INFO, "Disconnecting session with lwm2m client"); - - if (session == NULL) - { - return; - } - - if (AwaClientSession_Disconnect(session) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to disconnect session"); - } - - if (AwaClientSession_Free(&session) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free session"); - } + LOG(LOG_INFO, "Disconnecting session with lwm2m client"); + + if (session == NULL) + { + return; + } + + if (AwaClientSession_Disconnect(session) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to disconnect session"); + } + + if (AwaClientSession_Free(&session) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free session"); + } } diff --git a/src/device_manager.h b/src/device_manager.h index 112bc32..907e831 100644 --- a/src/device_manager.h +++ b/src/device_manager.h @@ -49,9 +49,9 @@ */ typedef enum { - PROVISION_OK, - PROVISION_FAIL, - ALREADY_PROVISIONED, + PROVISION_OK, + PROVISION_FAIL, + ALREADY_PROVISIONED, }ProvisionStatus; /** @@ -59,11 +59,11 @@ typedef enum */ typedef struct { - //! \{ - char deviceType[MAX_STR_SIZE]; - int licenseeID; - char fcap[MAX_STR_SIZE]; - //! \} + //! \{ + char deviceType[MAX_STR_SIZE]; + int licenseeID; + char fcap[MAX_STR_SIZE]; + //! \} }ProvisioningInfo; /** @@ -97,7 +97,7 @@ bool EstablishSession(); 2 for ALREADY_PROVISIONED */ ProvisionStatus ProvisionGatewayDevice(const char *deviceName, const char *deviceType, - int licenseeID, const char *fcap, const char *licenseeSecret); + int licenseeID, const char *fcap, const char *licenseeSecret); /** * @brief Check whether gateway device is already provisioned or not. @@ -129,7 +129,7 @@ void GetClientList(json_object *respObj); 2 for ALREADY_PROVISIONED */ ProvisionStatus ProvisionConstrainedDevice(const char *clientID, const char *fcap, - const char *deviceType, int licenseeID, const char *parentID); + const char *deviceType, int licenseeID, const char *parentID); /** * @brief Check if constrained device is provisioned or not @@ -138,4 +138,4 @@ ProvisionStatus ProvisionConstrainedDevice(const char *clientID, const char *fca */ bool IsConstrainedDeviceProvisioned(const char* clientID); -#endif /* DEVICE_MANAGER_H */ +#endif /* DEVICE_MANAGER_H */ diff --git a/src/device_manager_ubus.c b/src/device_manager_ubus.c index ac7322e..9a65b36 100644 --- a/src/device_manager_ubus.c +++ b/src/device_manager_ubus.c @@ -53,26 +53,26 @@ * Provision device arguments enum. */ enum { - ARG_DEVICE_NAME, - ARG_DEVICE_TYPE, - ARG_LICENSEE_ID, - ARG_FCAP, - ARG_LICENSEE_SECRET, - PROVISION_GATEWAY_DEVICE_MAX + ARG_DEVICE_NAME, + ARG_DEVICE_TYPE, + ARG_LICENSEE_ID, + ARG_FCAP, + ARG_LICENSEE_SECRET, + PROVISION_GATEWAY_DEVICE_MAX }; enum { - ARG_CONSTRAINED_CLIENT_ID, - ARG_CONSTRAINED_DEVICE_TYPE, - ARG_CONSTRAINED_LICENSEE_ID, - ARG_CONSTRAINED_FCAP, - ARG_CONSTRAINED_PARENT_ID, - PROVISION_CONSTRAINED_DEVICE_MAX + ARG_CONSTRAINED_CLIENT_ID, + ARG_CONSTRAINED_DEVICE_TYPE, + ARG_CONSTRAINED_LICENSEE_ID, + ARG_CONSTRAINED_FCAP, + ARG_CONSTRAINED_PARENT_ID, + PROVISION_CONSTRAINED_DEVICE_MAX }; enum { - ARG_CLIENT_ID, - IS_CONSTRAINED_DEVICE_PROVISIONED_MAX + ARG_CLIENT_ID, + IS_CONSTRAINED_DEVICE_PROVISIONED_MAX }; /*************************************************************************************************** @@ -84,10 +84,10 @@ enum { */ typedef struct { - //! \{ - const char *logFile; - unsigned int debugLevel; - //! \} + //! \{ + const char *logFile; + unsigned int debugLevel; + //! \} } CmdOpts; /*************************************************************************************************** @@ -97,29 +97,29 @@ typedef struct /** Provision gateway device arguments and their type. */ static const struct blobmsg_policy provisionGatewayDevicePolicy[PROVISION_GATEWAY_DEVICE_MAX] = { - [ARG_DEVICE_NAME] = {.name = "device_name", .type = BLOBMSG_TYPE_STRING}, - [ARG_DEVICE_TYPE] = {.name = "device_type", .type = BLOBMSG_TYPE_STRING}, - [ARG_LICENSEE_ID] = {.name = "licensee_id", .type = BLOBMSG_TYPE_INT32}, - [ARG_FCAP] = {.name = "fcap", .type = BLOBMSG_TYPE_STRING}, - [ARG_LICENSEE_SECRET] = {.name = "licensee_secret", .type = BLOBMSG_TYPE_STRING}, + [ARG_DEVICE_NAME] = {.name = "device_name", .type = BLOBMSG_TYPE_STRING}, + [ARG_DEVICE_TYPE] = {.name = "device_type", .type = BLOBMSG_TYPE_STRING}, + [ARG_LICENSEE_ID] = {.name = "licensee_id", .type = BLOBMSG_TYPE_INT32}, + [ARG_FCAP] = {.name = "fcap", .type = BLOBMSG_TYPE_STRING}, + [ARG_LICENSEE_SECRET] = {.name = "licensee_secret", .type = BLOBMSG_TYPE_STRING}, }; /** Provision constrained device arguments and their type. */ static const struct blobmsg_policy - provisionConstrainedDevicePolicy[PROVISION_CONSTRAINED_DEVICE_MAX] = + provisionConstrainedDevicePolicy[PROVISION_CONSTRAINED_DEVICE_MAX] = { - [ARG_CONSTRAINED_CLIENT_ID] = {.name = "client_id", .type = BLOBMSG_TYPE_STRING}, - [ARG_CONSTRAINED_DEVICE_TYPE] = {.name = "device_type", .type = BLOBMSG_TYPE_STRING}, - [ARG_CONSTRAINED_LICENSEE_ID] = {.name = "licensee_id", .type = BLOBMSG_TYPE_INT32}, - [ARG_CONSTRAINED_FCAP] = {.name = "fcap", .type = BLOBMSG_TYPE_STRING}, - [ARG_CONSTRAINED_PARENT_ID] = {.name = "parent_id", .type = BLOBMSG_TYPE_STRING} + [ARG_CONSTRAINED_CLIENT_ID] = {.name = "client_id", .type = BLOBMSG_TYPE_STRING}, + [ARG_CONSTRAINED_DEVICE_TYPE] = {.name = "device_type", .type = BLOBMSG_TYPE_STRING}, + [ARG_CONSTRAINED_LICENSEE_ID] = {.name = "licensee_id", .type = BLOBMSG_TYPE_INT32}, + [ARG_CONSTRAINED_FCAP] = {.name = "fcap", .type = BLOBMSG_TYPE_STRING}, + [ARG_CONSTRAINED_PARENT_ID] = {.name = "parent_id", .type = BLOBMSG_TYPE_STRING} }; /** IsConstrainedDeviceProvisioned arguments and their type. */ static const struct blobmsg_policy - isConstrainedDeviceProvisionedPolicy[IS_CONSTRAINED_DEVICE_PROVISIONED_MAX] = + isConstrainedDeviceProvisionedPolicy[IS_CONSTRAINED_DEVICE_PROVISIONED_MAX] = { - [ARG_CLIENT_ID] = {.name = "client_id", .type = BLOBMSG_TYPE_STRING}, + [ARG_CLIENT_ID] = {.name = "client_id", .type = BLOBMSG_TYPE_STRING}, }; /*************************************************************************************************** @@ -129,174 +129,168 @@ static const struct blobmsg_policy //! \{ static void PrintUsage(const char *program) { - printf("Usage: %s [options]\n\n" - " -l : Log filename\n" - " -v : Debug level from 1 to 5\n" - " fatal(1), error(2), warning(3), info(4), debug(5)\n" - " default is info\n" - " -h : Print help and exit\n\n", - program); + printf("Usage: %s [options]\n\n" + " -l : Log filename\n" + " -v : Debug level from 1 to 5\n" + " fatal(1), error(2), warning(3), info(4), debug(5)\n" + " default is info\n" + " -h : Print help and exit\n\n", + program); } static int ParseCommandArgs(int argc, char *argv[], CmdOpts *cmdOpts) { - int opt, tmp; - opterr = 0; - - /* default values */ - cmdOpts->logFile = NULL; - cmdOpts->debugLevel = LOG_INFO; - - while (1) - { - opt = getopt(argc, argv, "l:v:"); - if (opt == -1) - { - break; - } - - switch (opt) - { - case 'l': - cmdOpts->logFile = optarg; - break; - case 'v': - tmp = strtoul(optarg, NULL, 0); - if (tmp >= LOG_FATAL && tmp <= LOG_DBG) - { - cmdOpts->debugLevel = tmp; - } - else - { - LOG(LOG_ERR, "Invalid debug level"); - PrintUsage(argv[0]); - return -1; - } - break; - case 'h': - PrintUsage(argv[0]); - return 0; - default: - PrintUsage(argv[0]); - return -1; - } - } - return 1; + int opt, tmp; + opterr = 0; + + /* default values */ + cmdOpts->logFile = NULL; + cmdOpts->debugLevel = LOG_INFO; + + while (1) + { + opt = getopt(argc, argv, "l:v:"); + if (opt == -1) + { + break; + } + + switch (opt) + { + case 'l': + cmdOpts->logFile = optarg; + break; + case 'v': + tmp = strtoul(optarg, NULL, 0); + if (tmp >= LOG_FATAL && tmp <= LOG_DBG) + { + cmdOpts->debugLevel = tmp; + } + else + { + LOG(LOG_ERR, "Invalid debug level"); + PrintUsage(argv[0]); + return -1; + } + break; + case 'h': + PrintUsage(argv[0]); + return 0; + default: + PrintUsage(argv[0]); + return -1; + } + } + return 1; } static int ProvisionGatewayDeviceHandler(struct ubus_context *ctx, struct ubus_object *obj, - struct ubus_request_data *req, const char *method, struct blob_attr *msg) + struct ubus_request_data *req, const char *method, struct blob_attr *msg) { - struct blob_attr *args[PROVISION_GATEWAY_DEVICE_MAX]; - struct blob_buf b = {0}; + struct blob_attr *args[PROVISION_GATEWAY_DEVICE_MAX]; + struct blob_buf b = {0}; - blobmsg_parse(provisionGatewayDevicePolicy, PROVISION_GATEWAY_DEVICE_MAX, args, blob_data(msg), - blob_len(msg)); - if (!args[ARG_DEVICE_NAME] || !args[ARG_DEVICE_TYPE] || !args[ARG_LICENSEE_ID] || - !args[ARG_FCAP] || !args[ARG_LICENSEE_SECRET]) - return UBUS_STATUS_INVALID_ARGUMENT; + blobmsg_parse(provisionGatewayDevicePolicy, PROVISION_GATEWAY_DEVICE_MAX, args, blob_data(msg), blob_len(msg)); + if (!args[ARG_DEVICE_NAME] || !args[ARG_DEVICE_TYPE] || !args[ARG_LICENSEE_ID] || !args[ARG_FCAP] || !args[ARG_LICENSEE_SECRET]) + return UBUS_STATUS_INVALID_ARGUMENT; - char *deviceName = blobmsg_get_string(args[ARG_DEVICE_NAME]); - char *deviceType = blobmsg_get_string(args[ARG_DEVICE_TYPE]); - char *fcap = blobmsg_get_string(args[ARG_FCAP]); - int licenseeID = blobmsg_get_u32(args[ARG_LICENSEE_ID]); - char *licenseeSecret = blobmsg_get_string(args[ARG_LICENSEE_SECRET]); + char *deviceName = blobmsg_get_string(args[ARG_DEVICE_NAME]); + char *deviceType = blobmsg_get_string(args[ARG_DEVICE_TYPE]); + char *fcap = blobmsg_get_string(args[ARG_FCAP]); + int licenseeID = blobmsg_get_u32(args[ARG_LICENSEE_ID]); + char *licenseeSecret = blobmsg_get_string(args[ARG_LICENSEE_SECRET]); - if (!deviceName || !deviceType || !fcap || !licenseeSecret) - return UBUS_STATUS_UNKNOWN_ERROR; + if (!deviceName || !deviceType || !fcap || !licenseeSecret) + return UBUS_STATUS_UNKNOWN_ERROR; - ProvisionStatus status = ProvisionGatewayDevice(deviceName, deviceType, licenseeID, fcap, - licenseeSecret); + ProvisionStatus status = ProvisionGatewayDevice(deviceName, deviceType, licenseeID, fcap, licenseeSecret); - blob_buf_init(&b, 0); - blobmsg_add_u32(&b, "provision_status", status); - ubus_send_reply(ctx, req, b.head); - blob_buf_free(&b); + blob_buf_init(&b, 0); + blobmsg_add_u32(&b, "provision_status", status); + ubus_send_reply(ctx, req, b.head); + blob_buf_free(&b); - return UBUS_STATUS_OK; + return UBUS_STATUS_OK; } static int IsGatewayDeviceProvisionedHandler(struct ubus_context *ctx, struct ubus_object *obj, - struct ubus_request_data *req, const char *method, struct blob_attr *msg) + struct ubus_request_data *req, const char *method, struct blob_attr *msg) { - struct blob_buf b = {0}; - blob_buf_init(&b, 0); - bool ret = IsGatewayDeviceProvisioned(); - blobmsg_add_u8(&b, "provision_status", ret); - ubus_send_reply(ctx, req, b.head); - blob_buf_free(&b); - return UBUS_STATUS_OK; + struct blob_buf b = {0}; + blob_buf_init(&b, 0); + bool ret = IsGatewayDeviceProvisioned(); + blobmsg_add_u8(&b, "provision_status", ret); + ubus_send_reply(ctx, req, b.head); + blob_buf_free(&b); + return UBUS_STATUS_OK; } static int GetClientListHandler(struct ubus_context *ctx, struct ubus_object *obj, - struct ubus_request_data *req, const char *method, struct blob_attr *msg) + struct ubus_request_data *req, const char *method, struct blob_attr *msg) { - struct blob_buf b = {0}; - blob_buf_init(&b, 0); - json_object *respObj = json_object_new_object(); - GetClientList(respObj); - blobmsg_add_json_from_string(&b, json_object_get_string(respObj)); - ubus_send_reply(ctx, req, b.head); - blob_buf_free(&b); - json_object_put(respObj); - return UBUS_STATUS_OK; + struct blob_buf b = {0}; + blob_buf_init(&b, 0); + json_object *respObj = json_object_new_object(); + GetClientList(respObj); + blobmsg_add_json_from_string(&b, json_object_get_string(respObj)); + ubus_send_reply(ctx, req, b.head); + blob_buf_free(&b); + json_object_put(respObj); + return UBUS_STATUS_OK; } static int ProvisionConstrainedDeviceHandler(struct ubus_context *ctx, struct ubus_object *obj, - struct ubus_request_data *req, const char *method, struct blob_attr *msg) + struct ubus_request_data *req, const char *method, struct blob_attr *msg) { - struct blob_attr *args[PROVISION_CONSTRAINED_DEVICE_MAX]; - struct blob_buf b = {0}; - - blobmsg_parse(provisionConstrainedDevicePolicy, PROVISION_CONSTRAINED_DEVICE_MAX, args, - blob_data(msg), blob_len(msg)); - if (!args[ARG_CONSTRAINED_DEVICE_TYPE] || !args[ARG_CONSTRAINED_LICENSEE_ID] || - !args[ARG_CONSTRAINED_CLIENT_ID] || !args[ARG_CONSTRAINED_FCAP] || - !args[ARG_CONSTRAINED_PARENT_ID]) - return UBUS_STATUS_INVALID_ARGUMENT; - - char *deviceType = blobmsg_get_string(args[ARG_CONSTRAINED_DEVICE_TYPE]); - int licenseeID = blobmsg_get_u32(args[ARG_CONSTRAINED_LICENSEE_ID]); - char *clientID = blobmsg_get_string(args[ARG_CONSTRAINED_CLIENT_ID]); - char *fcap = blobmsg_get_string(args[ARG_CONSTRAINED_FCAP]); - char *parentID = blobmsg_get_string(args[ARG_CONSTRAINED_PARENT_ID]); - - if (!deviceType || !clientID || !fcap || !parentID) - return UBUS_STATUS_UNKNOWN_ERROR; - - ProvisionStatus status = ProvisionConstrainedDevice(clientID, fcap, deviceType, licenseeID, - parentID); - - blob_buf_init(&b, 0); - blobmsg_add_u32(&b, "status", status); - ubus_send_reply(ctx, req, b.head); - blob_buf_free(&b); - - return UBUS_STATUS_OK; + struct blob_attr *args[PROVISION_CONSTRAINED_DEVICE_MAX]; + struct blob_buf b = {0}; + + blobmsg_parse(provisionConstrainedDevicePolicy, PROVISION_CONSTRAINED_DEVICE_MAX, args, blob_data(msg), blob_len(msg)); + if (!args[ARG_CONSTRAINED_DEVICE_TYPE] || !args[ARG_CONSTRAINED_LICENSEE_ID] || + !args[ARG_CONSTRAINED_CLIENT_ID] || !args[ARG_CONSTRAINED_FCAP] || + !args[ARG_CONSTRAINED_PARENT_ID]) + return UBUS_STATUS_INVALID_ARGUMENT; + + char *deviceType = blobmsg_get_string(args[ARG_CONSTRAINED_DEVICE_TYPE]); + int licenseeID = blobmsg_get_u32(args[ARG_CONSTRAINED_LICENSEE_ID]); + char *clientID = blobmsg_get_string(args[ARG_CONSTRAINED_CLIENT_ID]); + char *fcap = blobmsg_get_string(args[ARG_CONSTRAINED_FCAP]); + char *parentID = blobmsg_get_string(args[ARG_CONSTRAINED_PARENT_ID]); + + if (!deviceType || !clientID || !fcap || !parentID) + return UBUS_STATUS_UNKNOWN_ERROR; + + ProvisionStatus status = ProvisionConstrainedDevice(clientID, fcap, deviceType, licenseeID, parentID); + + blob_buf_init(&b, 0); + blobmsg_add_u32(&b, "status", status); + ubus_send_reply(ctx, req, b.head); + blob_buf_free(&b); + + return UBUS_STATUS_OK; } static int IsConstrainedDeviceProvisionedHandler(struct ubus_context *ctx, struct ubus_object *obj, - struct ubus_request_data *req, const char *method, struct blob_attr *msg) + struct ubus_request_data *req, const char *method, struct blob_attr *msg) { - struct blob_attr *args[IS_CONSTRAINED_DEVICE_PROVISIONED_MAX]; - struct blob_buf b = {0}; - - blobmsg_parse(isConstrainedDeviceProvisionedPolicy, IS_CONSTRAINED_DEVICE_PROVISIONED_MAX, args, - blob_data(msg), blob_len(msg)); - if (!args[ARG_CLIENT_ID]) - return UBUS_STATUS_INVALID_ARGUMENT; - char *clientID = blobmsg_get_string(args[ARG_CLIENT_ID]); - if (!clientID) - return UBUS_STATUS_UNKNOWN_ERROR; - - bool ret = IsConstrainedDeviceProvisioned(clientID); - - blob_buf_init(&b, 0); - blobmsg_add_u8(&b, "provision_status", ret); - ubus_send_reply(ctx, req, b.head); - blob_buf_free(&b); - return UBUS_STATUS_OK; + struct blob_attr *args[IS_CONSTRAINED_DEVICE_PROVISIONED_MAX]; + struct blob_buf b = {0}; + + blobmsg_parse(isConstrainedDeviceProvisionedPolicy, IS_CONSTRAINED_DEVICE_PROVISIONED_MAX, args, blob_data(msg), blob_len(msg)); + if (!args[ARG_CLIENT_ID]) + return UBUS_STATUS_INVALID_ARGUMENT; + char *clientID = blobmsg_get_string(args[ARG_CLIENT_ID]); + if (!clientID) + return UBUS_STATUS_UNKNOWN_ERROR; + + bool ret = IsConstrainedDeviceProvisioned(clientID); + + blob_buf_init(&b, 0); + blobmsg_add_u8(&b, "provision_status", ret); + ubus_send_reply(ctx, req, b.head); + blob_buf_free(&b); + return UBUS_STATUS_OK; } //! \} @@ -305,65 +299,61 @@ static int IsConstrainedDeviceProvisionedHandler(struct ubus_context *ctx, struc */ int main(int argc, char **argv) { - int ret; - CmdOpts cmdOpts; - FILE *logFile = NULL; - struct ubus_context *ctx; - const char *path = NULL; - - struct ubus_method flowDeviceManagerMethods[] = - { - UBUS_METHOD("provision_gateway_device", ProvisionGatewayDeviceHandler, - provisionGatewayDevicePolicy), - UBUS_METHOD("provision_constrained_device", ProvisionConstrainedDeviceHandler, - provisionConstrainedDevicePolicy), - UBUS_METHOD("is_constrained_device_provisioned", IsConstrainedDeviceProvisionedHandler, - isConstrainedDeviceProvisionedPolicy), - UBUS_METHOD_NOARG("is_gateway_device_provisioned", IsGatewayDeviceProvisionedHandler), - UBUS_METHOD_NOARG("get_client_list", GetClientListHandler) - }; - struct ubus_object_type flowDeviceManagerObjectType = \ - UBUS_OBJECT_TYPE("device_manager", flowDeviceManagerMethods); - struct ubus_object ubusObject = - { - .type = &flowDeviceManagerObjectType, - .name = flowDeviceManagerObjectType.name, - .methods = flowDeviceManagerObjectType.methods, - .n_methods = flowDeviceManagerObjectType.n_methods - }; - - ret = ParseCommandArgs(argc, argv, &cmdOpts); - if (ret <= 0) - return ret; - if (cmdOpts.logFile) - logFile = SetLogFile(cmdOpts.logFile); - SetDebugLevel(cmdOpts.debugLevel); - - if (!EstablishSession()) - return -1; - - uloop_init(); - ctx = ubus_connect(path); - if (!ctx) - { - LOG(LOG_ERR, "Failed to connect to ubus"); - return -1; - } - if (ret = ubus_add_object(ctx, &ubusObject)) - { - LOG(LOG_ERR, "Couldn't add object : %s", ubus_strerror(ret)); - ubus_free(ctx); - return -1; - } - ubus_add_uloop(ctx); - uloop_run(); - - ReleaseSession(); - if (logFile) - fclose(logFile); - - ubus_remove_object(ctx, &ubusObject); - ubus_free(ctx); - uloop_done(); - return 0; + int ret; + CmdOpts cmdOpts; + FILE *logFile = NULL; + struct ubus_context *ctx; + const char *path = NULL; + + struct ubus_method flowDeviceManagerMethods[] = + { + UBUS_METHOD("provision_gateway_device", ProvisionGatewayDeviceHandler, provisionGatewayDevicePolicy), + UBUS_METHOD("provision_constrained_device", ProvisionConstrainedDeviceHandler, provisionConstrainedDevicePolicy), + UBUS_METHOD("is_constrained_device_provisioned", IsConstrainedDeviceProvisionedHandler, isConstrainedDeviceProvisionedPolicy), + UBUS_METHOD_NOARG("is_gateway_device_provisioned", IsGatewayDeviceProvisionedHandler), + UBUS_METHOD_NOARG("get_client_list", GetClientListHandler) + }; + struct ubus_object_type flowDeviceManagerObjectType = UBUS_OBJECT_TYPE("device_manager", flowDeviceManagerMethods); + struct ubus_object ubusObject = + { + .type = &flowDeviceManagerObjectType, + .name = flowDeviceManagerObjectType.name, + .methods = flowDeviceManagerObjectType.methods, + .n_methods = flowDeviceManagerObjectType.n_methods + }; + + ret = ParseCommandArgs(argc, argv, &cmdOpts); + if (ret <= 0) + return ret; + if (cmdOpts.logFile) + logFile = SetLogFile(cmdOpts.logFile); + SetDebugLevel(cmdOpts.debugLevel); + + if (!EstablishSession()) + return -1; + + uloop_init(); + ctx = ubus_connect(path); + if (!ctx) + { + LOG(LOG_ERR, "Failed to connect to ubus"); + return -1; + } + if (ret = ubus_add_object(ctx, &ubusObject)) + { + LOG(LOG_ERR, "Couldn't add object : %s", ubus_strerror(ret)); + ubus_free(ctx); + return -1; + } + ubus_add_uloop(ctx); + uloop_run(); + + ReleaseSession(); + if (logFile) + fclose(logFile); + + ubus_remove_object(ctx, &ubusObject); + ubus_free(ctx); + uloop_done(); + return 0; } diff --git a/src/fdm_common.h b/src/fdm_common.h index a86e886..27b8d79 100644 --- a/src/fdm_common.h +++ b/src/fdm_common.h @@ -52,65 +52,65 @@ #define MAKE_RESOURCE_PATH(path, objectId, resourceId) \ - AwaAPI_MakeResourcePath(path, URL_PATH_SIZE, objectId, OBJECT_INSTANCE_ID, resourceId) + AwaAPI_MakeResourcePath(path, URL_PATH_SIZE, objectId, OBJECT_INSTANCE_ID, resourceId) #define MAKE_FLOW_OBJECT_RESOURCE_PATH(path, resourceId) \ - MAKE_RESOURCE_PATH(path, Lwm2mObjectId_FlowObject, resourceId) + MAKE_RESOURCE_PATH(path, Lwm2mObjectId_FlowObject, resourceId) #define MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(path, resourceId) \ - MAKE_RESOURCE_PATH(path, Lwm2mObjectId_FlowAccess, resourceId) + MAKE_RESOURCE_PATH(path, Lwm2mObjectId_FlowAccess, resourceId) #define MAKE_FLOW_OBJECT_INSTANCE_PATH(path) \ - AwaAPI_MakeObjectInstancePath(path, URL_PATH_SIZE, Lwm2mObjectId_FlowObject, \ - OBJECT_INSTANCE_ID) + AwaAPI_MakeObjectInstancePath(path, URL_PATH_SIZE, Lwm2mObjectId_FlowObject, \ + OBJECT_INSTANCE_ID) #define MAKE_FLOW_ACCESS_OBJECT_PATH(path) \ - AwaAPI_MakeObjectPath(path, URL_PATH_SIZE, Lwm2mObjectId_FlowAccess) + AwaAPI_MakeObjectPath(path, URL_PATH_SIZE, Lwm2mObjectId_FlowAccess) //! \} /** * lwm2m object ids enum. */ typedef enum { - Lwm2mObjectId_DeviceObject = 3, - Lwm2mObjectId_FlowObject = 20000, - Lwm2mObjectId_FlowAccess + Lwm2mObjectId_DeviceObject = 3, + Lwm2mObjectId_FlowObject = 20000, + Lwm2mObjectId_FlowAccess } Lwm2mObjectId; /** * Flow object resources enum. */ typedef enum { - FlowObjectResourceId_DeviceId, - FlowObjectResourceId_ParentId, - FlowObjectResourceId_DeviceType, - FlowObjectResourceId_DeviceName, - FlowObjectResourceId_Description, - FlowObjectResourceId_Fcap, - FlowObjectResourceId_LicenseeId, - FlowObjectResourceId_LicenseeChallenge, - FlowObjectResourceId_HashIterations, - FlowObjectResourceId_LicenseeHash, - FlowObjectResourceId_Status + FlowObjectResourceId_DeviceId, + FlowObjectResourceId_ParentId, + FlowObjectResourceId_DeviceType, + FlowObjectResourceId_DeviceName, + FlowObjectResourceId_Description, + FlowObjectResourceId_Fcap, + FlowObjectResourceId_LicenseeId, + FlowObjectResourceId_LicenseeChallenge, + FlowObjectResourceId_HashIterations, + FlowObjectResourceId_LicenseeHash, + FlowObjectResourceId_Status } FlowObjectResourceId; /** * Flow access resources enum. */ typedef enum { - FlowAccessResourceId_Url, - FlowAccessResourceId_CustomerKey, - FlowAccessResourceId_CustomerSecret, - FlowAccessResourceId_RememberMeToken, - FlowAccessResourceId_RememberMeTokenExpiry + FlowAccessResourceId_Url, + FlowAccessResourceId_CustomerKey, + FlowAccessResourceId_CustomerSecret, + FlowAccessResourceId_RememberMeToken, + FlowAccessResourceId_RememberMeTokenExpiry } FlowAccessResourceId; /** * Device object resources enum */ typedef enum { - DeviceObjectResourceId_SerialNumber = 2, - DeviceObjectResourceId_SoftwareVersion = 19 + DeviceObjectResourceId_SerialNumber = 2, + DeviceObjectResourceId_SoftwareVersion = 19 } DeviceObjectResourceId; /** @@ -118,13 +118,13 @@ typedef enum { */ typedef struct { - //! \{ - AwaResourceID id; - const char *name; - AwaResourceType type; - bool isMandatory; - bool wantToSave; - //! \} + //! \{ + AwaResourceID id; + const char *name; + AwaResourceType type; + bool isMandatory; + bool wantToSave; + //! \} } RESOURCE_T; /** @@ -132,12 +132,12 @@ typedef struct */ typedef struct { - //! \{ - const char *name; - AwaObjectID id; - unsigned int numResources; - RESOURCE_T *resources; - //! \} + //! \{ + const char *name; + AwaObjectID id; + unsigned int numResources; + RESOURCE_T *resources; + //! \} } OBJECT_T; extern const OBJECT_T flowObject, flowAccessObject; @@ -146,10 +146,10 @@ extern const OBJECT_T flowObject, flowAccessObject; */ typedef struct { - //! \{ - AwaClientChangeSubscription *flowObjectChange; - AwaClientChangeSubscription *flowAccessObjectChange; - //! \} + //! \{ + AwaClientChangeSubscription *flowObjectChange; + AwaClientChangeSubscription *flowAccessObjectChange; + //! \} } FlowSubscriptions; /** @@ -157,16 +157,16 @@ typedef struct */ typedef struct { - //! \{ - AwaOpaque challenge; - AwaInteger iterations; - AwaOpaque licenseeHash; - bool hasChallenge; - bool hasIterations; - bool waitForServerResponse; - bool verifyLicensee; - bool isProvisionSuccess; - //! \} + //! \{ + AwaOpaque challenge; + AwaInteger iterations; + AwaOpaque licenseeHash; + bool hasChallenge; + bool hasIterations; + bool waitForServerResponse; + bool verifyLicensee; + bool isProvisionSuccess; + //! \} } Verification; -#endif /* FDM_COMMON_H */ +#endif /* FDM_COMMON_H */ diff --git a/src/fdm_get_client_list.c b/src/fdm_get_client_list.c index 15bd172..0823c90 100644 --- a/src/fdm_get_client_list.c +++ b/src/fdm_get_client_list.c @@ -59,63 +59,60 @@ //! \{ static void ListClients(const AwaServerSession *session, json_object *respObj) { - AwaError error; - json_object *listObj = json_object_new_array(); - AwaServerListClientsOperation *operation = AwaServerListClientsOperation_New(session); - if (operation == NULL) - { - LOG(LOG_ERR, "Failed to create new ListClientsOperation"); - json_object_put(listObj); - return; - } - error = AwaServerListClientsOperation_Perform(operation, LIST_CLIENTS_OPERATION_TIMEOUT); - if (error == AwaError_Success) - { - AwaClientIterator *clientIterator = - AwaServerListClientsOperation_NewClientIterator(operation); - if (clientIterator != NULL) - { - while(AwaClientIterator_Next(clientIterator)) - { - const char *clientID = AwaClientIterator_GetClientID(clientIterator); + AwaError error; + json_object *listObj = json_object_new_array(); + AwaServerListClientsOperation *operation = AwaServerListClientsOperation_New(session); + if (operation == NULL) + { + LOG(LOG_ERR, "Failed to create new ListClientsOperation"); + json_object_put(listObj); + return; + } + error = AwaServerListClientsOperation_Perform(operation, LIST_CLIENTS_OPERATION_TIMEOUT); + if (error == AwaError_Success) + { + AwaClientIterator *clientIterator = AwaServerListClientsOperation_NewClientIterator(operation); + if (clientIterator != NULL) + { + while(AwaClientIterator_Next(clientIterator)) + { + const char *clientID = AwaClientIterator_GetClientID(clientIterator); - json_bool provisionStatus = IsDeviceProvisioned(session, clientID) ? 1 : 0; - json_object *clientObj = json_object_new_object(); - json_object_object_add(clientObj, "clientId", json_object_new_string(clientID)); - json_object_object_add(clientObj, "is_device_provisioned", - json_object_new_boolean(provisionStatus)); - json_object_array_add(listObj, clientObj); + json_bool provisionStatus = IsDeviceProvisioned(session, clientID) ? 1 : 0; + json_object *clientObj = json_object_new_object(); + json_object_object_add(clientObj, "clientId", json_object_new_string(clientID)); + json_object_object_add(clientObj, "is_device_provisioned", json_object_new_boolean(provisionStatus)); + json_object_array_add(listObj, clientObj); - } - AwaClientIterator_Free(&clientIterator); - } - else - { - LOG(LOG_ERR, "Failed to create new list clients iterator"); - } - } - else - { - LOG(LOG_ERR, "Failed to perform list clients operation\nerror: %s", - AwaError_ToString(error)); - } + } + AwaClientIterator_Free(&clientIterator); + } + else + { + LOG(LOG_ERR, "Failed to create new list clients iterator"); + } + } + else + { + LOG(LOG_ERR, "Failed to perform list clients operation\nerror: %s", AwaError_ToString(error)); + } - if (AwaServerListClientsOperation_Free(&operation) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to free list clients operation"); - } + if (AwaServerListClientsOperation_Free(&operation) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to free list clients operation"); + } - json_object_object_add(respObj, "clients", listObj); + json_object_object_add(respObj, "clients", listObj); } //! \} void GetClientList(json_object *respObj) { - AwaServerSession *session = NULL; - session = Server_EstablishSession(SERVER_ADDRESS, SERVER_PORT); - if (session != NULL) - { - ListClients(session, respObj); - Server_ReleaseSession(&session); - } + AwaServerSession *session = NULL; + session = Server_EstablishSession(SERVER_ADDRESS, SERVER_PORT); + if (session != NULL) + { + ListClients(session, respObj); + Server_ReleaseSession(&session); + } } diff --git a/src/fdm_hmac.c b/src/fdm_hmac.c index eec632d..91dc548 100644 --- a/src/fdm_hmac.c +++ b/src/fdm_hmac.c @@ -64,10 +64,10 @@ #define PUT_UINT32(n,b,i) \ { \ - (b)[(i) ] = (uint8_t) ( (n) >> 24 ); \ - (b)[(i) + 1] = (uint8_t) ( (n) >> 16 ); \ - (b)[(i) + 2] = (uint8_t) ( (n) >> 8 ); \ - (b)[(i) + 3] = (uint8_t) ( (n) ); \ + (b)[(i) ] = (uint8_t) ( (n) >> 24 ); \ + (b)[(i) + 1] = (uint8_t) ( (n) >> 16 ); \ + (b)[(i) + 2] = (uint8_t) ( (n) >> 8 ); \ + (b)[(i) + 3] = (uint8_t) ( (n) ); \ } @@ -77,10 +77,10 @@ typedef struct { - uint8_t Data[64]; - uint32_t DataLen; - uint32_t BitLen[2]; - uint32_t State[8]; + uint8_t Data[64]; + uint32_t DataLen; + uint32_t BitLen[2]; + uint32_t State[8]; } Sha256ContextType; /*************************************************************************************************** @@ -89,14 +89,14 @@ typedef struct static const uint32_t k[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; /*************************************************************************************************** @@ -105,121 +105,121 @@ static const uint32_t k[64] = static void Sha256_Transform(Sha256ContextType *context, uint8_t * data) { - uint32_t a,b,c,d,e,f,g,h,i,j,t1,t2,m[64]; - - for (i = 0, j = 0; i < 16; ++i, j += 4) - { - m[i] = (data[j] << 24) | (data[j+1] << 16) | (data[j+2] << 8) | (data[j+3]); - } - - for (; i < 64; i++) - { - m[i] = SIG1(m[i-2]) + m[i-7] + SIG0(m[i-15]) + m[i-16]; - } - - a = context->State[0]; - b = context->State[1]; - c = context->State[2]; - d = context->State[3]; - e = context->State[4]; - f = context->State[5]; - g = context->State[6]; - h = context->State[7]; - - for (i = 0; i < 64; i++) - { - t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; - t2 = EP0(a) + MAJ(a,b,c); - h = g; - g = f; - f = e; - e = d + t1; - d = c; - c = b; - b = a; - a = t1 + t2; - } - - context->State[0] += a; - context->State[1] += b; - context->State[2] += c; - context->State[3] += d; - context->State[4] += e; - context->State[5] += f; - context->State[6] += g; - context->State[7] += h; + uint32_t a,b,c,d,e,f,g,h,i,j,t1,t2,m[64]; + + for (i = 0, j = 0; i < 16; ++i, j += 4) + { + m[i] = (data[j] << 24) | (data[j+1] << 16) | (data[j+2] << 8) | (data[j+3]); + } + + for (; i < 64; i++) + { + m[i] = SIG1(m[i-2]) + m[i-7] + SIG0(m[i-15]) + m[i-16]; + } + + a = context->State[0]; + b = context->State[1]; + c = context->State[2]; + d = context->State[3]; + e = context->State[4]; + f = context->State[5]; + g = context->State[6]; + h = context->State[7]; + + for (i = 0; i < 64; i++) + { + t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; + t2 = EP0(a) + MAJ(a,b,c); + h = g; + g = f; + f = e; + e = d + t1; + d = c; + c = b; + b = a; + a = t1 + t2; + } + + context->State[0] += a; + context->State[1] += b; + context->State[2] += c; + context->State[3] += d; + context->State[4] += e; + context->State[5] += f; + context->State[6] += g; + context->State[7] += h; } static void Sha256_Init(Sha256ContextType *context) { - context->DataLen = 0; - context->BitLen[0] = 0; - context->BitLen[1] = 0; - context->State[0] = 0x6a09e667; - context->State[1] = 0xbb67ae85; - context->State[2] = 0x3c6ef372; - context->State[3] = 0xa54ff53a; - context->State[4] = 0x510e527f; - context->State[5] = 0x9b05688c; - context->State[6] = 0x1f83d9ab; - context->State[7] = 0x5be0cd19; + context->DataLen = 0; + context->BitLen[0] = 0; + context->BitLen[1] = 0; + context->State[0] = 0x6a09e667; + context->State[1] = 0xbb67ae85; + context->State[2] = 0x3c6ef372; + context->State[3] = 0xa54ff53a; + context->State[4] = 0x510e527f; + context->State[5] = 0x9b05688c; + context->State[6] = 0x1f83d9ab; + context->State[7] = 0x5be0cd19; } static void Sha256_Update(Sha256ContextType *context, const uint8_t *data, uint32_t dataLen) { - uint32_t i; - - for (i = 0; i < dataLen; i++) - { - context->Data[context->DataLen] = data[i]; - context->DataLen++; - if (context->DataLen == 64) - { - Sha256_Transform(context,context->Data); - DBL_INT_ADD(context->BitLen[0], context->BitLen[1], 512); - context->DataLen = 0; - } - } + uint32_t i; + + for (i = 0; i < dataLen; i++) + { + context->Data[context->DataLen] = data[i]; + context->DataLen++; + if (context->DataLen == 64) + { + Sha256_Transform(context,context->Data); + DBL_INT_ADD(context->BitLen[0], context->BitLen[1], 512); + context->DataLen = 0; + } + } } static void Sha256_Final(Sha256ContextType *context, uint8_t hash[]) { - uint32_t i; - - i = context->DataLen; - - // Pad whatever data is left in the buffer. - if (context->DataLen < 56) - { - context->Data[i++] = 0x80; - while (i < 56) - context->Data[i++] = 0x00; - } - else - { - context->Data[i++] = 0x80; - while (i < 64) - context->Data[i++] = 0x00; - - Sha256_Transform(context,context->Data); - memset(context->Data, 0, 56); - } - - // Append to the padding the total message's length in bits and transform. - DBL_INT_ADD(context->BitLen[0], context->BitLen[1], context->DataLen * 8); - PUT_UINT32(context->BitLen[0], context->Data, 60); - PUT_UINT32(context->BitLen[1], context->Data, 56); - Sha256_Transform(context, context->Data); - - // Copy result into output buffer - PUT_UINT32(context->State[0], hash, 0); - PUT_UINT32(context->State[1], hash, 4); - PUT_UINT32(context->State[2], hash, 8); - PUT_UINT32(context->State[3], hash, 12); - PUT_UINT32(context->State[4], hash, 16); - PUT_UINT32(context->State[5], hash, 20); - PUT_UINT32(context->State[6], hash, 24); - PUT_UINT32(context->State[7], hash, 28); + uint32_t i; + + i = context->DataLen; + + // Pad whatever data is left in the buffer. + if (context->DataLen < 56) + { + context->Data[i++] = 0x80; + while (i < 56) + context->Data[i++] = 0x00; + } + else + { + context->Data[i++] = 0x80; + while (i < 64) + context->Data[i++] = 0x00; + + Sha256_Transform(context,context->Data); + memset(context->Data, 0, 56); + } + + // Append to the padding the total message's length in bits and transform. + DBL_INT_ADD(context->BitLen[0], context->BitLen[1], context->DataLen * 8); + PUT_UINT32(context->BitLen[0], context->Data, 60); + PUT_UINT32(context->BitLen[1], context->Data, 56); + Sha256_Transform(context, context->Data); + + // Copy result into output buffer + PUT_UINT32(context->State[0], hash, 0); + PUT_UINT32(context->State[1], hash, 4); + PUT_UINT32(context->State[2], hash, 8); + PUT_UINT32(context->State[3], hash, 12); + PUT_UINT32(context->State[4], hash, 16); + PUT_UINT32(context->State[5], hash, 20); + PUT_UINT32(context->State[6], hash, 24); + PUT_UINT32(context->State[7], hash, 28); } //! @endcond @@ -231,10 +231,10 @@ static void Sha256_Final(Sha256ContextType *context, uint8_t hash[]) */ static void Sha256_ComputeHash(uint8_t hash[SHA256_HASH_LENGTH], const uint8_t *data, int dataLen) { - Sha256ContextType context; - Sha256_Init(&context); - Sha256_Update(&context,data, dataLen); - Sha256_Final(&context, hash); + Sha256ContextType context; + Sha256_Init(&context); + Sha256_Update(&context,data, dataLen); + Sha256_Final(&context, hash); } /** @@ -246,46 +246,46 @@ static void Sha256_ComputeHash(uint8_t hash[SHA256_HASH_LENGTH], const uint8_t * * @param[in] keyLen - length of key */ void HmacSha256_ComputeHash(uint8_t hash[SHA256_HASH_LENGTH], const uint8_t *data, int dataLen, - const uint8_t *key, int keyLen) + const uint8_t *key, int keyLen) { - uint8_t innerKeyPad[MAX_KEY_LENGTH]; - uint8_t outerKeyPad[MAX_KEY_LENGTH]; - uint8_t keyHash[SHA256_HASH_LENGTH]; - uint8_t innerHash[SHA256_HASH_LENGTH]; - uint8_t buffer[MAX_BUFFER_LENGTH]; - unsigned int i; - - // if key is longer than 64 bytes use the hash of the key as the key. - if (keyLen > MAX_KEY_LENGTH) - { - Sha256_ComputeHash(keyHash, key, keyLen); - key = keyHash; - keyLen = SHA256_HASH_LENGTH; - } - - // copy key to pad values, we will then XOR this with 0x36 and 0x5c respectively - memset(innerKeyPad, 0, sizeof(innerKeyPad)); - memset(outerKeyPad, 0, sizeof(outerKeyPad)); - memcpy(innerKeyPad, key, keyLen); - memcpy(outerKeyPad, key, keyLen); - - for (i = 0; i < MAX_KEY_LENGTH; i++) - { - innerKeyPad[i] ^= 0x36; - outerKeyPad[i] ^= 0x5c; - } - - // perform inner SHA256 - memset(buffer, 0x00, sizeof(buffer)); - memcpy(buffer, innerKeyPad, MAX_KEY_LENGTH); - memcpy(buffer + MAX_KEY_LENGTH, data, dataLen); - - Sha256_ComputeHash(innerHash, buffer, MAX_KEY_LENGTH + dataLen); - - // perform outer SHA256 - memset(buffer, 0x00, sizeof(buffer)); - memcpy(buffer, outerKeyPad, MAX_KEY_LENGTH); - memcpy(buffer + MAX_KEY_LENGTH, innerHash, SHA256_HASH_LENGTH); - - Sha256_ComputeHash(hash, buffer, MAX_KEY_LENGTH + SHA256_HASH_LENGTH); + uint8_t innerKeyPad[MAX_KEY_LENGTH]; + uint8_t outerKeyPad[MAX_KEY_LENGTH]; + uint8_t keyHash[SHA256_HASH_LENGTH]; + uint8_t innerHash[SHA256_HASH_LENGTH]; + uint8_t buffer[MAX_BUFFER_LENGTH]; + unsigned int i; + + // if key is longer than 64 bytes use the hash of the key as the key. + if (keyLen > MAX_KEY_LENGTH) + { + Sha256_ComputeHash(keyHash, key, keyLen); + key = keyHash; + keyLen = SHA256_HASH_LENGTH; + } + + // copy key to pad values, we will then XOR this with 0x36 and 0x5c respectively + memset(innerKeyPad, 0, sizeof(innerKeyPad)); + memset(outerKeyPad, 0, sizeof(outerKeyPad)); + memcpy(innerKeyPad, key, keyLen); + memcpy(outerKeyPad, key, keyLen); + + for (i = 0; i < MAX_KEY_LENGTH; i++) + { + innerKeyPad[i] ^= 0x36; + outerKeyPad[i] ^= 0x5c; + } + + // perform inner SHA256 + memset(buffer, 0x00, sizeof(buffer)); + memcpy(buffer, innerKeyPad, MAX_KEY_LENGTH); + memcpy(buffer + MAX_KEY_LENGTH, data, dataLen); + + Sha256_ComputeHash(innerHash, buffer, MAX_KEY_LENGTH + dataLen); + + // perform outer SHA256 + memset(buffer, 0x00, sizeof(buffer)); + memcpy(buffer, outerKeyPad, MAX_KEY_LENGTH); + memcpy(buffer + MAX_KEY_LENGTH, innerHash, SHA256_HASH_LENGTH); + + Sha256_ComputeHash(hash, buffer, MAX_KEY_LENGTH + SHA256_HASH_LENGTH); } diff --git a/src/fdm_licensee_verification.c b/src/fdm_licensee_verification.c index 149055d..1ceb3fa 100644 --- a/src/fdm_licensee_verification.c +++ b/src/fdm_licensee_verification.c @@ -60,87 +60,86 @@ * @return true for success otherwise false. */ static bool CalculateLicenseeHash(uint8_t hash[SHA256_HASH_LENGTH], const char *challenge, - int challengeLength, int iterations, const char *licenseeSecret) + int challengeLength, int iterations, const char *licenseeSecret) { - unsigned int i; - uint8_t key[MAX_STR_SIZE]; - int keyLength; - - if (challenge == NULL || licenseeSecret == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return false; - } - - LOG(LOG_DBG, "Calculating licensee hash"); - - keyLength = b64Decode((char *)key, sizeof(key), licenseeSecret, strlen(licenseeSecret)); - - if (keyLength == -1) - { - LOG(LOG_ERR, "Failed to decode a base64 encoded value"); - return false; - } - - HmacSha256_ComputeHash(hash, (const uint8_t *) challenge, challengeLength, key, keyLength); - for (i = 1; i < iterations; i++) - { - HmacSha256_ComputeHash(hash, hash, SHA256_HASH_LENGTH, key, keyLength); - } - return true; + unsigned int i; + uint8_t key[MAX_STR_SIZE]; + int keyLength; + + if (challenge == NULL || licenseeSecret == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return false; + } + + LOG(LOG_DBG, "Calculating licensee hash"); + + keyLength = b64Decode((char *)key, sizeof(key), licenseeSecret, strlen(licenseeSecret)); + + if (keyLength == -1) + { + LOG(LOG_ERR, "Failed to decode a base64 encoded value"); + return false; + } + + HmacSha256_ComputeHash(hash, (const uint8_t *) challenge, challengeLength, key, keyLength); + for (i = 1; i < iterations; i++) + { + HmacSha256_ComputeHash(hash, hash, SHA256_HASH_LENGTH, key, keyLength); + } + return true; } -bool PerformFlowLicenseeVerification(AwaClientSession *session, Verification *verificationData, - const char *licenseeSecret) +bool PerformFlowLicenseeVerification(AwaClientSession *session, Verification *verificationData, const char *licenseeSecret) { - uint8_t licenseeHash[SHA256_HASH_LENGTH] = {0}; - char licenseeHashResourcePath[URL_PATH_SIZE] = {0}; - AwaError error; - - if (session == NULL || verificationData == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return false; - } - - LOG(LOG_INFO, "Performing flow license verification"); - - // Calculate the LicenseeHash based-on challenge - if (!CalculateLicenseeHash(licenseeHash, verificationData->challenge.Data, - verificationData->challenge.Size, verificationData->iterations, licenseeSecret)) - { - LOG(LOG_ERR, "Failed to calculate licensee hash"); - verificationData->waitForServerResponse = false; - return false; - } - - if (verificationData->licenseeHash.Data != NULL) - { - free(verificationData->licenseeHash.Data); - } - verificationData->licenseeHash.Data = malloc(SHA256_HASH_LENGTH); - if (verificationData->licenseeHash.Data != NULL) - { - memcpy(verificationData->licenseeHash.Data , licenseeHash, SHA256_HASH_LENGTH); - } - verificationData->licenseeHash.Size = SHA256_HASH_LENGTH; - - // Write the hash to the Flow object - if ((error = MAKE_FLOW_OBJECT_RESOURCE_PATH(licenseeHashResourcePath, - FlowObjectResourceId_LicenseeHash)) == AwaError_Success) - { - if(!SetResource(session, licenseeHashResourcePath, (void *)&verificationData->licenseeHash, - AwaResourceType_Opaque)) - { - LOG(LOG_ERR, "Failed to set licensee hash"); - return false; - } - } - else - { - LOG(LOG_ERR, "Failed to create licensee hash resource path\n" - "error: %s", AwaError_ToString(error)); - return false; - } - return true; + uint8_t licenseeHash[SHA256_HASH_LENGTH] = {0}; + char licenseeHashResourcePath[URL_PATH_SIZE] = {0}; + AwaError error; + + if (session == NULL || verificationData == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return false; + } + + LOG(LOG_INFO, "Performing flow license verification"); + + // Calculate the LicenseeHash based-on challenge + if (!CalculateLicenseeHash(licenseeHash, verificationData->challenge.Data, + verificationData->challenge.Size, verificationData->iterations, licenseeSecret)) + { + LOG(LOG_ERR, "Failed to calculate licensee hash"); + verificationData->waitForServerResponse = false; + return false; + } + + if (verificationData->licenseeHash.Data != NULL) + { + free(verificationData->licenseeHash.Data); + } + + verificationData->licenseeHash.Data = malloc(SHA256_HASH_LENGTH); + + if (verificationData->licenseeHash.Data != NULL) + { + memcpy(verificationData->licenseeHash.Data , licenseeHash, SHA256_HASH_LENGTH); + } + + verificationData->licenseeHash.Size = SHA256_HASH_LENGTH; + + // Write the hash to the Flow object + if ((error = MAKE_FLOW_OBJECT_RESOURCE_PATH(licenseeHashResourcePath, FlowObjectResourceId_LicenseeHash)) == AwaError_Success) + { + if(!SetResource(session, licenseeHashResourcePath, (void *)&verificationData->licenseeHash, AwaResourceType_Opaque)) + { + LOG(LOG_ERR, "Failed to set licensee hash"); + return false; + } + } + else + { + LOG(LOG_ERR, "Failed to create licensee hash resource path\nerror: %s", AwaError_ToString(error)); + return false; + } + return true; } diff --git a/src/fdm_licensee_verification.h b/src/fdm_licensee_verification.h index 70bb43e..2555355 100644 --- a/src/fdm_licensee_verification.h +++ b/src/fdm_licensee_verification.h @@ -37,14 +37,12 @@ #define FDM_LICENSEE_VERIFICATION_H /** - * @brief Perform flow licensee verification using challenge and hash iterations and set the - * licensee hash to the flow object. + * @brief Perform flow licensee verification using challenge and hash iterations and set the licensee hash to the flow object. * @param[in] session A pointer to a valid session. * @param[in] verificationData Licensee verification data. * @param[in] licenseeSecret Licensee Secret. * @return true for success otherwise false. */ -bool PerformFlowLicenseeVerification(AwaClientSession *session, Verification *verificationData, - const char *licenseeSecret); +bool PerformFlowLicenseeVerification(AwaClientSession *session, Verification *verificationData, const char *licenseeSecret); -#endif /* FDM_LICENSEE_VERIFICATION_H */ +#endif /* FDM_LICENSEE_VERIFICATION_H */ diff --git a/src/fdm_log.h b/src/fdm_log.h index 1787e29..59ecaa7 100644 --- a/src/fdm_log.h +++ b/src/fdm_log.h @@ -41,7 +41,6 @@ #include //! \{ - #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_CYAN "\x1b[36m" @@ -59,45 +58,45 @@ /** Macro for printing logging message with current time, function and line no. */ #define DEBUG_PRINT \ - do { \ - time_t currentTime = time(NULL); \ - char buffer[TIME_BUFFER_SIZE] = {0}; \ - strftime(buffer, TIME_BUFFER_SIZE, "%x %X", localtime(¤tTime)); \ - fprintf(debugStream,"[%s] ", buffer); \ - fprintf(debugStream, ANSI_COLOR_YELLOW); \ - fprintf(debugStream,"%s:%d: ", __FILENAME__, __LINE__); \ - fprintf(debugStream, ANSI_COLOR_RESET); \ - } while (0) + do { \ + time_t currentTime = time(NULL); \ + char buffer[TIME_BUFFER_SIZE] = {0}; \ + strftime(buffer, TIME_BUFFER_SIZE, "%x %X", localtime(¤tTime)); \ + fprintf(debugStream,"[%s] ", buffer); \ + fprintf(debugStream, ANSI_COLOR_YELLOW); \ + fprintf(debugStream,"%s:%d: ", __FILENAME__, __LINE__); \ + fprintf(debugStream, ANSI_COLOR_RESET); \ + } while (0) /** Macro for logging message at the specified level. */ #define LOG(level, ...) \ - do { \ - if (level <= debugLevel) \ - { \ - if (debugStream == NULL) \ - debugStream = stdout; \ - fprintf(debugStream, "\n"); \ - if (debugLevel == LOG_DBG) \ - { \ - DEBUG_PRINT; \ - } \ - switch (level) \ - { \ - case LOG_ERR: \ - fprintf(debugStream, ANSI_COLOR_RED); \ - break; \ - case LOG_INFO: \ - fprintf(debugStream, ANSI_COLOR_CYAN); \ - break; \ - default: \ - break; \ - } \ - fprintf(debugStream, __VA_ARGS__); \ - fprintf(debugStream, ANSI_COLOR_RESET); \ - fprintf(debugStream, "\n"); \ - fflush(debugStream); \ - } \ - } while (0) + do { \ + if (level <= debugLevel) \ + { \ + if (debugStream == NULL) \ + debugStream = stdout; \ + fprintf(debugStream, "\n"); \ + if (debugLevel == LOG_DBG) \ + { \ + DEBUG_PRINT; \ + } \ + switch (level) \ + { \ + case LOG_ERR: \ + fprintf(debugStream, ANSI_COLOR_RED); \ + break; \ + case LOG_INFO: \ + fprintf(debugStream, ANSI_COLOR_CYAN); \ + break; \ + default: \ + break; \ + } \ + fprintf(debugStream, __VA_ARGS__); \ + fprintf(debugStream, ANSI_COLOR_RESET); \ + fprintf(debugStream, "\n"); \ + fflush(debugStream); \ + } \ + } while (0) /** Output stream to dump logs. */ extern FILE *debugStream; @@ -105,4 +104,4 @@ extern FILE *debugStream; extern int debugLevel; -#endif /* FDM_LOG_H */ +#endif /* FDM_LOG_H */ diff --git a/src/fdm_provision_constrained.c b/src/fdm_provision_constrained.c index f55712e..aa1539a 100644 --- a/src/fdm_provision_constrained.c +++ b/src/fdm_provision_constrained.c @@ -74,25 +74,25 @@ */ typedef struct { - //! \{ - char flowObjectInstancePath[URL_PATH_SIZE]; - char flowAccessObjectPath[URL_PATH_SIZE]; - char flowAccessObjectInstancePath[URL_PATH_SIZE]; - - // FlowObject resources - char fcapPath[URL_PATH_SIZE]; - char deviceTypePath[URL_PATH_SIZE]; - char licenseeIDPath[URL_PATH_SIZE]; - char parentIDPath[URL_PATH_SIZE]; - - - // FlowAccess object resources - char flowCloudUrlPath[URL_PATH_SIZE]; - char customerKeyPath[URL_PATH_SIZE]; - char customerSecretPath[URL_PATH_SIZE]; - char rememberMeTokenPath[URL_PATH_SIZE]; - char rememberMeTokenExpiryPath[URL_PATH_SIZE]; - //! \} + //! \{ + char flowObjectInstancePath[URL_PATH_SIZE]; + char flowAccessObjectPath[URL_PATH_SIZE]; + char flowAccessObjectInstancePath[URL_PATH_SIZE]; + + // FlowObject resources + char fcapPath[URL_PATH_SIZE]; + char deviceTypePath[URL_PATH_SIZE]; + char licenseeIDPath[URL_PATH_SIZE]; + char parentIDPath[URL_PATH_SIZE]; + + + // FlowAccess object resources + char flowCloudUrlPath[URL_PATH_SIZE]; + char customerKeyPath[URL_PATH_SIZE]; + char customerSecretPath[URL_PATH_SIZE]; + char rememberMeTokenPath[URL_PATH_SIZE]; + char rememberMeTokenExpiryPath[URL_PATH_SIZE]; + //! \} } Paths; @@ -110,605 +110,576 @@ static bool pathsMade = false; static bool MakePaths(void) { - memset(&pathStore, 0, sizeof(Paths)); - if (AwaAPI_MakeObjectInstancePath(pathStore.flowObjectInstancePath, URL_PATH_SIZE, - Lwm2mObjectId_FlowObject, 0) != AwaError_Success || - AwaAPI_MakeObjectPath(pathStore.flowAccessObjectPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess) != AwaError_Success || - AwaAPI_MakeObjectInstancePath(pathStore.flowAccessObjectInstancePath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess, 0) != AwaError_Success || - // FlowObject resources - AwaAPI_MakeResourcePath(pathStore.fcapPath, URL_PATH_SIZE, Lwm2mObjectId_FlowObject, 0, - FlowObjectResourceId_Fcap) != AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.deviceTypePath, URL_PATH_SIZE, - Lwm2mObjectId_FlowObject, 0, - FlowObjectResourceId_DeviceType) != AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.licenseeIDPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowObject, 0, - FlowObjectResourceId_LicenseeId) != AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.parentIDPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowObject, 0, - FlowObjectResourceId_ParentId) != AwaError_Success || - // FlowAccess resources - AwaAPI_MakeResourcePath(pathStore.flowCloudUrlPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_Url) != AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.customerKeyPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_CustomerKey) != - AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.customerSecretPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_CustomerSecret) != - AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.rememberMeTokenPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_RememberMeToken) != - AwaError_Success || - AwaAPI_MakeResourcePath(pathStore.rememberMeTokenExpiryPath, URL_PATH_SIZE, - Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_RememberMeTokenExpiry) != - AwaError_Success) - { - LOG(LOG_ERR, "Couldn't generate all object and resource paths"); - return false; - } - - return true; + memset(&pathStore, 0, sizeof(Paths)); + if (AwaAPI_MakeObjectInstancePath(pathStore.flowObjectInstancePath, URL_PATH_SIZE, + Lwm2mObjectId_FlowObject, 0) != AwaError_Success || + AwaAPI_MakeObjectPath(pathStore.flowAccessObjectPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess) != AwaError_Success || + AwaAPI_MakeObjectInstancePath(pathStore.flowAccessObjectInstancePath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess, 0) != AwaError_Success || + // FlowObject resources + AwaAPI_MakeResourcePath(pathStore.fcapPath, URL_PATH_SIZE, Lwm2mObjectId_FlowObject, 0, + FlowObjectResourceId_Fcap) != AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.deviceTypePath, URL_PATH_SIZE, + Lwm2mObjectId_FlowObject, 0, + FlowObjectResourceId_DeviceType) != AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.licenseeIDPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowObject, 0, + FlowObjectResourceId_LicenseeId) != AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.parentIDPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowObject, 0, + FlowObjectResourceId_ParentId) != AwaError_Success || + // FlowAccess resources + AwaAPI_MakeResourcePath(pathStore.flowCloudUrlPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_Url) != AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.customerKeyPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_CustomerKey) != + AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.customerSecretPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_CustomerSecret) != + AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.rememberMeTokenPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_RememberMeToken) != + AwaError_Success || + AwaAPI_MakeResourcePath(pathStore.rememberMeTokenExpiryPath, URL_PATH_SIZE, + Lwm2mObjectId_FlowAccess, 0, FlowAccessResourceId_RememberMeTokenExpiry) != + AwaError_Success) + { + LOG(LOG_ERR, "Couldn't generate all object and resource paths"); + return false; + } + + return true; } bool IsDeviceProvisioned(const AwaServerSession *session, const char *clientID) { - AwaError error = AwaError_Unspecified; - bool result = false; - const char * tempStr = NULL; - const AwaTime *tempTimePtr = NULL; - - if (!pathsMade) - { - if (!MakePaths()) - { - LOG(LOG_ERR, "Failed to create paths"); - return false; - } - pathsMade = true; - } - - AwaServerReadOperation *readOp = AwaServerReadOperation_New(session); - if (readOp == NULL) - { - LOG(LOG_ERR, "Couldn't create new ServerReadOperation for reading client resources"); - return false; - } - error = AwaServerReadOperation_AddPath(readOp, clientID, - pathStore.flowAccessObjectInstancePath); - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Couldn't add %s path to the read operation\nerror: %s", - pathStore.flowAccessObjectInstancePath, AwaError_ToString(error)); - goto read_fail; - } - - error = AwaServerReadOperation_Perform(readOp, COAP_TIMEOUT); - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Couldn't perform read operation\nerror: %s", AwaError_ToString(error)); - goto read_fail; - } - const AwaServerReadResponse *readResponse = AwaServerReadOperation_GetResponse(readOp, - clientID); - if (readResponse == NULL) - { - LOG(LOG_ERR, "Failed to retrieve read response"); - goto read_fail; - } - - if (!AwaServerReadResponse_ContainsPath(readResponse, - pathStore.flowAccessObjectInstancePath)) - { - LOG(LOG_ERR, "Read response does not contain FlowAccess Object"); - goto read_fail; - } - - error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, - pathStore.flowCloudUrlPath, &tempStr); - if (error != AwaError_Success || tempStr == NULL) - { - LOG(LOG_ERR, "Failed to retrieve FlowCloudUrl\nerror: %s", AwaError_ToString(error)); - goto read_fail; - } - - error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, - pathStore.customerKeyPath, &tempStr); - if (error != AwaError_Success || tempStr == NULL) - { - LOG(LOG_ERR, "Failed to retrieve CustomerKey\nerror: %s", AwaError_ToString(error)); - goto read_fail; - } - - error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, - pathStore.customerSecretPath, &tempStr); - if (error != AwaError_Success || tempStr == NULL) - { - LOG(LOG_ERR, "Failed to retrieve CustomerSecret\nerror: %s", AwaError_ToString(error)); - goto read_fail; - } - - error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, - pathStore.rememberMeTokenPath, &tempStr); - if (error != AwaError_Success || tempStr == NULL) - { - LOG(LOG_ERR, "Failed to retrieve RememberMeToken\nerror: %s", AwaError_ToString(error)); - goto read_fail; - } - - error = AwaServerReadResponse_GetValueAsTimePointer(readResponse, - pathStore.rememberMeTokenExpiryPath, &tempTimePtr); - if (error != AwaError_Success || *tempTimePtr == 0) - { - LOG(LOG_ERR, "Failed to retrieve RememberMeTokenExpiry\nerror: %s", - AwaError_ToString(error)); - goto read_fail; - } - else - { - result = true; - } - - read_fail: - AwaServerReadOperation_Free(&readOp); - return result; + AwaError error = AwaError_Unspecified; + bool result = false; + const char * tempStr = NULL; + const AwaTime *tempTimePtr = NULL; + + if (!pathsMade) + { + if (!MakePaths()) + { + LOG(LOG_ERR, "Failed to create paths"); + return false; + } + pathsMade = true; + } + + AwaServerReadOperation *readOp = AwaServerReadOperation_New(session); + if (readOp == NULL) + { + LOG(LOG_ERR, "Couldn't create new ServerReadOperation for reading client resources"); + return false; + } + error = AwaServerReadOperation_AddPath(readOp, clientID, pathStore.flowAccessObjectInstancePath); + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Couldn't add %s path to the read operation\nerror: %s", + pathStore.flowAccessObjectInstancePath, AwaError_ToString(error)); + goto read_fail; + } + + error = AwaServerReadOperation_Perform(readOp, COAP_TIMEOUT); + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Couldn't perform read operation\nerror: %s", AwaError_ToString(error)); + goto read_fail; + } + const AwaServerReadResponse *readResponse = AwaServerReadOperation_GetResponse(readOp, clientID); + if (readResponse == NULL) + { + LOG(LOG_ERR, "Failed to retrieve read response"); + goto read_fail; + } + + if (!AwaServerReadResponse_ContainsPath(readResponse, pathStore.flowAccessObjectInstancePath)) + { + LOG(LOG_ERR, "Read response does not contain FlowAccess Object"); + goto read_fail; + } + + error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, pathStore.flowCloudUrlPath, &tempStr); + if (error != AwaError_Success || tempStr == NULL) + { + LOG(LOG_ERR, "Failed to retrieve FlowCloudUrl\nerror: %s", AwaError_ToString(error)); + goto read_fail; + } + + error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, pathStore.customerKeyPath, &tempStr); + if (error != AwaError_Success || tempStr == NULL) + { + LOG(LOG_ERR, "Failed to retrieve CustomerKey\nerror: %s", AwaError_ToString(error)); + goto read_fail; + } + + error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, pathStore.customerSecretPath, &tempStr); + if (error != AwaError_Success || tempStr == NULL) + { + LOG(LOG_ERR, "Failed to retrieve CustomerSecret\nerror: %s", AwaError_ToString(error)); + goto read_fail; + } + + error = AwaServerReadResponse_GetValueAsCStringPointer(readResponse, pathStore.rememberMeTokenPath, &tempStr); + if (error != AwaError_Success || tempStr == NULL) + { + LOG(LOG_ERR, "Failed to retrieve RememberMeToken\nerror: %s", AwaError_ToString(error)); + goto read_fail; + } + + error = AwaServerReadResponse_GetValueAsTimePointer(readResponse, pathStore.rememberMeTokenExpiryPath, &tempTimePtr); + if (error != AwaError_Success || *tempTimePtr == 0) + { + LOG(LOG_ERR, "Failed to retrieve RememberMeTokenExpiry\nerror: %s", AwaError_ToString(error)); + goto read_fail; + } + else + { + result = true; + } + + read_fail: + AwaServerReadOperation_Free(&readOp); + return result; } static bool IsDevicePresent(const AwaServerSession *session, const char *clientID) { - AwaError error = AwaError_Unspecified; - bool result = false; - if (session == NULL || clientID == NULL) - return false; - - AwaServerListClientsOperation *clientListOperation = - AwaServerListClientsOperation_New(session); - if (clientListOperation == NULL) - { - return false; - } - - error = AwaServerListClientsOperation_Perform(clientListOperation, QUERY_TIMEOUT); - if (error == AwaError_Success) - { - const AwaServerListClientsResponse *response = - AwaServerListClientsOperation_GetResponse(clientListOperation, clientID); - result = (response != NULL); - } - AwaServerListClientsOperation_Free(&clientListOperation); - return result; + AwaError error = AwaError_Unspecified; + bool result = false; + if (session == NULL || clientID == NULL) + return false; + + AwaServerListClientsOperation *clientListOperation = AwaServerListClientsOperation_New(session); + if (clientListOperation == NULL) + { + return false; + } + + error = AwaServerListClientsOperation_Perform(clientListOperation, QUERY_TIMEOUT); + if (error == AwaError_Success) + { + const AwaServerListClientsResponse *response = AwaServerListClientsOperation_GetResponse(clientListOperation, clientID); + result = (response != NULL); + } + AwaServerListClientsOperation_Free(&clientListOperation); + return result; } static bool IsFlowObjectInstancePresent(const AwaServerSession *session, const char *clientID) { - AwaServerReadOperation *readOp = AwaServerReadOperation_New(session); - if (readOp == NULL) - { - LOG(LOG_ERR, "Couldn't create new ServerReadOperation for reading client resources"); - return false; - } - AwaError error = AwaServerReadOperation_AddPath(readOp, clientID, - pathStore.flowObjectInstancePath); - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Couldn't add %s path to the read operation\nerror: %s", - pathStore.flowObjectInstancePath, AwaError_ToString(error)); - return false; - } - - error = AwaServerReadOperation_Perform(readOp, COAP_TIMEOUT); - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Couldn't perform read operation\nerror: %s", AwaError_ToString(error)); - return false; - } - - const AwaServerReadResponse *readResponse = AwaServerReadOperation_GetResponse(readOp, - clientID); - if (readResponse == NULL) - { - LOG(LOG_ERR, "Failed to retrieve read response"); - return false; - } - - if (!AwaServerReadResponse_ContainsPath(readResponse, pathStore.flowObjectInstancePath)) - { - LOG(LOG_ERR, "Read response does not contain FlowAccess Object"); - return false; - } - return true; + AwaServerReadOperation *readOp = AwaServerReadOperation_New(session); + if (readOp == NULL) + { + LOG(LOG_ERR, "Couldn't create new ServerReadOperation for reading client resources"); + return false; + } + AwaError error = AwaServerReadOperation_AddPath(readOp, clientID, pathStore.flowObjectInstancePath); + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Couldn't add %s path to the read operation\nerror: %s", + pathStore.flowObjectInstancePath, AwaError_ToString(error)); + return false; + } + + error = AwaServerReadOperation_Perform(readOp, COAP_TIMEOUT); + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Couldn't perform read operation\nerror: %s", AwaError_ToString(error)); + return false; + } + + const AwaServerReadResponse *readResponse = AwaServerReadOperation_GetResponse(readOp, clientID); + if (readResponse == NULL) + { + LOG(LOG_ERR, "Failed to retrieve read response"); + return false; + } + + if (!AwaServerReadResponse_ContainsPath(readResponse, pathStore.flowObjectInstancePath)) + { + LOG(LOG_ERR, "Read response does not contain FlowAccess Object"); + return false; + } + return true; } static void FlowAccessObjectUpdated(const AwaChangeSet *changeSet, void *context) { - LOG(LOG_DBG, "In FlowAccessObjectUpdated"); - if (changeSet != NULL) - { - if (!pathsMade) - { - if (!MakePaths()) - { - LOG(LOG_ERR, "Failed to create paths"); - return; - } - pathsMade = true; - } - - const char *url=NULL, *key=NULL, *secret=NULL, *token=NULL; - const AwaTime *tokenExpiry = NULL; - if (AwaChangeSet_ContainsPath(changeSet, pathStore.flowCloudUrlPath) && - AwaChangeSet_HasValue(changeSet, pathStore.flowCloudUrlPath)) - { - AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.flowCloudUrlPath, &url); - LOG(LOG_DBG, "Retrieved flowcloudUrl"); - } - else - { - LOG(LOG_DBG, "Failed to retrieve flowcloudUrl"); - } - - if (AwaChangeSet_ContainsPath(changeSet, pathStore.customerKeyPath) && - AwaChangeSet_HasValue(changeSet, pathStore.customerKeyPath)) - { - AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.customerKeyPath, &key); - LOG(LOG_DBG, "Retrieved customerKey"); - } - else - { - LOG(LOG_DBG, "Failed to retrieve customerKey"); - } - - if (AwaChangeSet_ContainsPath(changeSet, pathStore.customerSecretPath) && - AwaChangeSet_HasValue(changeSet, pathStore.customerSecretPath)) - { - AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.customerSecretPath, &secret); - LOG(LOG_DBG, "Retrieved customerSecret"); - } - else - { - LOG(LOG_DBG, "Failed to retrieve customerSecret"); - } - - if (AwaChangeSet_ContainsPath(changeSet, pathStore.rememberMeTokenPath) && - AwaChangeSet_HasValue(changeSet, pathStore.rememberMeTokenPath)) - { - AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.rememberMeTokenPath, &token); - LOG(LOG_DBG, "Retrieved rememberMeToken"); - } - else - { - LOG(LOG_DBG, "Failed to retrieve rememberMeToken"); - } - - if (AwaChangeSet_ContainsPath(changeSet, pathStore.rememberMeTokenExpiryPath) && - AwaChangeSet_HasValue(changeSet, pathStore.rememberMeTokenExpiryPath)) - { - AwaChangeSet_GetValueAsTimePointer(changeSet, pathStore.rememberMeTokenExpiryPath, - &tokenExpiry); - LOG(LOG_DBG, "Retrieved rememberMeTokenExpiry"); - } - else - { - LOG(LOG_DBG, "Failed to retrieve rememberMeTokenExpiry"); - } - - if ((url != NULL) && (key != NULL) && (secret != NULL) && (token != NULL) && - (*tokenExpiry != 0)) - { - LOG(LOG_INFO, "Provisioned"); - isProvisioned = true; - } - else - { - LOG(LOG_INFO, "Not Provisioned yet"); - } - } - else - { - LOG(LOG_ERR, "Invalid FlowAccess object changeset"); - } + LOG(LOG_DBG, "In FlowAccessObjectUpdated"); + if (changeSet != NULL) + { + if (!pathsMade) + { + if (!MakePaths()) + { + LOG(LOG_ERR, "Failed to create paths"); + return; + } + pathsMade = true; + } + + const char *url=NULL, *key=NULL, *secret=NULL, *token=NULL; + const AwaTime *tokenExpiry = NULL; + if (AwaChangeSet_ContainsPath(changeSet, pathStore.flowCloudUrlPath) && + AwaChangeSet_HasValue(changeSet, pathStore.flowCloudUrlPath)) + { + AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.flowCloudUrlPath, &url); + LOG(LOG_DBG, "Retrieved flowcloudUrl"); + } + else + { + LOG(LOG_DBG, "Failed to retrieve flowcloudUrl"); + } + + if (AwaChangeSet_ContainsPath(changeSet, pathStore.customerKeyPath) && + AwaChangeSet_HasValue(changeSet, pathStore.customerKeyPath)) + { + AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.customerKeyPath, &key); + LOG(LOG_DBG, "Retrieved customerKey"); + } + else + { + LOG(LOG_DBG, "Failed to retrieve customerKey"); + } + + if (AwaChangeSet_ContainsPath(changeSet, pathStore.customerSecretPath) && + AwaChangeSet_HasValue(changeSet, pathStore.customerSecretPath)) + { + AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.customerSecretPath, &secret); + LOG(LOG_DBG, "Retrieved customerSecret"); + } + else + { + LOG(LOG_DBG, "Failed to retrieve customerSecret"); + } + + if (AwaChangeSet_ContainsPath(changeSet, pathStore.rememberMeTokenPath) && + AwaChangeSet_HasValue(changeSet, pathStore.rememberMeTokenPath)) + { + AwaChangeSet_GetValueAsCStringPointer(changeSet, pathStore.rememberMeTokenPath, &token); + LOG(LOG_DBG, "Retrieved rememberMeToken"); + } + else + { + LOG(LOG_DBG, "Failed to retrieve rememberMeToken"); + } + + if (AwaChangeSet_ContainsPath(changeSet, pathStore.rememberMeTokenExpiryPath) && + AwaChangeSet_HasValue(changeSet, pathStore.rememberMeTokenExpiryPath)) + { + AwaChangeSet_GetValueAsTimePointer(changeSet, pathStore.rememberMeTokenExpiryPath, &tokenExpiry); + LOG(LOG_DBG, "Retrieved rememberMeTokenExpiry"); + } + else + { + LOG(LOG_DBG, "Failed to retrieve rememberMeTokenExpiry"); + } + + if ((url != NULL) && (key != NULL) && (secret != NULL) && (token != NULL) && + (*tokenExpiry != 0)) + { + LOG(LOG_INFO, "Provisioned"); + isProvisioned = true; + } + else + { + LOG(LOG_INFO, "Not Provisioned yet"); + } + } + else + { + LOG(LOG_ERR, "Invalid FlowAccess object changeset"); + } } static bool ObserveDeviceFlowAccessObject(const AwaServerSession *session, const char *clientID, - AwaServerObserveOperation **flowAccessObjectChange, - AwaServerObservation **flowAccessObjectChangeObservation) + AwaServerObserveOperation **flowAccessObjectChange, + AwaServerObservation **flowAccessObjectChangeObservation) { - if ((session == NULL) || (clientID == NULL)) - { - LOG(LOG_ERR, "Null arguments to %s()", __func__); - return false; - } - - if (!pathsMade) - { - if (!MakePaths()) - { - LOG(LOG_ERR, "Failed to create paths"); - return false; - } - pathsMade = true; - } - - AwaError error = AwaError_Unspecified; - *flowAccessObjectChange = AwaServerObserveOperation_New(session); - if (*flowAccessObjectChange == NULL) - { - LOG(LOG_ERR, "Could not create new observe operation to subscribe to constrained \ - device's FlowAccess object"); - return false; - } - - *flowAccessObjectChangeObservation = AwaServerObservation_New(clientID, - pathStore.flowAccessObjectPath, FlowAccessObjectUpdated, NULL); - if (*flowAccessObjectChangeObservation == NULL) - { - LOG(LOG_ERR, "Could not create new observation to subscribe to constrained device's \ - FlowAccess object"); - AwaServerObserveOperation_Free(flowAccessObjectChange); - *flowAccessObjectChange = NULL; - return false; - } - - error = AwaServerObserveOperation_AddObservation(*flowAccessObjectChange, - *flowAccessObjectChangeObservation); - if (error == AwaError_Success) - { - error = AwaServerObserveOperation_Perform(*flowAccessObjectChange, COAP_TIMEOUT); - if (error == AwaError_Success) - { - LOG(LOG_INFO, "Subscribed to FlowAccess object"); - return true; - } - else - { - LOG(LOG_ERR, "Error failed to observe client FlowAccess object\nerror: %s", - AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Error failed to add observation to observe client FlowAccess operation \ - \nerror: %s", AwaError_ToString(error)); - } - - AwaServerObservation_Free(flowAccessObjectChangeObservation); - *flowAccessObjectChangeObservation = NULL; - AwaServerObserveOperation_Free(flowAccessObjectChange); - *flowAccessObjectChange = NULL; - return false; + if ((session == NULL) || (clientID == NULL)) + { + LOG(LOG_ERR, "Null arguments to %s()", __func__); + return false; + } + + if (!pathsMade) + { + if (!MakePaths()) + { + LOG(LOG_ERR, "Failed to create paths"); + return false; + } + pathsMade = true; + } + + AwaError error = AwaError_Unspecified; + *flowAccessObjectChange = AwaServerObserveOperation_New(session); + if (*flowAccessObjectChange == NULL) + { + LOG(LOG_ERR, "Could not create new observe operation to subscribe to constrained device's FlowAccess object"); + return false; + } + + *flowAccessObjectChangeObservation = AwaServerObservation_New(clientID, + pathStore.flowAccessObjectPath, FlowAccessObjectUpdated, NULL); + if (*flowAccessObjectChangeObservation == NULL) + { + LOG(LOG_ERR, "Could not create new observation to subscribe to constrained device's FlowAccess object"); + AwaServerObserveOperation_Free(flowAccessObjectChange); + *flowAccessObjectChange = NULL; + return false; + } + + error = AwaServerObserveOperation_AddObservation(*flowAccessObjectChange, *flowAccessObjectChangeObservation); + if (error == AwaError_Success) + { + error = AwaServerObserveOperation_Perform(*flowAccessObjectChange, COAP_TIMEOUT); + if (error == AwaError_Success) + { + LOG(LOG_INFO, "Subscribed to FlowAccess object"); + return true; + } + else + { + LOG(LOG_ERR, "Error failed to observe client FlowAccess object\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Error failed to add observation to observe client FlowAccess operation\nerror: %s", AwaError_ToString(error)); + } + + AwaServerObservation_Free(flowAccessObjectChangeObservation); + *flowAccessObjectChangeObservation = NULL; + AwaServerObserveOperation_Free(flowAccessObjectChange); + *flowAccessObjectChange = NULL; + return false; } static bool RemoveDeviceObservations(const char *clientID, - AwaServerObserveOperation **flowAccessObjectChange, - AwaServerObservation **flowAccessObjectChangeObservation) + AwaServerObserveOperation **flowAccessObjectChange, + AwaServerObservation **flowAccessObjectChangeObservation) { - bool result = false; - if ((clientID == NULL) || - (flowAccessObjectChange == NULL) || - (flowAccessObjectChangeObservation == NULL)) - { - LOG(LOG_ERR, "Null arguments to %s()", __func__); - return false; - } - - AwaError error = AwaError_Unspecified; - AwaServerObservation_Free(flowAccessObjectChangeObservation); - *flowAccessObjectChangeObservation = NULL; - - AwaServerObservation *cancelObservation = AwaServerObservation_New(clientID, - pathStore.flowAccessObjectPath, FlowAccessObjectUpdated, NULL); - if (cancelObservation != NULL) - { - error = AwaServerObserveOperation_AddCancelObservation(*flowAccessObjectChange, - cancelObservation); - if (error == AwaError_Success) - { - error = AwaServerObserveOperation_Perform(*flowAccessObjectChange, COAP_TIMEOUT); - if (error == AwaError_Success) - { - result = true; - } - else - { - LOG(LOG_ERR, "Failed to cancel observation of constrained device's FlowAccess \ - object\nerror: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to add cancel observation of constrained device's FlowAccess \ - object\nerror: %s", AwaError_ToString(error)); - } - AwaServerObservation_Free(&cancelObservation); - } - else - { - LOG(LOG_ERR, "Couldn't create a cancel observation for constrained device's FlowAccess \ - object"); - } - - AwaServerObserveOperation_Free(flowAccessObjectChange); - *flowAccessObjectChange = NULL; - - return result; + bool result = false; + if ((clientID == NULL) || + (flowAccessObjectChange == NULL) || + (flowAccessObjectChangeObservation == NULL)) + { + LOG(LOG_ERR, "Null arguments to %s()", __func__); + return false; + } + + AwaError error = AwaError_Unspecified; + AwaServerObservation_Free(flowAccessObjectChangeObservation); + *flowAccessObjectChangeObservation = NULL; + + AwaServerObservation *cancelObservation = AwaServerObservation_New(clientID, pathStore.flowAccessObjectPath, FlowAccessObjectUpdated, NULL); + if (cancelObservation != NULL) + { + error = AwaServerObserveOperation_AddCancelObservation(*flowAccessObjectChange, cancelObservation); + if (error == AwaError_Success) + { + error = AwaServerObserveOperation_Perform(*flowAccessObjectChange, COAP_TIMEOUT); + if (error == AwaError_Success) + { + result = true; + } + else + { + LOG(LOG_ERR, "Failed to cancel observation of constrained device's FlowAccess object\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to add cancel observation of constrained device's FlowAccess object\nerror: %s", AwaError_ToString(error)); + } + AwaServerObservation_Free(&cancelObservation); + } + else + { + LOG(LOG_ERR, "Couldn't create a cancel observation for constrained device's FlowAccess object"); + } + + AwaServerObserveOperation_Free(flowAccessObjectChange); + *flowAccessObjectChange = NULL; + + return result; } static bool WriteProvisioningInformationToDevice (const AwaServerSession *session, - const char *clientID, const char *fcapCode, const char *deviceType, int licenseeID, - const char *parentID) + const char *clientID, const char *fcapCode, const char *deviceType, int licenseeID, + const char *parentID) { - bool result = false; - AwaError error = AwaError_Success; - unsigned char i, gatewayDeviceID[DEVICE_ID_SIZE]; - AwaOpaque parentIDOpaque; - - // 3 because two is for hex letters and one for space - if (strlen(parentID)/3 != DEVICE_ID_SIZE) - { - LOG(LOG_ERR, "ParentID is not of %u bytes", DEVICE_ID_SIZE); - return false; - } - - AwaServerWriteOperation *writeOp = AwaServerWriteOperation_New(session, - AwaWriteMode_Update); - if (writeOp != NULL) - { - if (!IsFlowObjectInstancePresent(session, clientID)) - { - AwaServerWriteOperation_CreateObjectInstance(writeOp, pathStore.flowObjectInstancePath); - } - - error = AwaServerWriteOperation_AddValueAsCString(writeOp, - pathStore.fcapPath, fcapCode); - if (error == AwaError_Success) - { - error = AwaServerWriteOperation_AddValueAsCString(writeOp, - pathStore.deviceTypePath, deviceType); - } - if (error == AwaError_Success) - { - error = AwaServerWriteOperation_AddValueAsInteger(writeOp, - pathStore.licenseeIDPath, licenseeID); - } - if (error == AwaError_Success) - { - for (i = 0; i < DEVICE_ID_SIZE; i++) - { - // 3 because two is for hex letters and one for space - sscanf(&parentID[i*3], "%02hhX", &gatewayDeviceID[i]); - } - parentIDOpaque.Data = gatewayDeviceID; - parentIDOpaque.Size = sizeof(gatewayDeviceID); - error = AwaServerWriteOperation_AddValueAsOpaque(writeOp, - pathStore.parentIDPath, parentIDOpaque); - } - if (error == AwaError_Success) - { - error = AwaServerWriteOperation_Perform(writeOp, clientID, COAP_TIMEOUT); - if (error == AwaError_Success) - { - result = true; - } - } - else - { - LOG(LOG_ERR, "Failed to create write request\nerror: %s", - AwaError_ToString(error)); - } - - AwaServerWriteOperation_Free(&writeOp); - } - return result; + bool result = false; + AwaError error = AwaError_Success; + unsigned char i, gatewayDeviceID[DEVICE_ID_SIZE]; + AwaOpaque parentIDOpaque; + + // 3 because two is for hex letters and one for space + if (strlen(parentID)/3 != DEVICE_ID_SIZE) + { + LOG(LOG_ERR, "ParentID is not of %u bytes", DEVICE_ID_SIZE); + return false; + } + + AwaServerWriteOperation *writeOp = AwaServerWriteOperation_New(session, AwaWriteMode_Update); + if (writeOp != NULL) + { + if (!IsFlowObjectInstancePresent(session, clientID)) + { + AwaServerWriteOperation_CreateObjectInstance(writeOp, pathStore.flowObjectInstancePath); + } + + error = AwaServerWriteOperation_AddValueAsCString(writeOp, pathStore.fcapPath, fcapCode); + if (error == AwaError_Success) + { + error = AwaServerWriteOperation_AddValueAsCString(writeOp, pathStore.deviceTypePath, deviceType); + } + if (error == AwaError_Success) + { + error = AwaServerWriteOperation_AddValueAsInteger(writeOp, pathStore.licenseeIDPath, licenseeID); + } + if (error == AwaError_Success) + { + for (i = 0; i < DEVICE_ID_SIZE; i++) + { + // 3 because two is for hex letters and one for space + sscanf(&parentID[i*3], "%02hhX", &gatewayDeviceID[i]); + } + parentIDOpaque.Data = gatewayDeviceID; + parentIDOpaque.Size = sizeof(gatewayDeviceID); + error = AwaServerWriteOperation_AddValueAsOpaque(writeOp, pathStore.parentIDPath, parentIDOpaque); + } + if (error == AwaError_Success) + { + error = AwaServerWriteOperation_Perform(writeOp, clientID, COAP_TIMEOUT); + if (error == AwaError_Success) + { + result = true; + } + } + else + { + LOG(LOG_ERR, "Failed to create write request\nerror: %s", + AwaError_ToString(error)); + } + + AwaServerWriteOperation_Free(&writeOp); + } + return result; } static bool WaitForNotification(AwaServerSession *session) { - int timeout = POLLING_TIMEOUT_SECONDS; - while (timeout-- != 0) - { - AwaServerSession_Process(session, COAP_TIMEOUT); - AwaServerSession_DispatchCallbacks(session); - if (isProvisioned) - { - return true; - } - sleep(POLLING_SLEEP_SECONDS); - } - LOG(LOG_ERR, "Failed to provision device"); - return false; + int timeout = POLLING_TIMEOUT_SECONDS; + while (timeout-- != 0) + { + AwaServerSession_Process(session, COAP_TIMEOUT); + AwaServerSession_DispatchCallbacks(session); + if (isProvisioned) + { + return true; + } + sleep(POLLING_SLEEP_SECONDS); + } + LOG(LOG_ERR, "Failed to provision device"); + return false; } bool IsConstrainedDeviceProvisioned(const char *clientID) { - bool status = false; - if (clientID == NULL) - { - LOG(LOG_ERR, "Null arguments to %s()", __func__); - return false; - } - AwaServerSession *serverSession = Server_EstablishSession(SERVER_ADDRESS, SERVER_PORT); - if (serverSession == NULL) - { - LOG(LOG_ERR, "Failed to establish session with server"); - return false; - } - - if (IsDevicePresent(serverSession, clientID)) - { - status = IsDeviceProvisioned(serverSession, clientID); - } - Server_ReleaseSession(&serverSession); - return status; + bool status = false; + if (clientID == NULL) + { + LOG(LOG_ERR, "Null arguments to %s()", __func__); + return false; + } + + AwaServerSession *serverSession = Server_EstablishSession(SERVER_ADDRESS, SERVER_PORT); + + if (serverSession == NULL) + { + LOG(LOG_ERR, "Failed to establish session with server"); + return false; + } + + if (IsDevicePresent(serverSession, clientID)) + { + status = IsDeviceProvisioned(serverSession, clientID); + } + + Server_ReleaseSession(&serverSession); + return status; } ProvisionStatus ProvisionConstrainedDevice(const char *clientID, const char*fcap, - const char *deviceType, int licenseeID, const char *parentID) + const char *deviceType, int licenseeID, const char *parentID) { - ProvisionStatus result = PROVISION_FAIL; - OBJECT_T flowObjects[] = {flowObject, flowAccessObject}; - LOG(LOG_INFO, "Provision constrained device:\n" - "\n%-11s\t = %s\n%-11s\t = %s\n%-11s\t = %d\n%-11s\t = %s", "Client ID", clientID, "Device Type", - deviceType, "Licensee ID", licenseeID, "Parent ID", parentID); - if (clientID == NULL || fcap == NULL || parentID == NULL) - { - LOG(LOG_ERR, "Null arguments to %s()", __func__); - return PROVISION_FAIL; - } - - AwaServerSession *serverSession = Server_EstablishSession(SERVER_ADDRESS, SERVER_PORT); - if (serverSession == NULL) - { - LOG(LOG_ERR, "Failed to establish session with server"); - return PROVISION_FAIL; - } - - if (DefineObjectsAtServer(serverSession, flowObjects, ARRAY_SIZE(flowObjects))) - { - if (!IsDevicePresent(serverSession, clientID)) - { - LOG(LOG_ERR, "Device not present"); - } - else if (IsDeviceProvisioned(serverSession, clientID)) - { - LOG(LOG_INFO, "Device already provisioned"); - result = ALREADY_PROVISIONED; - } - else - { - AwaServerObserveOperation *flowAccessObjectChange = NULL; - AwaServerObservation *flowAccessObjectChangeObservation = NULL; - LOG(LOG_INFO, "Provisioning constrained device"); - isProvisioned = false; - - if (ObserveDeviceFlowAccessObject(serverSession, clientID, &flowAccessObjectChange, - &flowAccessObjectChangeObservation)) - { - if (!WriteProvisioningInformationToDevice(serverSession, clientID, fcap, - deviceType, licenseeID, parentID)) - { - LOG(LOG_ERR, "Writing of device provisioning information failed"); - } - else if (WaitForNotification(serverSession)) - { - result = PROVISION_OK; - } - RemoveDeviceObservations(clientID, &flowAccessObjectChange, - &flowAccessObjectChangeObservation); - } - else - { - LOG(LOG_ERR, "Failed to observe device flow access object"); - } - } - } - else - { - LOG(LOG_ERR, "Failed to register flow objects' definitions at the server"); - } - Server_ReleaseSession(&serverSession); - LOG(LOG_INFO, "status = %d", result); - return result; + ProvisionStatus result = PROVISION_FAIL; + OBJECT_T flowObjects[] = {flowObject, flowAccessObject}; + LOG(LOG_INFO, "Provision constrained device:\n" + "\n%-11s\t = %s\n%-11s\t = %s\n%-11s\t = %d\n%-11s\t = %s", "Client ID", clientID, "Device Type", + deviceType, "Licensee ID", licenseeID, "Parent ID", parentID); + if (clientID == NULL || fcap == NULL || parentID == NULL) + { + LOG(LOG_ERR, "Null arguments to %s()", __func__); + return PROVISION_FAIL; + } + + AwaServerSession *serverSession = Server_EstablishSession(SERVER_ADDRESS, SERVER_PORT); + if (serverSession == NULL) + { + LOG(LOG_ERR, "Failed to establish session with server"); + return PROVISION_FAIL; + } + + if (DefineObjectsAtServer(serverSession, flowObjects, ARRAY_SIZE(flowObjects))) + { + if (!IsDevicePresent(serverSession, clientID)) + { + LOG(LOG_ERR, "Device not present"); + } + else if (IsDeviceProvisioned(serverSession, clientID)) + { + LOG(LOG_INFO, "Device already provisioned"); + result = ALREADY_PROVISIONED; + } + else + { + AwaServerObserveOperation *flowAccessObjectChange = NULL; + AwaServerObservation *flowAccessObjectChangeObservation = NULL; + LOG(LOG_INFO, "Provisioning constrained device"); + isProvisioned = false; + + if (ObserveDeviceFlowAccessObject(serverSession, clientID, &flowAccessObjectChange, &flowAccessObjectChangeObservation)) + { + if (!WriteProvisioningInformationToDevice(serverSession, clientID, fcap, deviceType, licenseeID, parentID)) + { + LOG(LOG_ERR, "Writing of device provisioning information failed"); + } + else if (WaitForNotification(serverSession)) + { + result = PROVISION_OK; + } + RemoveDeviceObservations(clientID, &flowAccessObjectChange, &flowAccessObjectChangeObservation); + } + else + { + LOG(LOG_ERR, "Failed to observe device flow access object"); + } + } + } + else + { + LOG(LOG_ERR, "Failed to register flow objects' definitions at the server"); + } + Server_ReleaseSession(&serverSession); + LOG(LOG_INFO, "status = %d", result); + return result; } diff --git a/src/fdm_provision_constrained.h b/src/fdm_provision_constrained.h index 11558b8..5f9b105 100644 --- a/src/fdm_provision_constrained.h +++ b/src/fdm_provision_constrained.h @@ -46,7 +46,7 @@ 2 for ALREADY_PROVISIONED */ ProvisionStatus ProvisionConstrainedDevice(const char *clientID, const char *fcap, - const char *deviceType, int licenseeID, const char *parentID); + const char *deviceType, int licenseeID, const char *parentID); /** * @brief Poll the contents of the FlowAccessObject of the constrained device. @@ -57,4 +57,4 @@ ProvisionStatus ProvisionConstrainedDevice(const char *clientID, const char *fca */ bool IsDeviceProvisioned(const AwaServerSession *session, const char *clientID); -#endif /* FDM_PROVISION_CONSTRAINED_H */ +#endif /* FDM_PROVISION_CONSTRAINED_H */ diff --git a/src/fdm_register.c b/src/fdm_register.c index a785970..5754b24 100644 --- a/src/fdm_register.c +++ b/src/fdm_register.c @@ -69,217 +69,207 @@ */ static AwaObjectDefinition *CreateObjectDefinition(const OBJECT_T *object) { - unsigned int i; - bool success = true; - RESOURCE_T *resource; - AwaError error; - AwaObjectDefinition *awaObject = AwaObjectDefinition_New(object->id, - object->name, MIN_INSTANCES, MAX_INSTANCES); - - if (awaObject == NULL) - { - LOG(LOG_ERR, "Failed to create %s definition", object->name); - return NULL; - } - - // define resources - for (i = 0; i < object->numResources; i++) - { - resource = &object->resources[i]; - - switch (resource->type) - { - case AwaResourceType_String: - error = AwaObjectDefinition_AddResourceDefinitionAsString(awaObject, - resource->id, resource->name, resource->isMandatory, - AwaResourceOperations_ReadWrite, ""); - break; - - case AwaResourceType_Integer: - error = AwaObjectDefinition_AddResourceDefinitionAsInteger(awaObject, - resource->id, resource->name, resource->isMandatory, - AwaResourceOperations_ReadWrite, 0); - break; - - case AwaResourceType_Time: - error = AwaObjectDefinition_AddResourceDefinitionAsTime(awaObject, - resource->id, resource->name, resource->isMandatory, - AwaResourceOperations_ReadWrite, 0); - break; - - case AwaResourceType_Opaque: - error = AwaObjectDefinition_AddResourceDefinitionAsOpaque(awaObject, - resource->id, resource->name, resource->isMandatory, - AwaResourceOperations_ReadWrite, - ((AwaOpaque){0})); - break; - - default: - LOG(LOG_ERR, "Unknown resource type found, can't be added to %s definition", - object->name); - error = AwaError_Unspecified; - break; - } - - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Failed to add %s resource to %s object definition\n" - "error: %s", resource->name, object->name, AwaError_ToString(error)); - success = false; - break; - } - } - - if (!success) - { - AwaObjectDefinition_Free(&awaObject); - return NULL; - } - - return awaObject; + unsigned int i; + bool result = true; + RESOURCE_T *resource; + AwaError error; + AwaObjectDefinition *awaObject = AwaObjectDefinition_New(object->id, object->name, MIN_INSTANCES, MAX_INSTANCES); + + if (awaObject == NULL) + { + LOG(LOG_ERR, "Failed to create %s definition", object->name); + return NULL; + } + + // define resources + for (i = 0; i < object->numResources; i++) + { + resource = &object->resources[i]; + + switch (resource->type) + { + case AwaResourceType_String: + error = AwaObjectDefinition_AddResourceDefinitionAsString(awaObject, + resource->id, resource->name, resource->isMandatory, + AwaResourceOperations_ReadWrite, ""); + break; + + case AwaResourceType_Integer: + error = AwaObjectDefinition_AddResourceDefinitionAsInteger(awaObject, + resource->id, resource->name, resource->isMandatory, + AwaResourceOperations_ReadWrite, 0); + break; + + case AwaResourceType_Time: + error = AwaObjectDefinition_AddResourceDefinitionAsTime(awaObject, + resource->id, resource->name, resource->isMandatory, + AwaResourceOperations_ReadWrite, 0); + break; + + case AwaResourceType_Opaque: + error = AwaObjectDefinition_AddResourceDefinitionAsOpaque(awaObject, + resource->id, resource->name, resource->isMandatory, + AwaResourceOperations_ReadWrite, + ((AwaOpaque){0})); + break; + + default: + LOG(LOG_ERR, "Unknown resource type found, can't be added to %s definition", object->name); + error = AwaError_Unspecified; + break; + } + + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Failed to add %s resource to %s object definition\n" + "error: %s", resource->name, object->name, AwaError_ToString(error)); + result = false; + break; + } + } + + if (!result) + { + AwaObjectDefinition_Free(&awaObject); + return NULL; + } + + return awaObject; } -bool DefineObjectsAtServer(AwaServerSession *session, const OBJECT_T *objects, - unsigned int numObjects) +bool DefineObjectsAtServer(AwaServerSession *session, const OBJECT_T *objects, unsigned int numObjects) { - unsigned int i; - unsigned int definitionCount = 0; - bool success = true; - AwaError error = AwaError_Success; - const OBJECT_T *object; - - if (session == NULL) - { - LOG(LOG_ERR, "Null session passsed to %s()", __func__); - return false; - } - - LOG(LOG_INFO, "Registering objects"); - - AwaServerDefineOperation *handler = AwaServerDefineOperation_New(session); - if (handler == NULL) - { - LOG(LOG_ERR, "Failed to create define operation for session"); - return false; - } - - for (i = 0; i < numObjects; i++) - { - object = &objects[i]; - if (AwaServerSession_IsObjectDefined(session, object->id)) - { - LOG(LOG_DBG, "%s object already defined", object->name); - continue; - } - - AwaObjectDefinition *awaObject = CreateObjectDefinition(object); - if (awaObject == NULL) - { - LOG(LOG_ERR, "Failed to create %s definition", object->name); - success = false; - break; - } - if ((error = AwaServerDefineOperation_Add(handler, awaObject)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to add %s definition to define operation\n" - "error: %s", object->name, AwaError_ToString(error)); - success = false; - AwaObjectDefinition_Free(&awaObject); - break; - } - definitionCount++; - AwaObjectDefinition_Free(&awaObject); - } - - if (success && definitionCount != 0) - { - if ((error = AwaServerDefineOperation_Perform(handler, IPC_TIMEOUT)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to perform define operation\n" - "error: %s", AwaError_ToString(error)); - success = false; - } - } - if ((error = AwaServerDefineOperation_Free(&handler)) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free define operation object\n" - "error: %s", AwaError_ToString(error)); - } - return success; + unsigned int i; + unsigned int definitionCount = 0; + bool result = true; + AwaError error = AwaError_Success; + const OBJECT_T *object; + + if (session == NULL) + { + LOG(LOG_ERR, "Null session passsed to %s()", __func__); + return false; + } + + LOG(LOG_INFO, "Registering objects"); + + AwaServerDefineOperation *handler = AwaServerDefineOperation_New(session); + if (handler == NULL) + { + LOG(LOG_ERR, "Failed to create define operation for session"); + return false; + } + + for (i = 0; i < numObjects; i++) + { + object = &objects[i]; + if (AwaServerSession_IsObjectDefined(session, object->id)) + { + LOG(LOG_DBG, "%s object already defined", object->name); + continue; + } + + AwaObjectDefinition *awaObject = CreateObjectDefinition(object); + if (awaObject == NULL) + { + LOG(LOG_ERR, "Failed to create %s definition", object->name); + result = false; + break; + } + + if ((error = AwaServerDefineOperation_Add(handler, awaObject)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to add %s definition to define operation\n" + "error: %s", object->name, AwaError_ToString(error)); + result = false; + AwaObjectDefinition_Free(&awaObject); + break; + } + definitionCount++; + AwaObjectDefinition_Free(&awaObject); + } + + if (result && definitionCount != 0) + { + if ((error = AwaServerDefineOperation_Perform(handler, IPC_TIMEOUT)) + != AwaError_Success) + { + LOG(LOG_ERR, "Failed to perform define operation\nerror: %s", AwaError_ToString(error)); + result = false; + } + } + if ((error = AwaServerDefineOperation_Free(&handler)) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free define operation object\nerror: %s", AwaError_ToString(error)); + } + return result; } -bool DefineObjectsAtClient(AwaClientSession *session, const OBJECT_T *objects, - unsigned int numObjects) +bool DefineObjectsAtClient(AwaClientSession *session, const OBJECT_T *objects, unsigned int numObjects) { - unsigned int i; - unsigned int definitionCount = 0; - bool success = true; - AwaError error = AwaError_Success; - const OBJECT_T *object; - - if (session == NULL) - { - LOG(LOG_ERR, "Null session passsed to %s()", __func__); - return false; - } - - LOG(LOG_INFO, "Registering flow objects"); - - AwaClientDefineOperation *handler = AwaClientDefineOperation_New(session); - if (handler == NULL) - { - LOG(LOG_ERR, "Failed to create define operation for session"); - return false; - } - - for (i = 0; i < numObjects; i++) - { - object = &objects[i]; - - if (AwaClientSession_IsObjectDefined(session, object->id)) - { - LOG(LOG_DBG, "%s object already defined", object->name); - continue; - } - - AwaObjectDefinition *awaObject = CreateObjectDefinition(object); - if (awaObject == NULL) - { - LOG(LOG_ERR, "Failed to create %s definition", object->name); - success = false; - break; - } - - if ((error = AwaClientDefineOperation_Add(handler, awaObject)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to add %s definition to define operation\n" - "error: %s", object->name, AwaError_ToString(error)); - success = false; - } - definitionCount++; - AwaObjectDefinition_Free(&awaObject); - } - - if (success && definitionCount != 0) - { - if ((error = AwaClientDefineOperation_Perform(handler, IPC_TIMEOUT)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to perform define operation\n" - "error: %s", AwaError_ToString(error)); - success = false; - } - } - if ((error = AwaClientDefineOperation_Free(&handler)) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free define operation object\n" - "error: %s", AwaError_ToString(error)); - } - return success; + unsigned int i; + unsigned int definitionCount = 0; + bool result = true; + AwaError error = AwaError_Success; + const OBJECT_T *object; + + if (session == NULL) + { + LOG(LOG_ERR, "Null session passsed to %s()", __func__); + return false; + } + + LOG(LOG_INFO, "Registering flow objects"); + + AwaClientDefineOperation *handler = AwaClientDefineOperation_New(session); + if (handler == NULL) + { + LOG(LOG_ERR, "Failed to create define operation for session"); + return false; + } + + for (i = 0; i < numObjects; i++) + { + object = &objects[i]; + + if (AwaClientSession_IsObjectDefined(session, object->id)) + { + LOG(LOG_DBG, "%s object already defined", object->name); + continue; + } + + AwaObjectDefinition *awaObject = CreateObjectDefinition(object); + if (awaObject == NULL) + { + LOG(LOG_ERR, "Failed to create %s definition", object->name); + result = false; + break; + } + + if ((error = AwaClientDefineOperation_Add(handler, awaObject)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to add %s definition to define operation\nerror: %s", object->name, AwaError_ToString(error)); + result = false; + } + definitionCount++; + AwaObjectDefinition_Free(&awaObject); + } + + if (result && definitionCount != 0) + { + if ((error = AwaClientDefineOperation_Perform(handler, IPC_TIMEOUT)) + != AwaError_Success) + { + LOG(LOG_ERR, "Failed to perform define operation\nerror: %s", AwaError_ToString(error)); + result = false; + } + } + if ((error = AwaClientDefineOperation_Free(&handler)) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free define operation object\nerror: %s", AwaError_ToString(error)); + } + return result; } /** @@ -291,433 +281,397 @@ bool DefineObjectsAtClient(AwaClientSession *session, const OBJECT_T *objects, * @param[in] create_resource true if resource needs to be created * @return true for success otherwise false. */ -static bool AddResourceToHandler(AwaClientSetOperation *handler, const char *resourcePath, - void *value, AwaResourceType type, bool create_resource) +static bool AddResourceToHandler(AwaClientSetOperation *handler, const char *resourcePath, void *value, AwaResourceType type, bool create_resource) { - AwaInteger *intValue; - AwaOpaque *opaqueValue; - AwaTime *timeValue; - AwaError error; - - if (handler == NULL || resourcePath == NULL || value == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return false; - } - - LOG(LOG_DBG, "Add resource %s to set operation handler", resourcePath); - - if (create_resource) - { - if (AwaClientSetOperation_CreateOptionalResource(handler, resourcePath) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to create %s", resourcePath); - return false; - } - } - switch (type) - { - case AwaResourceType_String: - error = AwaClientSetOperation_AddValueAsCString(handler, resourcePath, - (char *)value); - break; - - case AwaResourceType_Integer: - intValue = value; - error = AwaClientSetOperation_AddValueAsInteger(handler, resourcePath, *intValue); - break; - - case AwaResourceType_Time: - timeValue = value; - error = AwaClientSetOperation_AddValueAsTime(handler, resourcePath, *timeValue); - break; - - case AwaResourceType_Opaque: - opaqueValue = value; - error = AwaClientSetOperation_AddValueAsOpaque(handler, resourcePath, *opaqueValue); - break; - - default: - LOG(LOG_ERR, "Unknown resource type"); - return false; - } - - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Failed to set value of %s\n" - "error: %s", resourcePath, AwaError_ToString(error)); - return false; - } - return true; + AwaInteger *intValue; + AwaOpaque *opaqueValue; + AwaTime *timeValue; + AwaError error; + + if (handler == NULL || resourcePath == NULL || value == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return false; + } + + LOG(LOG_DBG, "Add resource %s to set operation handler", resourcePath); + + if (create_resource) + { + if (AwaClientSetOperation_CreateOptionalResource(handler, resourcePath) + != AwaError_Success) + { + LOG(LOG_ERR, "Failed to create %s", resourcePath); + return false; + } + } + switch (type) + { + case AwaResourceType_String: + error = AwaClientSetOperation_AddValueAsCString(handler, resourcePath, (char *)value); + break; + + case AwaResourceType_Integer: + intValue = value; + error = AwaClientSetOperation_AddValueAsInteger(handler, resourcePath, *intValue); + break; + + case AwaResourceType_Time: + timeValue = value; + error = AwaClientSetOperation_AddValueAsTime(handler, resourcePath, *timeValue); + break; + + case AwaResourceType_Opaque: + opaqueValue = value; + error = AwaClientSetOperation_AddValueAsOpaque(handler, resourcePath, *opaqueValue); + break; + + default: + LOG(LOG_ERR, "Unknown resource type"); + return false; + } + + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Failed to set value of %s\nerror: %s", resourcePath, AwaError_ToString(error)); + return false; + } + return true; } -bool SetResource(AwaClientSession *session, const char *resourcePath, void *value, - AwaResourceType type) +bool SetResource(AwaClientSession *session, const char *resourcePath, void *value, AwaResourceType type) { - AwaError error; - bool success = false; - - if (session == NULL || resourcePath == NULL || value == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return false; - } - - LOG(LOG_DBG, "Setting value of %s", resourcePath); - - AwaClientSetOperation *handler = AwaClientSetOperation_New(session); - if (handler == NULL) - { - LOG(LOG_ERR, "Failed to create set operation for session"); - return false; - } - - if (AddResourceToHandler(handler, resourcePath, value, type, true)) - { - if ((error = AwaClientSetOperation_Perform(handler, IPC_TIMEOUT)) - == AwaError_Success) - { - success = true; - } - else - { - LOG(LOG_ERR, "Failed to perform set operation\nerror: %s", - AwaError_ToString(error)); - } - } - - if ((error = AwaClientSetOperation_Free(&handler)) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free set operation handler\nerror: %s", - AwaError_ToString(error)); - } - return success; + AwaError error; + bool result = false; + + if (session == NULL || resourcePath == NULL || value == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return false; + } + + LOG(LOG_DBG, "Setting value of %s", resourcePath); + + AwaClientSetOperation *handler = AwaClientSetOperation_New(session); + if (handler == NULL) + { + LOG(LOG_ERR, "Failed to create set operation for session"); + return false; + } + + if (AddResourceToHandler(handler, resourcePath, value, type, true)) + { + if ((error = AwaClientSetOperation_Perform(handler, IPC_TIMEOUT)) == AwaError_Success) + { + result = true; + } + else + { + LOG(LOG_ERR, "Failed to perform set operation\nerror: %s", AwaError_ToString(error)); + } + } + + if ((error = AwaClientSetOperation_Free(&handler)) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free set operation handler\nerror: %s", AwaError_ToString(error)); + } + return result; } -bool DoesObjectExist(AwaClientSession *session, AwaObjectID objectId, - AwaObjectInstanceID objectInstanceId) +bool DoesObjectExist(AwaClientSession *session, AwaObjectID objectId, AwaObjectInstanceID objectInstanceId) { - const AwaClientGetResponse *response = NULL; - char objectInstancePath[URL_PATH_SIZE] = {0}; - bool success = false; - AwaError error; - - if (session == NULL) - { - LOG(LOG_ERR, "Null session passed to %s()", __func__); - return false; - } - - LOG(LOG_DBG, "Checking whether object %d exist or not", objectId); - - if ((error = AwaAPI_MakeObjectInstancePath(objectInstancePath, URL_PATH_SIZE, objectId, - objectInstanceId)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to generate path for %d object\nerror: %s", objectId, - AwaError_ToString(error)); - return false; - } - - AwaClientGetOperation *handler = AwaClientGetOperation_New(session); - if (handler == NULL) - { - LOG(LOG_ERR, "Failed to create get operation for session"); - return false; - } - - if ((error = AwaClientGetOperation_AddPath(handler, objectInstancePath)) - == AwaError_Success) - { - if ((error = AwaClientGetOperation_Perform(handler, IPC_TIMEOUT)) - == AwaError_Success) - { - response = AwaClientGetOperation_GetResponse(handler); - if (response != NULL) - { - if (AwaClientGetResponse_ContainsPath(response, objectInstancePath)) - { - success = true; - } - else - { - LOG(LOG_DBG, "%d object doesn't exist", objectId); - } - } - else - { - LOG(LOG_ERR, "Failed to get response from get operation handler"); - } - } - else - { - LOG(LOG_ERR, "Failed to perform get operation\nerror: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to add %d object path to get operation handler\nerror: %s", objectId, - AwaError_ToString(error)); - } - - if ((error = AwaClientGetOperation_Free(&handler)) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free get operation handler\nerror: %s", - AwaError_ToString(error)); - } - return success; + const AwaClientGetResponse *response = NULL; + char objectInstancePath[URL_PATH_SIZE] = {0}; + bool result = false; + AwaError error; + + if (session == NULL) + { + LOG(LOG_ERR, "Null session passed to %s()", __func__); + return false; + } + + LOG(LOG_DBG, "Checking whether object %d exist or not", objectId); + + if ((error = AwaAPI_MakeObjectInstancePath(objectInstancePath, URL_PATH_SIZE, objectId, objectInstanceId)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to generate path for %d object\nerror: %s", objectId, AwaError_ToString(error)); + return false; + } + + AwaClientGetOperation *handler = AwaClientGetOperation_New(session); + if (handler == NULL) + { + LOG(LOG_ERR, "Failed to create get operation for session"); + return false; + } + + if ((error = AwaClientGetOperation_AddPath(handler, objectInstancePath)) == AwaError_Success) + { + if ((error = AwaClientGetOperation_Perform(handler, IPC_TIMEOUT)) == AwaError_Success) + { + response = AwaClientGetOperation_GetResponse(handler); + if (response != NULL) + { + if (AwaClientGetResponse_ContainsPath(response, objectInstancePath)) + { + result = true; + } + else + { + LOG(LOG_DBG, "%d object doesn't exist", objectId); + } + } + else + { + LOG(LOG_ERR, "Failed to get response from get operation handler"); + } + } + else + { + LOG(LOG_ERR, "Failed to perform get operation\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to add %d object path to get operation handler\nerror: %s", objectId, AwaError_ToString(error)); + } + + if ((error = AwaClientGetOperation_Free(&handler)) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free get operation handler\nerror: %s", AwaError_ToString(error)); + } + return result; } -bool PopulateFlowObject(AwaClientSession *session, const char *deviceName, - const char *deviceType, int64_t licenseeID, const char *fcap) +bool PopulateFlowObject(AwaClientSession *session, const char *deviceName, const char *deviceType, int64_t licenseeID, const char *fcap) { - char objectInstancePath[URL_PATH_SIZE] = {0}; - char deviceNameResourcePath[URL_PATH_SIZE] = {0}; - char deviceTypeResourcePath[URL_PATH_SIZE] = {0}; - char licenseeIdResourcePath[URL_PATH_SIZE] = {0}; - char fcapResourcePath[URL_PATH_SIZE] = {0}; - bool status = false; - bool create_resource = false; - AwaError error; - - if (session == NULL || deviceName == NULL || deviceType == NULL || fcap == NULL) - { - LOG(LOG_ERR, "Null parameters passed to %s()", __func__); - return false; - } - - LOG(LOG_INFO, "Populate flow object with device type, licensee id and fcap"); - - //Generate all object and resource paths - if ((error = MAKE_FLOW_OBJECT_INSTANCE_PATH(objectInstancePath) != AwaError_Success || - (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(deviceNameResourcePath, - FlowObjectResourceId_DeviceName)) != AwaError_Success || - (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(deviceTypeResourcePath, - FlowObjectResourceId_DeviceType)) != AwaError_Success || - (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(licenseeIdResourcePath, - FlowObjectResourceId_LicenseeId)) != AwaError_Success || - (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(fcapResourcePath, FlowObjectResourceId_Fcap)) - != AwaError_Success)) - { - LOG(LOG_ERR, "Failed to generate all object and resource paths\nerror: %s", - AwaError_ToString(error)); - return false; - } - - AwaClientSetOperation *handler = AwaClientSetOperation_New(session); - if (handler == NULL) - { - LOG(LOG_ERR, "Failed to create set operation for session"); - return false; - } - - if (!DoesObjectExist(session, Lwm2mObjectId_FlowObject, OBJECT_INSTANCE_ID)) - { - LOG(LOG_DBG, "Flow object instance doesn't exist, so create it"); - if ((error = AwaClientSetOperation_CreateObjectInstance(handler, objectInstancePath)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to create flow object instance\nerror: %s", - AwaError_ToString(error)); - } - create_resource = true; - } - else - { - LOG(LOG_DBG, "Flow object instance exist"); - } - - if (AddResourceToHandler(handler, deviceNameResourcePath, (void *)deviceName, - AwaResourceType_String, create_resource) && - AddResourceToHandler(handler, deviceTypeResourcePath, (void *)deviceType, - AwaResourceType_String, create_resource) && - AddResourceToHandler(handler, fcapResourcePath, (void *)fcap, AwaResourceType_String, - create_resource) && - AddResourceToHandler(handler, licenseeIdResourcePath, &licenseeID, - AwaResourceType_Integer, create_resource)) - { - if ((error = AwaClientSetOperation_Perform(handler, IPC_TIMEOUT)) - == AwaError_Success) - { - status = true; - } - else - { - LOG(LOG_ERR, "Failed to perform set operation\nerror: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to add flow object's resources(device name, device type, licensee id, " - "fcap) to set operation handler"); - } - - if ((error = AwaClientSetOperation_Free(&handler)) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free set operation handler\nerror: %s", - AwaError_ToString(error)); - } - return status; + char objectInstancePath[URL_PATH_SIZE] = {0}; + char deviceNameResourcePath[URL_PATH_SIZE] = {0}; + char deviceTypeResourcePath[URL_PATH_SIZE] = {0}; + char licenseeIdResourcePath[URL_PATH_SIZE] = {0}; + char fcapResourcePath[URL_PATH_SIZE] = {0}; + bool status = false; + bool create_resource = false; + AwaError error; + + if (session == NULL || deviceName == NULL || deviceType == NULL || fcap == NULL) + { + LOG(LOG_ERR, "Null parameters passed to %s()", __func__); + return false; + } + + LOG(LOG_INFO, "Populate flow object with device type, licensee id and fcap"); + + //Generate all object and resource paths + if ((error = MAKE_FLOW_OBJECT_INSTANCE_PATH(objectInstancePath) != AwaError_Success || + (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(deviceNameResourcePath, + FlowObjectResourceId_DeviceName)) != AwaError_Success || + (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(deviceTypeResourcePath, + FlowObjectResourceId_DeviceType)) != AwaError_Success || + (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(licenseeIdResourcePath, + FlowObjectResourceId_LicenseeId)) != AwaError_Success || + (error = MAKE_FLOW_OBJECT_RESOURCE_PATH(fcapResourcePath, FlowObjectResourceId_Fcap)) + != AwaError_Success)) + { + LOG(LOG_ERR, "Failed to generate all object and resource paths\nerror: %s", AwaError_ToString(error)); + return false; + } + + AwaClientSetOperation *handler = AwaClientSetOperation_New(session); + if (handler == NULL) + { + LOG(LOG_ERR, "Failed to create set operation for session"); + return false; + } + + if (!DoesObjectExist(session, Lwm2mObjectId_FlowObject, OBJECT_INSTANCE_ID)) + { + LOG(LOG_DBG, "Flow object instance doesn't exist, so create it"); + if ((error = AwaClientSetOperation_CreateObjectInstance(handler, objectInstancePath)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to create flow object instance\nerror: %s", AwaError_ToString(error)); + } + create_resource = true; + } + else + { + LOG(LOG_DBG, "Flow object instance exist"); + } + + if (AddResourceToHandler(handler, deviceNameResourcePath, (void *)deviceName, + AwaResourceType_String, create_resource) && + AddResourceToHandler(handler, deviceTypeResourcePath, (void *)deviceType, + AwaResourceType_String, create_resource) && + AddResourceToHandler(handler, fcapResourcePath, (void *)fcap, AwaResourceType_String, + create_resource) && + AddResourceToHandler(handler, licenseeIdResourcePath, &licenseeID, + AwaResourceType_Integer, create_resource)) + { + if ((error = AwaClientSetOperation_Perform(handler, IPC_TIMEOUT)) == AwaError_Success) + { + status = true; + } + else + { + LOG(LOG_ERR, "Failed to perform set operation\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to add flow object's resources(device name, device type, licensee id, fcap) to set operation handler"); + } + + if ((error = AwaClientSetOperation_Free(&handler)) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free set operation handler\nerror: %s", AwaError_ToString(error)); + } + return status; } -unsigned int GetResources(AwaClientSession *session, const OBJECT_T objects[], - unsigned int numObjects, char strings[][MAX_STR_SIZE]) +unsigned int GetResources(AwaClientSession *session, const OBJECT_T objects[], unsigned int numObjects, char strings[][MAX_STR_SIZE]) { - const char *value; - const AwaInteger *intValue; - const AwaTime *timeValue; - AwaOpaque opaqueValue; - unsigned int i, j, k, resCount = 0; - unsigned char *opaqueData; - char *offset; - const OBJECT_T *object; - RESOURCE_T *resource; - bool success = true; - AwaError error; - char objectInstancePath[URL_PATH_SIZE]; - char resourcePath[URL_PATH_SIZE]; - const AwaClientGetResponse *response; - AwaClientGetOperation *operation; - - if ((operation = AwaClientGetOperation_New(session)) == NULL) - { - LOG(LOG_ERR, "Failed to create get operation from session"); - return 0; - } - - for (i = 0; i < numObjects; i++) - { - memset(objectInstancePath, 0, URL_PATH_SIZE); - memset(resourcePath, 0, URL_PATH_SIZE); - - object = &objects[i]; - - if ((error = AwaAPI_MakeObjectInstancePath(objectInstancePath, URL_PATH_SIZE, - object->id, OBJECT_INSTANCE_ID)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to create path for %s object\nerror: %s", object->name, - AwaError_ToString(error)); - success = false; - break; - } - if ((error = AwaClientGetOperation_AddPath(operation, objectInstancePath)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to add %s object path to get operation\nerror: %s", object->name, - AwaError_ToString(error)); - success = false; - break; - } - if ((error = AwaClientGetOperation_Perform(operation, IPC_TIMEOUT)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to perform get operation for %s object\nerror: %s", object->name, - AwaError_ToString(error)); - success = false; - break; - } - if ((response = AwaClientGetOperation_GetResponse(operation)) == NULL) - { - LOG(LOG_ERR, "Failed to get response from get operation for %s object", object->name); - success = false; - break; - } - if (!AwaClientGetResponse_ContainsPath(response, objectInstancePath)) - { - LOG(LOG_ERR, "Response doesn't contain %s object path", object->name); - success = false; - break; - } - - for (j = 0; j < object->numResources; j++) - { - resource = &object->resources[j]; - if (!resource->wantToSave) - { - continue; - } - if ((error = AwaAPI_MakeResourcePath(resourcePath, URL_PATH_SIZE, object->id, - OBJECT_INSTANCE_ID, resource->id)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to create path for %s resource\nerror: %s", resource->name, - AwaError_ToString(error)); - success = false; - break; - } - if (!AwaClientGetResponse_HasValue(response, resourcePath)) - { - LOG(LOG_ERR, "Get operation response doesn't contain path of %s resource", - resource->name); - success = false; - break; - } - - switch (resource->type) - { - case AwaResourceType_String: - if ((error = AwaClientGetResponse_GetValueAsCStringPointer(response, - resourcePath, &value)) == AwaError_Success) - { - sprintf(strings[resCount++], "%s=\"%s\"", resource->name, value); - } - break; - - case AwaResourceType_Integer: - if ((error = AwaClientGetResponse_GetValueAsIntegerPointer(response, - resourcePath, &intValue)) == AwaError_Success) - { - sprintf(strings[resCount++], "%s=\"%" PRId64 "\"", resource->name, - *intValue); - } - break; - - case AwaResourceType_Time: - if ((error = AwaClientGetResponse_GetValueAsTimePointer(response, - resourcePath, &timeValue)) == AwaError_Success) - { - sprintf(strings[resCount++], "%s=\"%" PRId64 "\"", resource->name, - *timeValue); - } - break; - - case AwaResourceType_Opaque: - if ((error = AwaClientGetResponse_GetValueAsOpaque(response, resourcePath, - &opaqueValue)) == AwaError_Success) - { - opaqueData = (unsigned char *)opaqueValue.Data; - offset = strings[resCount]; - offset += sprintf(strings[resCount], "%s=\"", resource->name); - for (k = 0; k < DEVICE_ID_SIZE; k++) - { - offset += sprintf(offset, "%02X ", *opaqueData++); - } - sprintf(offset, "\""); - resCount++; - } - break; - - default: - LOG(LOG_ERR, "Unknown resource type"); - error = AwaError_Unspecified; - break; - } - if (error != AwaError_Success) - { - LOG(LOG_ERR, "Failed to get %s resource value from response\nerror: %s", - resource->name, AwaError_ToString(error)); - success = false; - break; - } - } - if (!success) - { - break; - } - } - - if ((error = AwaClientGetOperation_Free(&operation)) != AwaError_Success) - { - LOG(LOG_WARN, "Failed to free get operation\nerror: %s", AwaError_ToString(error)); - } - return (success ? resCount : 0); + const char *value; + const AwaInteger *intValue; + const AwaTime *timeValue; + AwaOpaque opaqueValue; + unsigned int i, j, k, resCount = 0; + unsigned char *opaqueData; + char *offset; + const OBJECT_T *object; + RESOURCE_T *resource; + bool result = true; + AwaError error; + char objectInstancePath[URL_PATH_SIZE]; + char resourcePath[URL_PATH_SIZE]; + const AwaClientGetResponse *response; + AwaClientGetOperation *operation; + + if ((operation = AwaClientGetOperation_New(session)) == NULL) + { + LOG(LOG_ERR, "Failed to create get operation from session"); + return 0; + } + + for (i = 0; i < numObjects; i++) + { + memset(objectInstancePath, 0, URL_PATH_SIZE); + memset(resourcePath, 0, URL_PATH_SIZE); + + object = &objects[i]; + + if ((error = AwaAPI_MakeObjectInstancePath(objectInstancePath, URL_PATH_SIZE, + object->id, OBJECT_INSTANCE_ID)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to create path for %s object\nerror: %s", object->name, AwaError_ToString(error)); + result = false; + break; + } + if ((error = AwaClientGetOperation_AddPath(operation, objectInstancePath)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to add %s object path to get operation\nerror: %s", object->name, AwaError_ToString(error)); + result = false; + break; + } + if ((error = AwaClientGetOperation_Perform(operation, IPC_TIMEOUT)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to perform get operation for %s object\nerror: %s", object->name, AwaError_ToString(error)); + result = false; + break; + } + if ((response = AwaClientGetOperation_GetResponse(operation)) == NULL) + { + LOG(LOG_ERR, "Failed to get response from get operation for %s object", object->name); + result = false; + break; + } + if (!AwaClientGetResponse_ContainsPath(response, objectInstancePath)) + { + LOG(LOG_ERR, "Response doesn't contain %s object path", object->name); + result = false; + break; + } + + for (j = 0; j < object->numResources; j++) + { + resource = &object->resources[j]; + if (!resource->wantToSave) + { + continue; + } + if ((error = AwaAPI_MakeResourcePath(resourcePath, URL_PATH_SIZE, object->id, + OBJECT_INSTANCE_ID, resource->id)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to create path for %s resource\nerror: %s", resource->name, AwaError_ToString(error)); + result = false; + break; + } + if (!AwaClientGetResponse_HasValue(response, resourcePath)) + { + LOG(LOG_ERR, "Get operation response doesn't contain path of %s resource", resource->name); + result = false; + break; + } + + switch (resource->type) + { + case AwaResourceType_String: + if ((error = AwaClientGetResponse_GetValueAsCStringPointer(response, resourcePath, &value)) == AwaError_Success) + { + sprintf(strings[resCount++], "%s=\"%s\"", resource->name, value); + } + break; + + case AwaResourceType_Integer: + if ((error = AwaClientGetResponse_GetValueAsIntegerPointer(response, resourcePath, &intValue)) == AwaError_Success) + { + sprintf(strings[resCount++], "%s=\"%" PRId64 "\"", resource->name, *intValue); + } + break; + + case AwaResourceType_Time: + if ((error = AwaClientGetResponse_GetValueAsTimePointer(response, resourcePath, &timeValue)) == AwaError_Success) + { + sprintf(strings[resCount++], "%s=\"%" PRId64 "\"", resource->name, *timeValue); + } + break; + + case AwaResourceType_Opaque: + if ((error = AwaClientGetResponse_GetValueAsOpaque(response, resourcePath, &opaqueValue)) == AwaError_Success) + { + opaqueData = (unsigned char *)opaqueValue.Data; + offset = strings[resCount]; + offset += sprintf(strings[resCount], "%s=\"", resource->name); + for (k = 0; k < DEVICE_ID_SIZE; k++) + { + offset += sprintf(offset, "%02X ", *opaqueData++); + } + sprintf(offset, "\""); + resCount++; + } + break; + + default: + LOG(LOG_ERR, "Unknown resource type"); + error = AwaError_Unspecified; + break; + } + if (error != AwaError_Success) + { + LOG(LOG_ERR, "Failed to get %s resource value from response\nerror: %s", resource->name, AwaError_ToString(error)); + result = false; + break; + } + } + if (!result) + { + break; + } + } + + if ((error = AwaClientGetOperation_Free(&operation)) != AwaError_Success) + { + LOG(LOG_WARN, "Failed to free get operation\nerror: %s", AwaError_ToString(error)); + } + return (result ? resCount : 0); } diff --git a/src/fdm_register.h b/src/fdm_register.h index 240aadc..80bbdae 100644 --- a/src/fdm_register.h +++ b/src/fdm_register.h @@ -49,8 +49,7 @@ * @param[in] numObjects Number of objects to define and register. * @return true for success otherwise false. */ -bool DefineObjectsAtClient(AwaClientSession *session, const OBJECT_T *objects, - unsigned int numObjects); +bool DefineObjectsAtClient(AwaClientSession *session, const OBJECT_T *objects, unsigned int numObjects); /** * @brief Define objects and their resources and register them with Awa server. @@ -59,8 +58,7 @@ bool DefineObjectsAtClient(AwaClientSession *session, const OBJECT_T *objects, * @param[in] numObjects Number of objects to define and register. * @return true for success otherwise false. */ -bool DefineObjectsAtServer(AwaServerSession *session, const OBJECT_T *objects, - unsigned int numObjects); +bool DefineObjectsAtServer(AwaServerSession *session, const OBJECT_T *objects, unsigned int numObjects); /** * @brief Check lwm2m object existence. @@ -69,8 +67,7 @@ bool DefineObjectsAtServer(AwaServerSession *session, const OBJECT_T *objects, * @param[in] objectInstanceId The numerical object instance id. * @return true for success otherwise false. */ -bool DoesObjectExist(AwaClientSession *session, AwaObjectID objectId, - AwaObjectInstanceID objectInstanceId); +bool DoesObjectExist(AwaClientSession *session, AwaObjectID objectId, AwaObjectInstanceID objectInstanceId); /** * @brief Populate flow object with device type, licensee id and fcap. @@ -81,8 +78,7 @@ bool DoesObjectExist(AwaClientSession *session, AwaObjectID objectId, * @param[in] fcap FlowCloud Access Provisioning Code. * @return true for success otherwise false. */ -bool PopulateFlowObject(AwaClientSession *session, const char *deviceName, - const char *deviceType, int64_t licenseeID, const char *fcap); +bool PopulateFlowObject(AwaClientSession *session, const char *deviceName, const char *deviceType, int64_t licenseeID, const char *fcap); /** * @brief Set specified value to resource. @@ -92,8 +88,7 @@ bool PopulateFlowObject(AwaClientSession *session, const char *deviceName, * @param[in] type Resource type. * @return true for success otherwise false. */ -bool SetResource(AwaClientSession *session, const char *resourcePath, void *value, - AwaResourceType type); +bool SetResource(AwaClientSession *session, const char *resourcePath, void *value, AwaResourceType type); /** * @brief Get value of specified object's resources for which wantToSave parameter is set. @@ -103,7 +98,6 @@ bool SetResource(AwaClientSession *session, const char *resourcePath, void *valu * @param[out] strings Resource value strings. * @return resource count for success and 0 for fail. */ -unsigned int GetResources(AwaClientSession *session, const OBJECT_T objects[], - unsigned int numObjects, char strings[][MAX_STR_SIZE]); +unsigned int GetResources(AwaClientSession *session, const OBJECT_T objects[], unsigned int numObjects, char strings[][MAX_STR_SIZE]); -#endif /* FDM_REGISTER_H */ +#endif /* FDM_REGISTER_H */ diff --git a/src/fdm_server_session.c b/src/fdm_server_session.c index 2163cde..9481f38 100644 --- a/src/fdm_server_session.c +++ b/src/fdm_server_session.c @@ -46,50 +46,50 @@ AwaServerSession *Server_EstablishSession(const char *address, unsigned int port) { - // Initialise Device Management session - AwaServerSession *session; - session = AwaServerSession_New(); + // Initialise Device Management session + AwaServerSession *session; + session = AwaServerSession_New(); - if (session == NULL) - { - LOG(LOG_ERR, "Failed to create new server session"); - return NULL; - } + if (session == NULL) + { + LOG(LOG_ERR, "Failed to create new server session"); + return NULL; + } - if (AwaServerSession_SetIPCAsUDP(session, address, port) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to set IPC as UDP for server session"); - AwaServerSession_Free(&session); - return NULL; - } + if (AwaServerSession_SetIPCAsUDP(session, address, port) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to set IPC as UDP for server session"); + AwaServerSession_Free(&session); + return NULL; + } - if (AwaServerSession_Connect(session) == AwaError_Success) - { - LOG(LOG_INFO, "Session established with server"); - } - else - { - LOG(LOG_ERR, "Failed to establish session with server"); - AwaServerSession_Free(&session); - } - return session; + if (AwaServerSession_Connect(session) == AwaError_Success) + { + LOG(LOG_INFO, "Session established with server"); + } + else + { + LOG(LOG_ERR, "Failed to establish session with server"); + AwaServerSession_Free(&session); + } + return session; } void Server_ReleaseSession(AwaServerSession **session) { - if (session == NULL) - { - return; - } + if (session == NULL) + { + return; + } - if (AwaServerSession_Disconnect(*session) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to disconnect session with server"); - } + if (AwaServerSession_Disconnect(*session) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to disconnect session with server"); + } - if (AwaServerSession_Free(session) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to free session with server"); - } + if (AwaServerSession_Free(session) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to free session with server"); + } } diff --git a/src/fdm_server_session.h b/src/fdm_server_session.h index 7981ec4..6cb5671 100644 --- a/src/fdm_server_session.h +++ b/src/fdm_server_session.h @@ -30,8 +30,7 @@ /** * @file fdm_server_session.h - * @brief Header file for exposing operations to establish and release sessions with Awa LWM2M - * server. + * @brief Header file for exposing operations to establish and release sessions with Awa LWM2M server. */ #ifndef FDM_SERVER_SESSION_H @@ -53,4 +52,4 @@ AwaServerSession *Server_EstablishSession(const char *address, unsigned int port */ void Server_ReleaseSession(AwaServerSession **session); -#endif /* FDM_SERVER_SESSION_H */ +#endif /* FDM_SERVER_SESSION_H */ diff --git a/src/fdm_subscribe.c b/src/fdm_subscribe.c index ba9af77..57671bd 100644 --- a/src/fdm_subscribe.c +++ b/src/fdm_subscribe.c @@ -56,122 +56,110 @@ */ static void flowObjectCallback(const AwaChangeSet *changeSet, void *context) { - static bool done = false; - char licenseeChallengeResourcePath[URL_PATH_SIZE] = {0}; - char hashIterationsResourcePath[URL_PATH_SIZE] = {0}; - AwaOpaque licenseeChallenge = {0}; - Verification *verificationData = (Verification *)context; - AwaError error; - - if (changeSet == NULL || context == NULL) - { - LOG(LOG_DBG, "Flow object change notification doesn't contain any data"); - return; - } - - LOG(LOG_INFO, "Flow object updated"); - - // Extract and store licensee challenge - if ((error = MAKE_FLOW_OBJECT_RESOURCE_PATH(licenseeChallengeResourcePath, - FlowObjectResourceId_LicenseeChallenge)) == AwaError_Success) - { - if (AwaChangeSet_ContainsPath(changeSet, licenseeChallengeResourcePath)) - { - if ((error = AwaChangeSet_GetValueAsOpaque(changeSet, licenseeChallengeResourcePath, - &licenseeChallenge)) == AwaError_Success && - licenseeChallenge.Data != NULL && - licenseeChallenge.Size > 0) - { - if (verificationData->challenge.Data != NULL) - { - free(verificationData->challenge.Data); - } - verificationData->challenge.Data = malloc(licenseeChallenge.Size); - if (verificationData->challenge.Data != NULL) - { - memcpy(verificationData->challenge.Data, licenseeChallenge.Data, - licenseeChallenge.Size); - verificationData->challenge.Size = licenseeChallenge.Size; - verificationData->hasChallenge = true; - } - else - { - LOG(LOG_ERR, "Failed to allocate memory for storing licensee challenge"); - } - } - else - { - LOG(LOG_ERR, "Failed to get licensee challenge\nerror: %s", - AwaError_ToString(error)); - } - } - else - { - LOG(LOG_DBG, "Flow object change notification doesn't contain licensee challenge " - "resource"); - } - } - else - { - LOG(LOG_DBG, "Failed to create licensee challenge resource path\nerror: %s", - AwaError_ToString(error)); - } - - if ((error = MAKE_FLOW_OBJECT_RESOURCE_PATH(hashIterationsResourcePath, - FlowObjectResourceId_HashIterations)) == AwaError_Success) - { - if (AwaChangeSet_ContainsPath(changeSet, hashIterationsResourcePath)) - { - const AwaInteger *iterationsValue = NULL; - if (AwaChangeSet_GetValueAsIntegerPointer(changeSet, hashIterationsResourcePath, - &iterationsValue) == AwaError_Success) - { - verificationData->iterations = *iterationsValue; - verificationData->hasIterations = true; - } - else - { - LOG(LOG_ERR, "Failed to get hash iterations"); - } - } - else - { - LOG(LOG_DBG, "Flow object change notification doesn't contain hash iterations resource"); - } - } - else - { - LOG(LOG_DBG, "Failed to create hash iterations resource path\nerror: %s", - AwaError_ToString(error)); - } - - // no errors yet, check to see if we have what we need for provisioning - if (verificationData->waitForServerResponse && verificationData->hasChallenge && - verificationData->hasIterations && !done) - { - verificationData->verifyLicensee = true; - done = true; // do this step once, because setting an object that we are observing will - // cause an infinite loop - } + static bool done = false; + char licenseeChallengeResourcePath[URL_PATH_SIZE] = {0}; + char hashIterationsResourcePath[URL_PATH_SIZE] = {0}; + AwaOpaque licenseeChallenge = {0}; + Verification *verificationData = (Verification *)context; + AwaError error; + + if (changeSet == NULL || context == NULL) + { + LOG(LOG_DBG, "Flow object change notification doesn't contain any data"); + return; + } + + LOG(LOG_INFO, "Flow object updated"); + + // Extract and store licensee challenge + if ((error = MAKE_FLOW_OBJECT_RESOURCE_PATH(licenseeChallengeResourcePath, FlowObjectResourceId_LicenseeChallenge)) == AwaError_Success) + { + if (AwaChangeSet_ContainsPath(changeSet, licenseeChallengeResourcePath)) + { + if ((error = AwaChangeSet_GetValueAsOpaque(changeSet, licenseeChallengeResourcePath, + &licenseeChallenge)) == AwaError_Success && licenseeChallenge.Data != NULL && licenseeChallenge.Size > 0) + { + if (verificationData->challenge.Data != NULL) + { + free(verificationData->challenge.Data); + } + + verificationData->challenge.Data = malloc(licenseeChallenge.Size); + + if (verificationData->challenge.Data != NULL) + { + memcpy(verificationData->challenge.Data, licenseeChallenge.Data, licenseeChallenge.Size); + verificationData->challenge.Size = licenseeChallenge.Size; + verificationData->hasChallenge = true; + } + else + { + LOG(LOG_ERR, "Failed to allocate memory for storing licensee challenge"); + } + } + else + { + LOG(LOG_ERR, "Failed to get licensee challenge\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_DBG, "Flow object change notification doesn't contain licensee challenge resource"); + } + } + else + { + LOG(LOG_DBG, "Failed to create licensee challenge resource path\nerror: %s", AwaError_ToString(error)); + } + + if ((error = MAKE_FLOW_OBJECT_RESOURCE_PATH(hashIterationsResourcePath, FlowObjectResourceId_HashIterations)) == AwaError_Success) + { + if (AwaChangeSet_ContainsPath(changeSet, hashIterationsResourcePath)) + { + const AwaInteger *iterationsValue = NULL; + if (AwaChangeSet_GetValueAsIntegerPointer(changeSet, hashIterationsResourcePath, &iterationsValue) == AwaError_Success) + { + verificationData->iterations = *iterationsValue; + verificationData->hasIterations = true; + } + else + { + LOG(LOG_ERR, "Failed to get hash iterations"); + } + } + else + { + LOG(LOG_DBG, "Flow object change notification doesn't contain hash iterations resource"); + } + } + else + { + LOG(LOG_DBG, "Failed to create hash iterations resource path\nerror: %s", AwaError_ToString(error)); + } + + // no errors yet, check to see if we have what we need for provisioning + if (verificationData->waitForServerResponse && verificationData->hasChallenge && verificationData->hasIterations && !done) + { + verificationData->verifyLicensee = true; + done = true; // do this step once, because setting an object that we are observing will cause an infinite loop + } } /** -* @brief Check whether ChangeSet contains specified resource and also whether that resource contains -* any value. +* @brief Check whether ChangeSet contains specified resource and also whether that resource contains any value. * @param[in] changeSet A pointer to a valid ChangeSet. * @param[in] resourcePath The resource path with which to query the Get Response. * @return true for success otherwise false. - */ +*/ static bool HasResource(const AwaChangeSet *changeSet, const char *resourcePath) { - if (changeSet == NULL || resourcePath == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return false; - } - - return (AwaChangeSet_ContainsPath(changeSet, resourcePath) && - AwaChangeSet_HasValue(changeSet, resourcePath)); + if (changeSet == NULL || resourcePath == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return false; + } + + return (AwaChangeSet_ContainsPath(changeSet, resourcePath) && AwaChangeSet_HasValue(changeSet, resourcePath)); } /** @@ -183,266 +171,237 @@ static bool HasResource(const AwaChangeSet *changeSet, const char *resourcePath) */ static void flowAccessCallback(const AwaChangeSet *changeSet, void *context) { - char urlPath[URL_PATH_SIZE] = {0}; - char keyPath[URL_PATH_SIZE] = {0}; - char secretPath[URL_PATH_SIZE] = {0}; - char tokenPath[URL_PATH_SIZE] = {0}; - char tokenExpiryPath[URL_PATH_SIZE] = {0}; - Verification *verificationData = (Verification *)context; - AwaError error; - - if (changeSet == NULL || context == NULL) - { - return; - } - - LOG(LOG_INFO, "Flow access object updated"); - - if ((error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(urlPath, FlowAccessResourceId_Url)) - != AwaError_Success || - (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(keyPath, FlowAccessResourceId_CustomerKey)) - != AwaError_Success || - (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(secretPath, - FlowAccessResourceId_CustomerSecret)) != AwaError_Success || - (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(tokenPath, - FlowAccessResourceId_RememberMeToken)) != AwaError_Success || - (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(tokenExpiryPath, - FlowAccessResourceId_RememberMeTokenExpiry)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to generate resource path for all Flow access resources\nerror: %s", - AwaError_ToString(error)); - return; - } - - if (!HasResource(changeSet, urlPath) || - !HasResource(changeSet, keyPath) || - !HasResource(changeSet, secretPath) || - !HasResource(changeSet, tokenPath) || - !HasResource(changeSet, tokenExpiryPath)) - { - LOG(LOG_ERR, "Flow access notification doesn't have all the resources"); - verificationData->waitForServerResponse = false; - return; - } - - LOG(LOG_INFO, "Gateway device provisioned successfully"); - verificationData->waitForServerResponse = false; - verificationData->isProvisionSuccess = true; + char urlPath[URL_PATH_SIZE] = {0}; + char keyPath[URL_PATH_SIZE] = {0}; + char secretPath[URL_PATH_SIZE] = {0}; + char tokenPath[URL_PATH_SIZE] = {0}; + char tokenExpiryPath[URL_PATH_SIZE] = {0}; + Verification *verificationData = (Verification *)context; + AwaError error; + + if (changeSet == NULL || context == NULL) + { + return; + } + + LOG(LOG_INFO, "Flow access object updated"); + + if ((error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(urlPath, FlowAccessResourceId_Url)) + != AwaError_Success || + (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(keyPath, FlowAccessResourceId_CustomerKey)) + != AwaError_Success || + (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(secretPath, + FlowAccessResourceId_CustomerSecret)) != AwaError_Success || + (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(tokenPath, + FlowAccessResourceId_RememberMeToken)) != AwaError_Success || + (error = MAKE_FLOW_ACCESS_OBJECT_RESOURCE_PATH(tokenExpiryPath, + FlowAccessResourceId_RememberMeTokenExpiry)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to generate resource path for all Flow access resources\nerror: %s", AwaError_ToString(error)); + return; + } + + if (!HasResource(changeSet, urlPath) || + !HasResource(changeSet, keyPath) || + !HasResource(changeSet, secretPath) || + !HasResource(changeSet, tokenPath) || + !HasResource(changeSet, tokenExpiryPath)) + { + LOG(LOG_ERR, "Flow access notification doesn't have all the resources"); + verificationData->waitForServerResponse = false; + return; + } + + LOG(LOG_INFO, "Gateway device provisioned successfully"); + verificationData->waitForServerResponse = false; + verificationData->isProvisionSuccess = true; } -bool SubscribeToFlowObjects(AwaClientSession *session, FlowSubscriptions *subscriptions, - Verification *verificationData) +bool SubscribeToFlowObjects(AwaClientSession *session, FlowSubscriptions *subscriptions, Verification *verificationData) { - char flowObjectInstancePath[URL_PATH_SIZE] = {0}; - char flowAccessInstancePath[URL_PATH_SIZE] = {0}; - const AwaClientSubscribeResponse *response; - const AwaPathResult *flowObjectSubscribeResult; - const AwaPathResult *flowAccessSubscribeResult; - bool success = false; - AwaError error; - - if(session == NULL || subscriptions == NULL || verificationData == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return false; - } - - LOG(LOG_INFO, "Subscribing to Flow and Flow Access object change notifications"); - - if ((error = MAKE_FLOW_OBJECT_INSTANCE_PATH(flowObjectInstancePath)) != AwaError_Success || - (error = MAKE_FLOW_ACCESS_OBJECT_PATH(flowAccessInstancePath)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to generate path for %u or %u objects\nerror: %s", - Lwm2mObjectId_FlowObject, Lwm2mObjectId_FlowAccess, AwaError_ToString(error)); - return false; - } - - // Subscribe to Flow and Flow access object change notifications and the specified callback - // function will be fired on AwaClientSession_DispatchCallbacks if the subscribed entity has - // changed since the session callbacks were last dispatched. - subscriptions->flowObjectChange = AwaClientChangeSubscription_New(flowObjectInstancePath, - flowObjectCallback, verificationData); - if (subscriptions->flowObjectChange == NULL) - { - LOG(LOG_ERR, "Failed to create flow subscription object"); - return false; - } - subscriptions->flowAccessObjectChange = - AwaClientChangeSubscription_New(flowAccessInstancePath, flowAccessCallback, - verificationData); - if (subscriptions->flowAccessObjectChange == NULL) - { - LOG(LOG_ERR, "Failed to create flow access subscription object"); - return false; - } - - AwaClientSubscribeOperation *operation = AwaClientSubscribeOperation_New(session); - if (operation == NULL) - { - LOG(LOG_ERR, "Failed to create subscribe operation from session"); - return false; - } - - if ((error = AwaClientSubscribeOperation_AddChangeSubscription(operation, - subscriptions->flowObjectChange)) == AwaError_Success && - (error = AwaClientSubscribeOperation_AddChangeSubscription(operation, - subscriptions->flowAccessObjectChange)) == AwaError_Success) - { - if ((error = AwaClientSubscribeOperation_Perform(operation, IPC_TIMEOUT)) - == AwaError_Success) - { - response = AwaClientSubscribeOperation_GetResponse(operation); - if (((flowObjectSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, - flowObjectInstancePath)) != NULL) && - ((flowAccessSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, - flowAccessInstancePath)) != NULL)) - { - if ((error = AwaPathResult_GetError(flowObjectSubscribeResult)) - == AwaError_Success && - (error = AwaPathResult_GetError(flowAccessSubscribeResult)) - == AwaError_Success) - { - success = true; - } - else - { - LOG(LOG_ERR, "Failed to get error from subscribe result for flow object or " - "flow access object or both\nerror: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to get flow object or flow access object path in subscribe " - "operation response"); - } - } - else - { - LOG(LOG_ERR, "Failed to perform subscribe operation\nerror: %s", - AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to add change subscription to subscribe operation of flow object or " - "flow access object or both\nerror: %s", AwaError_ToString(error)); - } - - if ((error = AwaClientSubscribeOperation_Free(&operation)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to free subscribe operation\nerror: %s", AwaError_ToString(error)); - } - return success; + char flowObjectInstancePath[URL_PATH_SIZE] = {0}; + char flowAccessInstancePath[URL_PATH_SIZE] = {0}; + const AwaClientSubscribeResponse *response; + const AwaPathResult *flowObjectSubscribeResult; + const AwaPathResult *flowAccessSubscribeResult; + bool result = false; + AwaError error; + + if(session == NULL || subscriptions == NULL || verificationData == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return false; + } + + LOG(LOG_INFO, "Subscribing to Flow and Flow Access object change notifications"); + + if ((error = MAKE_FLOW_OBJECT_INSTANCE_PATH(flowObjectInstancePath)) != AwaError_Success || + (error = MAKE_FLOW_ACCESS_OBJECT_PATH(flowAccessInstancePath)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to generate path for %u or %u objects\nerror: %s", + Lwm2mObjectId_FlowObject, Lwm2mObjectId_FlowAccess, AwaError_ToString(error)); + return false; + } + + // Subscribe to Flow and Flow access object change notifications and the specified callback + // function will be fired on AwaClientSession_DispatchCallbacks if the subscribed entity has + // changed since the session callbacks were last dispatched. + subscriptions->flowObjectChange = AwaClientChangeSubscription_New(flowObjectInstancePath, flowObjectCallback, verificationData); + if (subscriptions->flowObjectChange == NULL) + { + LOG(LOG_ERR, "Failed to create flow subscription object"); + return false; + } + subscriptions->flowAccessObjectChange = AwaClientChangeSubscription_New(flowAccessInstancePath, flowAccessCallback, verificationData); + if (subscriptions->flowAccessObjectChange == NULL) + { + LOG(LOG_ERR, "Failed to create flow access subscription object"); + return false; + } + + AwaClientSubscribeOperation *operation = AwaClientSubscribeOperation_New(session); + if (operation == NULL) + { + LOG(LOG_ERR, "Failed to create subscribe operation from session"); + return false; + } + + if ((error = AwaClientSubscribeOperation_AddChangeSubscription(operation, subscriptions->flowObjectChange)) == AwaError_Success && + (error = AwaClientSubscribeOperation_AddChangeSubscription(operation, subscriptions->flowAccessObjectChange)) == AwaError_Success) + { + if ((error = AwaClientSubscribeOperation_Perform(operation, IPC_TIMEOUT)) == AwaError_Success) + { + response = AwaClientSubscribeOperation_GetResponse(operation); + if (((flowObjectSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, flowObjectInstancePath)) != NULL) && + ((flowAccessSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, flowAccessInstancePath)) != NULL)) + { + if ((error = AwaPathResult_GetError(flowObjectSubscribeResult)) == AwaError_Success && + (error = AwaPathResult_GetError(flowAccessSubscribeResult)) == AwaError_Success) + { + result = true; + } + else + { + LOG(LOG_ERR, "Failed to get error from subscribe result for flow object or " + "flow access object or both\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to get flow object or flow access object path in subscribe operation response"); + } + } + else + { + LOG(LOG_ERR, "Failed to perform subscribe operation\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to add change subscription to subscribe operation of flow object or " + "flow access object or both\nerror: %s", AwaError_ToString(error)); + } + + if ((error = AwaClientSubscribeOperation_Free(&operation)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to free subscribe operation\nerror: %s", AwaError_ToString(error)); + } + return result; } void UnSubscribeFromFlowObjects(AwaClientSession *session, FlowSubscriptions *subscriptions) { - AwaClientSubscribeOperation *operation; - const AwaClientSubscribeResponse *response; - const AwaPathResult *flowSubscribeResult; - const AwaPathResult *flowAccessSubscribeResult; - char flowObjectInstancePath[URL_PATH_SIZE]; - char flowAccessPath[URL_PATH_SIZE]; - bool success = true; - AwaError error; - - if(session == NULL || subscriptions == NULL) - { - LOG(LOG_ERR, "Null params passed to %s()", __func__); - return; - } - - LOG(LOG_INFO, "Unsubscribe from flow and flow access change notifications"); - - if ((error = MAKE_FLOW_OBJECT_INSTANCE_PATH(flowObjectInstancePath)) != AwaError_Success || - (error = MAKE_FLOW_ACCESS_OBJECT_PATH(flowAccessPath)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to create path for flow object or flow access object\nerror: %s", - AwaError_ToString(error)); - success = false; - } - - if (success && - ((operation = AwaClientSubscribeOperation_New(session)) == NULL)) - { - LOG(LOG_ERR, "Failed to create subscribe operation from session"); - success = false; - } - - if (success && - (error = AwaClientSubscribeOperation_AddCancelChangeSubscription(operation, - subscriptions->flowObjectChange)) == AwaError_Success && - (error = AwaClientSubscribeOperation_AddCancelChangeSubscription(operation, - subscriptions->flowAccessObjectChange)) == AwaError_Success) - { - if ((error = AwaClientSubscribeOperation_Perform(operation, IPC_TIMEOUT)) - == AwaError_Success) - { - response = AwaClientSubscribeOperation_GetResponse(operation); - if (((flowSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, - flowObjectInstancePath)) != NULL) && - (flowAccessSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, - flowAccessPath)) != NULL) - { - if ((error = AwaPathResult_GetError(flowSubscribeResult)) - == AwaError_Success && - (error = AwaPathResult_GetError(flowAccessSubscribeResult)) - == AwaError_Success) - { - LOG(LOG_DBG, "Successfully cancelled subscription to flow and flow access " - "update events"); - } - else - { - LOG(LOG_ERR, "Failed to cancel subscription to flow object or flow access " - "object update events or both\nerror: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to get flow object or flow acccess object path from subscribe " - "operation response"); - } - } - else - { - LOG(LOG_ERR, "Failed to perform subscribe operation for flow object or flow access " - "object or both\nerror: %s", AwaError_ToString(error)); - } - } - else - { - LOG(LOG_ERR, "Failed to add cancel flag to a change subscription in a specified subscribe" - "operation for flow object or flow access object or both\nerror: %s", - AwaError_ToString(error)); - } - - if (subscriptions->flowObjectChange != NULL) - { - if ((error = AwaClientChangeSubscription_Free(&subscriptions->flowObjectChange)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to free flow subscription object\nerror: %s", - AwaError_ToString(error)); - } - } - - if (subscriptions->flowAccessObjectChange != NULL) - { - if ((error = AwaClientChangeSubscription_Free(&subscriptions->flowAccessObjectChange)) - != AwaError_Success) - { - LOG(LOG_ERR, "Failed to free flow access subscription object\nerror: %s", - AwaError_ToString(error)); - } - } - - if (operation != NULL) - { - if ((error = AwaClientSubscribeOperation_Free(&operation)) != AwaError_Success) - { - LOG(LOG_ERR, "Failed to free subscribe operation\nerror: %s", - AwaError_ToString(error)); - } - } + AwaClientSubscribeOperation *operation; + const AwaClientSubscribeResponse *response; + const AwaPathResult *flowSubscribeResult; + const AwaPathResult *flowAccessSubscribeResult; + char flowObjectInstancePath[URL_PATH_SIZE]; + char flowAccessPath[URL_PATH_SIZE]; + bool result = true; + AwaError error; + + if(session == NULL || subscriptions == NULL) + { + LOG(LOG_ERR, "Null params passed to %s()", __func__); + return; + } + + LOG(LOG_INFO, "Unsubscribe from flow and flow access change notifications"); + + if ((error = MAKE_FLOW_OBJECT_INSTANCE_PATH(flowObjectInstancePath)) != AwaError_Success || + (error = MAKE_FLOW_ACCESS_OBJECT_PATH(flowAccessPath)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to create path for flow object or flow access object\nerror: %s", AwaError_ToString(error)); + result = false; + } + + if (result && ((operation = AwaClientSubscribeOperation_New(session)) == NULL)) + { + LOG(LOG_ERR, "Failed to create subscribe operation from session"); + result = false; + } + + if (result && + (error = AwaClientSubscribeOperation_AddCancelChangeSubscription(operation, + subscriptions->flowObjectChange)) == AwaError_Success && + (error = AwaClientSubscribeOperation_AddCancelChangeSubscription(operation, + subscriptions->flowAccessObjectChange)) == AwaError_Success) + { + if ((error = AwaClientSubscribeOperation_Perform(operation, IPC_TIMEOUT)) == AwaError_Success) + { + response = AwaClientSubscribeOperation_GetResponse(operation); + if (((flowSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, flowObjectInstancePath)) != NULL) && + (flowAccessSubscribeResult = AwaClientSubscribeResponse_GetPathResult(response, flowAccessPath)) != NULL) + { + if ((error = AwaPathResult_GetError(flowSubscribeResult)) == AwaError_Success && + (error = AwaPathResult_GetError(flowAccessSubscribeResult)) == AwaError_Success) + { + LOG(LOG_DBG, "Successfully cancelled subscription to flow and flow access update events"); + } + else + { + LOG(LOG_ERR, "Failed to cancel subscription to flow object or flow access " + "object update events or both\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to get flow object or flow acccess object path from subscribe operation response"); + } + } + else + { + LOG(LOG_ERR, "Failed to perform subscribe operation for flow object or flow access object or both\nerror: %s", AwaError_ToString(error)); + } + } + else + { + LOG(LOG_ERR, "Failed to add cancel flag to a change subscription in a specified subscribe" + "operation for flow object or flow access object or both\nerror: %s", + AwaError_ToString(error)); + } + + if (subscriptions->flowObjectChange != NULL) + { + if ((error = AwaClientChangeSubscription_Free(&subscriptions->flowObjectChange)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to free flow subscription object\nerror: %s", AwaError_ToString(error)); + } + } + + if (subscriptions->flowAccessObjectChange != NULL) + { + if ((error = AwaClientChangeSubscription_Free(&subscriptions->flowAccessObjectChange)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to free flow access subscription object\nerror: %s", AwaError_ToString(error)); + } + } + + if (operation != NULL) + { + if ((error = AwaClientSubscribeOperation_Free(&operation)) != AwaError_Success) + { + LOG(LOG_ERR, "Failed to free subscribe operation\nerror: %s", AwaError_ToString(error)); + } + } } diff --git a/src/fdm_subscribe.h b/src/fdm_subscribe.h index 8b3b564..4617998 100644 --- a/src/fdm_subscribe.h +++ b/src/fdm_subscribe.h @@ -46,8 +46,7 @@ * @param[in] verificationData Licensee verification data. * @return true for success otherwise false. */ -bool SubscribeToFlowObjects(AwaClientSession *session, FlowSubscriptions *subscriptions, - Verification *verificationData); +bool SubscribeToFlowObjects(AwaClientSession *session, FlowSubscriptions *subscriptions, Verification *verificationData); /** * @brief Send a request to the Awa LWM2M Core to remove the Change Subscriptions for flow and @@ -58,4 +57,4 @@ bool SubscribeToFlowObjects(AwaClientSession *session, FlowSubscriptions *subscr */ void UnSubscribeFromFlowObjects(AwaClientSession *session, FlowSubscriptions *subscriptions); -#endif /* FDM_SUBSCRIBE_H */ +#endif /* FDM_SUBSCRIBE_H */ diff --git a/src/utils.c b/src/utils.c index 3fabfc2..7151e39 100644 --- a/src/utils.c +++ b/src/utils.c @@ -42,16 +42,16 @@ */ void CopyStringWithoutSpace(char *targetString, const char *sourceString) { - unsigned int i = 0, j = 0; + unsigned int i = 0, j = 0; - while (sourceString[i] != '\0') - { - if (sourceString[i] != ' ') - { - targetString[j] = sourceString[i]; - j++; - } - i++; - } - targetString[j] = '\0'; + while (sourceString[i] != '\0') + { + if (sourceString[i] != ' ') + { + targetString[j] = sourceString[i]; + j++; + } + i++; + } + targetString[j] = '\0'; } diff --git a/src/utils.h b/src/utils.h index 33eb6db..72de39f 100644 --- a/src/utils.h +++ b/src/utils.h @@ -36,7 +36,7 @@ #ifndef UTILS_H #define UTILS_H -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -45,8 +45,8 @@ extern "C" { */ void CopyStringWithoutSpace(char *targetString, const char *sourceString); -#ifdef __cplusplus +#ifdef __cplusplus } #endif -#endif /* UTILS_H */ +#endif /* UTILS_H */