void CALEGattRemoteCharacteristicWriteCb(char *remoteAddress, bt_gatt_server_h server, bt_gatt_h charPath, int offset, char *charValue, int charValueLen, void *userData) { OIC_LOG(DEBUG, TAG, "IN"); if (NULL == charValue || NULL == remoteAddress) { OIC_LOG(ERROR, TAG, "Param callback values are NULL"); return; } OIC_LOG_V(DEBUG, TAG, "charPath = [%s] charValue = [%s] len [%d]", (char *)charPath, charValue, charValueLen); uint8_t *data = OICMalloc(charValueLen); if (NULL == data) { OIC_LOG(ERROR, TAG, "Malloc failed!"); return; } memcpy(data, charValue, charValueLen); ca_mutex_lock(g_leReqRespCbMutex); if (NULL == g_leServerDataReceivedCallback) { OIC_LOG(ERROR, TAG, "gReqRespCallback is NULL!"); ca_mutex_unlock(g_leReqRespCbMutex); OICFree(data); return; } OIC_LOG(DEBUG, TAG, "Sending data up !"); uint32_t sentLength = 0; g_leServerDataReceivedCallback(remoteAddress, data, charValueLen, &sentLength); ca_mutex_unlock(g_leReqRespCbMutex); OICFree(data); OIC_LOG(DEBUG, TAG, "OUT"); }
ca_mutex ca_mutex_new(void) { ca_mutex retVal = NULL; ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(sizeof(ca_mutex_internal)); if (NULL != mutexInfo) { // create the mutex with the attributes set int ret=pthread_mutex_init(&(mutexInfo->mutex), PTHREAD_MUTEX_DEFAULT); if (0 == ret) { retVal = (ca_mutex) mutexInfo; } else { OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__); OICFree(mutexInfo); } } return retVal; }
static void OCCopyPropertyValueArray(OCRepPayloadValue* dest, OCRepPayloadValue* source) { if (!dest || !source) { return; } size_t dimTotal = calcDimTotal(source->arr.dimensions); switch(source->arr.type) { case OCREP_PROP_INT: dest->arr.iArray = (int64_t*)OICMalloc(dimTotal * sizeof(int64_t)); memcpy(dest->arr.iArray, source->arr.iArray, dimTotal * sizeof(int64_t)); break; case OCREP_PROP_DOUBLE: dest->arr.dArray = (double*)OICMalloc(dimTotal * sizeof(double)); memcpy(dest->arr.dArray, source->arr.dArray, dimTotal * sizeof(double)); break; case OCREP_PROP_BOOL: dest->arr.bArray = (bool*)OICMalloc(dimTotal * sizeof(bool)); memcpy(dest->arr.bArray, source->arr.bArray, dimTotal * sizeof(bool)); break; case OCREP_PROP_STRING: dest->arr.strArray = (char**)OICMalloc(dimTotal * sizeof(char*)); for(size_t i = 0; i < dimTotal; ++i) { dest->arr.strArray[i] = OICStrdup(source->arr.strArray[i]); } break; case OCREP_PROP_OBJECT: dest->arr.objArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*)); for(size_t i = 0; i < dimTotal; ++i) { dest->arr.objArray[i] = OCRepPayloadClone(source->arr.objArray[i]); } break; case OCREP_PROP_ARRAY: dest->arr.objArray = (OCRepPayload**)OICMalloc(dimTotal * sizeof(OCRepPayload*)); for(size_t i = 0; i < dimTotal; ++i) { dest->arr.objArray[i] = OCRepPayloadClone(source->arr.objArray[i]); } break; default: OIC_LOG(ERROR, TAG, "CopyPropertyValueArray invalid type"); break; } }
void CARAXmppMessageReceivedCB(void * const param, xmpp_error_code_t result, const void *const sender, const void *const msg, size_t messageOctets) { if (g_networkPacketCallback) { VERIFY_NON_NULL_VOID(sender, RA_ADAPTER_TAG, "sender is NULL"); VERIFY_NON_NULL_VOID(msg, RA_ADAPTER_TAG, "message is NULL"); OIC_LOG_V (ERROR, RA_ADAPTER_TAG, "Message received from %s", sender); OIC_LOG_V (ERROR, RA_ADAPTER_TAG, "Message reception result %d", result); CAEndpoint_t *endPoint = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_REMOTE_ACCESS, sender, 0); if (!endPoint) { OIC_LOG(ERROR, RA_ADAPTER_TAG, "EndPoint creation failed!"); return; } void *buf = OICMalloc(messageOctets); if (!buf) { OIC_LOG(ERROR, RA_ADAPTER_TAG, "Memory alloc of message failed!"); CAFreeEndpoint(endPoint); return; } memcpy(buf, msg, messageOctets); CANetworkPacketReceivedCallback networkPacketCallback = g_networkPacketCallback; if (networkPacketCallback) { g_networkPacketCallback(endPoint, buf, messageOctets); } CAFreeEndpoint (endPoint); } else { OIC_LOG_V (ERROR, RA_ADAPTER_TAG, "No callback for RA received message found"); } }
NSConsumerThread * NSThreadInit(NSThreadFunc func, void * data) { NS_VERIFY_NOT_NULL(func, NULL); pthread_mutex_init(&g_create_mutex, NULL); NSConsumerThread * handle = (NSConsumerThread *)OICMalloc(sizeof(NSConsumerThread)); NS_VERIFY_NOT_NULL(handle, NULL); memset(handle, 0, sizeof(NSConsumerThread)); pthread_mutexattr_init(&(handle->mutex_attr)); int pthreadResult = pthread_mutexattr_settype(&(handle->mutex_attr), PTHREAD_MUTEX_RECURSIVE); NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(pthreadResult == 0 ? (void *)1 : NULL, NULL, NSDestroyThreadHandle(handle)); pthreadResult = pthread_mutex_init(&(handle->mutex), &(handle->mutex_attr)); NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(pthreadResult == 0 ? (void *)1 : NULL, NULL, NSDestroyThreadHandle(handle)); pthread_mutex_lock(&g_create_mutex); handle->isStarted = true; pthread_attr_t attrDetached = {}; pthread_attr_init(& attrDetached); pthread_attr_setdetachstate(& attrDetached, PTHREAD_CREATE_DETACHED); pthreadResult = pthread_create(&(handle->thread_id), & attrDetached, func, (data == NULL) ? (void *) handle : (void *)data); NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(pthreadResult == 0 ? (void *)1 : NULL, NULL, NSDestroyThreadHandle(handle)); pthread_attr_destroy(& attrDetached); pthread_mutex_unlock(&g_create_mutex); return handle; }
OCStackResult ZigbeeInit(const char * comPort, PIPlugin_Zigbee ** plugin, PINewResourceFound newResourceCB) { if(!plugin) { return OC_STACK_INVALID_PARAM; } *plugin = (PIPlugin_Zigbee *) OICMalloc(sizeof(PIPlugin_Zigbee) + sizeof(PIPluginBase)); if(!*plugin) { return OC_STACK_NO_MEMORY; } ((*plugin)->header).type = PLUGIN_ZIGBEE; ((*plugin)->header).comPort = OICStrdup(comPort); ((*plugin)->header).NewResourceFoundCB = newResourceCB; ((*plugin)->header).next = NULL; ((*plugin)->header).resourceList = NULL; ((*plugin)->header).processEHRequest = ProcessEHRequest; gPlugin = plugin; return TWInitialize(comPort); }
CAResult_t u_linklist_add(u_linklist_t *linklist, void *data) { VERIFY_NON_NULL(linklist, TAG, "list is null"); VERIFY_NON_NULL(data, TAG, "data is null"); u_linklist_data_t *add_node = NULL; u_linklist_data_t *node = linklist->list; add_node = (u_linklist_data_t *) OICMalloc(sizeof(u_linklist_data_t)); if (NULL == add_node) { OIC_LOG(DEBUG, TAG, "LinklistAdd FAIL, memory allocation failed"); return CA_MEMORY_ALLOC_FAILED; } add_node->data = data; add_node->next = NULL; if (NULL == node) { linklist->list = add_node; linklist->size += 1; } else { //else loop through the list and find the last node, insert next to it while (true) { if(node->next == NULL) { node->next = add_node; linklist->size += 1; break; } node = node->next; }; } return CA_STATUS_OK; }
void *OICRealloc(void* ptr, size_t size) { // Override realloc() behavior for NULL pointer which normally would // work as per malloc(), however we suppress the behavior of possibly // returning a non-null unique pointer. if (ptr == NULL) { return OICMalloc(size); } // Otherwise leave the behavior up to realloc() itself: #ifdef ENABLE_MALLOC_DEBUG void* newptr = realloc(ptr, size); OIC_LOG_V(INFO, TAG, "realloc: ptr=%p, newptr=%p, size=%u", ptr, newptr, size); // Very important to return the correct pointer here, as it only *somtimes* // differs and thus can be hard to notice/test: return newptr; #else return realloc(ptr, size); #endif }
static void CAWiFiPacketReceiveCallback(const char* address, const char* data) { OIC_LOG_V(DEBUG, TAG, "CAWiFiPacketReceiveCallback, from: %s, data: %s", address, data); // call the callback if (gWifiReceivedCallback != NULL) { CARemoteEndpoint_t* endpoint = NULL; endpoint = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t)); // set address memset((void*) endpoint->addressInfo.IP.ipAddress, 0, CA_IPADDR_SIZE); if (CA_IPADDR_SIZE > strlen(address)) strcpy((char*) endpoint->addressInfo.IP.ipAddress, address); // set connectivity type endpoint->connectivityType = CA_WIFI; gWifiReceivedCallback(endpoint, data, strlen(data)); } }
/** * Make the peer address corresponding to the given GATT * characteristic. * * @param[in] c Information about GATT characteristic for which the * peer (client) @c CAEndpoint_t object is being * created. * * @return @c String containing an encoded address associated with the * peer connected to the peripheral on which the characteristic * implementation resides, or @c NULL on error. */ static char * CAGattCharacteristicMakePeerAddress( CAGattCharacteristic * c) { assert(c != NULL); /* Length of stringified pointer in hexadecimal format, plus one for null terminator. */ static size_t const PSEUDO_ADDR_LEN = sizeof(intptr_t) / 4 + 1; assert(MAX_ADDR_STR_SIZE_CA > PSEUDO_ADDR_LEN); /* Since there is no direct way to obtain the client endpoint associated with the GATT characterstics on the server side, embed a stringified pointer to the response charactertistic of the form "&ABCDEF01" is the CAEndpoint_t instead. This works since: 1) only one LE central is ever connected to an LE peripheral 2) the CA layer doesn't directly interpret the address */ char * const addr = OICMalloc(PSEUDO_ADDR_LEN); int const count = snprintf(addr, PSEUDO_ADDR_LEN, "&%" PRIxPTR, (uintptr_t) c); if (count >= (int) PSEUDO_ADDR_LEN) { OIC_LOG(ERROR, TAG, "Error creating peer address on server side."); return NULL; } return addr; }
CAResult_t CAEDRStartReceiveThread(bool isSecured) { OIC_LOG(DEBUG, TAG, "CAEDRStartReceiveThread"); oc_mutex_lock(g_mutexReceiveServer); /** * The task to listen for data from unicast is added to the thread pool. * This is a blocking call is made where we try to receive some data.. * We will keep waiting until some data is received. * This task will be terminated when thread pool is freed on stopping the adapters. * Thread context will be freed by thread on exit. */ CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) OICMalloc( sizeof(CAAdapterReceiveThreadContext_t)); if (!ctx) { OIC_LOG(ERROR, TAG, "Out of memory!"); oc_mutex_unlock(g_mutexReceiveServer); return CA_MEMORY_ALLOC_FAILED; } g_stopUnicast = false; ctx->stopFlag = &g_stopUnicast; ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER; if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAReceiveHandler, (void *) ctx, NULL)) { OIC_LOG(ERROR, TAG, "Failed to create read thread!"); oc_mutex_unlock(g_mutexReceiveServer); OICFree((void *) ctx); return CA_STATUS_FAILED; } oc_mutex_unlock(g_mutexReceiveServer); OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; }
void NSConsumerHandleMakeSyncInfo(NSSyncInfo * sync) { NS_VERIFY_NOT_NULL_V(sync); NSProvider_internal * provider = NSProviderCacheFind(sync->providerId); NS_VERIFY_NOT_NULL_V (provider); NSProviderConnectionInfo * connections = NSCopyProviderConnections(provider->connection); NS_VERIFY_NOT_NULL_V (connections); NSSyncInfo_internal * syncInfo = (NSSyncInfo_internal *)OICMalloc(sizeof(NSSyncInfo_internal)); NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(syncInfo, NSRemoveConnections(connections)); OICStrcpy(syncInfo->providerId, sizeof(char) * NS_DEVICE_ID_LENGTH, sync->providerId); syncInfo->messageId = sync->messageId; syncInfo->state = sync->state; syncInfo->connection = connections; NSTask * syncTask = NSMakeTask(TASK_SEND_SYNCINFO, (void *) syncInfo); NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(syncTask, NSOICFree(syncInfo)); NSConsumerPushEvent(syncTask); }
OicSecCred_t * JSONToCredBin(const char * jsonStr) { if (NULL == jsonStr) { OIC_LOG(ERROR, TAG,"JSONToCredBin jsonStr in NULL"); return NULL; } OicSecCred_t *headCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t)); OCStackResult ret = OC_STACK_ERROR; cJSON *jsonRoot = NULL; VERIFY_NON_NULL(TAG, headCred, ERROR); jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); cJSON *jsonCredMap = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME); VERIFY_NON_NULL(TAG, jsonCredMap, ERROR); // creds cJSON *jsonCredArray = NULL; jsonCredArray = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_CREDS_NAME); VERIFY_NON_NULL(TAG, jsonCredArray, ERROR); if (cJSON_Array == jsonCredArray->type) { int numCred = cJSON_GetArraySize(jsonCredArray); VERIFY_SUCCESS(TAG, numCred > 0, ERROR); int idx = 0; do { cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx); VERIFY_NON_NULL(TAG, jsonCred, ERROR); OicSecCred_t *cred = NULL; if(idx == 0) { cred = headCred; } else { cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t)); OicSecCred_t *temp = headCred; while (temp->next) { temp = temp->next; } temp->next = cred; } VERIFY_NON_NULL(TAG, cred, ERROR); size_t jsonObjLen = 0; cJSON *jsonObj = NULL; //CredId -- Mandatory jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); cred->credId = jsonObj->valueint; } //subject -- Mandatory jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECTID_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); ret = ConvertStrToUuid(jsonObj->valuestring, &cred->subject); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); //CredType -- Mandatory jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); cred->credType = (OicSecCredType_t)jsonObj->valueint; //PrivateData is mandatory for some of the credential types listed below. jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME); if (NULL != jsonObj) { cJSON *jsonPriv = cJSON_GetObjectItem(jsonObj, OIC_JSON_DATA_NAME); VERIFY_NON_NULL(TAG, jsonPriv, ERROR); jsonObjLen = strlen(jsonPriv->valuestring); cred->privateData.data = (uint8_t *)OICCalloc(1, jsonObjLen); VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR); memcpy(cred->privateData.data, jsonPriv->valuestring, jsonObjLen); cred->privateData.len = jsonObjLen; cJSON *jsonEncoding = cJSON_GetObjectItem(jsonObj, OIC_JSON_ENCODING_NAME); VERIFY_NON_NULL(TAG, jsonEncoding, ERROR); if(strcmp(OIC_SEC_ENCODING_RAW, jsonEncoding->valuestring) == 0) { cred->privateData.encoding = OIC_ENCODING_RAW; } else if(strcmp(OIC_SEC_ENCODING_BASE64, jsonEncoding->valuestring) == 0) { cred->privateData.encoding = OIC_ENCODING_BASE64; } else { printf("Unknow encoding type dectected!\n"); printf("json2cbor will use \"oic.sec.encoding.raw\" as default encoding type.\n"); cred->privateData.encoding = OIC_ENCODING_RAW; } } #ifdef __WITH_X509__ //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type. jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME); if (NULL != jsonObj) { cJSON *jsonPub = cJSON_GetObjectItem(jsonObj, OIC_JSON_DATA_NAME); VERIFY_NON_NULL(TAG, jsonPub, ERROR); jsonObjLen = strlen(jsonPub->valuestring); cred->publicData.data = (uint8_t *)OICCalloc(1, jsonObjLen); VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR); memcpy(cred->publicData.data, jsonPub->valuestring, jsonObjLen); cred->publicData.len = jsonObjLen; } #endif // __WITH_X509__ //Period -- Not Mandatory jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME); if(jsonObj && cJSON_String == jsonObj->type) { jsonObjLen = strlen(jsonObj->valuestring) + 1; cred->period = (char *)OICMalloc(jsonObjLen); VERIFY_NON_NULL(TAG, cred->period, ERROR); strncpy(cred->period, jsonObj->valuestring, jsonObjLen); } cred->next = NULL; } while( ++idx < numCred); } // rownerid cJSON *jsonCredObj = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_ROWNERID_NAME); VERIFY_NON_NULL(TAG, jsonCredObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonCredObj->type, ERROR); ret = ConvertStrToUuid(jsonCredObj->valuestring, &headCred->rownerID); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); ret = OC_STACK_OK; exit: if (OC_STACK_OK != ret) { DeleteCredList(headCred); headCred = NULL; } return headCred; }
OicSecAcl_t* JSONToAclBin(const char * jsonStr) { OCStackResult ret = OC_STACK_ERROR; OicSecAcl_t * headAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t)); cJSON *jsonRoot = NULL; VERIFY_NON_NULL(TAG, jsonStr, ERROR); jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); cJSON *jsonAclMap = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME); VERIFY_NON_NULL(TAG, jsonAclMap, ERROR); cJSON *jsonAclObj = NULL; // aclist jsonAclObj = cJSON_GetObjectItem(jsonAclMap, OIC_JSON_ACLIST_NAME); VERIFY_NON_NULL(TAG, jsonAclObj, ERROR); // aclist-aces cJSON *jsonAclArray = NULL; jsonAclArray = cJSON_GetObjectItem(jsonAclObj, OIC_JSON_ACES_NAME); VERIFY_NON_NULL(TAG, jsonAclArray, ERROR); if (cJSON_Array == jsonAclArray->type) { int numAcl = cJSON_GetArraySize(jsonAclArray); int idx = 0; VERIFY_SUCCESS(TAG, numAcl > 0, INFO); do { cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx); VERIFY_NON_NULL(TAG, jsonAcl, ERROR); OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t)); VERIFY_NON_NULL(TAG, ace, ERROR); LL_APPEND(headAcl->aces, ace); size_t jsonObjLen = 0; cJSON *jsonObj = NULL; jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECTID_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); if(strcmp(jsonObj->valuestring, WILDCARD_RESOURCE_URI) == 0) { ace->subjectuuid.id[0] = '*'; } else { ret = ConvertStrToUuid(jsonObj->valuestring, &ace->subjectuuid); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); } // Resources -- Mandatory jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR); size_t resourcesLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, resourcesLen > 0, ERROR); for(size_t idxx = 0; idxx < resourcesLen; idxx++) { OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t)); VERIFY_NON_NULL(TAG, rsrc, ERROR); cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx); VERIFY_NON_NULL(TAG, jsonRsrc, ERROR); //href size_t jsonRsrcObjLen = 0; cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME); VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR); jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1; rsrc->href = (char*)OICMalloc(jsonRsrcObjLen); VERIFY_NON_NULL(TAG, (rsrc->href), ERROR); OICStrcpy(rsrc->href, jsonRsrcObjLen, jsonRsrcObj->valuestring); //rel jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_REL_NAME); if(jsonRsrcObj) { jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1; rsrc->rel = (char*)OICMalloc(jsonRsrcObjLen); VERIFY_NON_NULL(TAG, (rsrc->rel), ERROR); OICStrcpy(rsrc->rel, jsonRsrcObjLen, jsonRsrcObj->valuestring); } //rt jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_RT_NAME); if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type) { rsrc->typeLen = (size_t)cJSON_GetArraySize(jsonRsrcObj); VERIFY_SUCCESS(TAG, (0 < rsrc->typeLen), ERROR); rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*)); VERIFY_NON_NULL(TAG, (rsrc->types), ERROR); for(size_t i = 0; i < rsrc->typeLen; i++) { cJSON *jsonRsrcType = cJSON_GetArrayItem(jsonRsrcObj, i); rsrc->types[i] = OICStrdup(jsonRsrcType->valuestring); VERIFY_NON_NULL(TAG, (rsrc->types[i]), ERROR); } } //if jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_IF_NAME); if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type) { rsrc->interfaceLen = (size_t)cJSON_GetArraySize(jsonRsrcObj); VERIFY_SUCCESS(TAG, (0 < rsrc->interfaceLen), ERROR); rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*)); VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR); for(size_t i = 0; i < rsrc->interfaceLen; i++) { cJSON *jsonInterface = cJSON_GetArrayItem(jsonRsrcObj, i); rsrc->interfaces[i] = OICStrdup(jsonInterface->valuestring); VERIFY_NON_NULL(TAG, (rsrc->interfaces[i]), ERROR); } } LL_APPEND(ace->resources, rsrc); } // Permissions -- Mandatory jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERMISSION_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); ace->permission = jsonObj->valueint; //Validity -- Not Mandatory cJSON *jsonValidityObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_VALIDITY_NAME); if(jsonValidityObj) { VERIFY_SUCCESS(TAG, cJSON_Array == jsonValidityObj->type, ERROR); size_t validityLen = cJSON_GetArraySize(jsonValidityObj); VERIFY_SUCCESS(TAG, (0 < validityLen), ERROR); cJSON *jsonValidity = NULL; for(size_t i = 0; i < validityLen; i++) { jsonValidity = cJSON_GetArrayItem(jsonValidityObj, i); VERIFY_NON_NULL(TAG, jsonValidity, ERROR); VERIFY_SUCCESS(TAG, (jsonValidity->type == cJSON_Array), ERROR); OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t)); VERIFY_NON_NULL(TAG, validity, ERROR); LL_APPEND(ace->validities, validity); //Period cJSON* jsonPeriod = cJSON_GetArrayItem(jsonValidity, 0); if(jsonPeriod) { VERIFY_SUCCESS(TAG, (cJSON_String == jsonPeriod->type), ERROR); jsonObjLen = strlen(jsonPeriod->valuestring) + 1; validity->period = (char*)OICMalloc(jsonObjLen); VERIFY_NON_NULL(TAG, validity->period, ERROR); OICStrcpy(validity->period, jsonObjLen, jsonPeriod->valuestring); } //Recurrence cJSON* jsonRecurObj = cJSON_GetArrayItem(jsonValidity, 1); if(jsonRecurObj) { VERIFY_SUCCESS(TAG, (cJSON_Array == jsonRecurObj->type), ERROR); validity->recurrenceLen = cJSON_GetArraySize(jsonRecurObj); VERIFY_SUCCESS(TAG, (0 < validity->recurrenceLen), ERROR); validity->recurrences = (char**)OICCalloc(validity->recurrenceLen, sizeof(char*)); VERIFY_NON_NULL(TAG, validity->recurrences, ERROR); cJSON *jsonRecur = NULL; for(size_t i = 0; i < validity->recurrenceLen; i++) { jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i); VERIFY_NON_NULL(TAG, jsonRecur, ERROR); jsonObjLen = strlen(jsonRecur->valuestring) + 1; validity->recurrences[i] = (char*)OICMalloc(jsonObjLen); VERIFY_NON_NULL(TAG, validity->recurrences[i], ERROR); OICStrcpy(validity->recurrences[i], jsonObjLen, jsonRecur->valuestring); } } } } } while( ++idx < numAcl); } // rownerid jsonAclObj = cJSON_GetObjectItem(jsonAclMap, OIC_JSON_ROWNERID_NAME); VERIFY_NON_NULL(TAG, jsonAclObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonAclObj->type, ERROR); ret = ConvertStrToUuid(jsonAclObj->valuestring, &headAcl->rownerID); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { DeleteACLList(headAcl); headAcl = NULL; } return headAcl; }
OicSecDoxm_t* JSONToDoxmBin(const char * jsonStr) { printf("IN JSONToDoxmBin\n"); if (NULL == jsonStr) { return NULL; } OCStackResult ret = OC_STACK_ERROR; OicSecDoxm_t *doxm = NULL; cJSON *jsonDoxm = NULL; cJSON *jsonObj = NULL; size_t jsonObjLen = 0; cJSON *jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME); VERIFY_NON_NULL(TAG, jsonDoxm, ERROR); doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(OicSecDoxm_t)); VERIFY_NON_NULL(TAG, doxm, ERROR); //OxmType -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME); if ((jsonObj) && (cJSON_Array == jsonObj->type)) { doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR); doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *)); VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR); for (size_t i = 0; i < doxm->oxmTypeLen ; i++) { cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR); jsonObjLen = strlen(jsonOxmTy->valuestring) + 1; doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen); VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR); strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen); } } //Oxm -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXMS_NAME); if (jsonObj && cJSON_Array == jsonObj->type) { doxm->oxmLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR); doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t)); VERIFY_NON_NULL(TAG, doxm->oxm, ERROR); for (size_t i = 0; i < doxm->oxmLen ; i++) { cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxm, ERROR); doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint; } } //OxmSel -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME); if (jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint; } //sct -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME); if (jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->sct = (OicSecCredType_t)jsonObj->valueint; } //Owned -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME); if (jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->owned = jsonObj->valueint; } //DPC -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME); if (jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->dpc = jsonObj->valueint; } //DeviceId -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME); if (jsonObj) { VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); if (cJSON_String == jsonObj->type) { //Check for empty string, in case DeviceId field has not been set yet if (jsonObj->valuestring[0]) { ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->deviceID); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); } } } //rowner -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_ROWNERID_NAME); if (true == doxm->owned) { VERIFY_NON_NULL(TAG, jsonObj, ERROR); } if (jsonObj) { ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->rownerID); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); } //Owner -- will be empty when device status is unowned. jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVOWNERID_NAME); if (true == doxm->owned) { VERIFY_NON_NULL(TAG, jsonObj, ERROR); } if (jsonObj) { ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->owner); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); } ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { DeleteDoxmBinData(doxm); doxm = NULL; } printf("OUT JSONToDoxmBin\n"); return doxm; }
CAResult_t CASendMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t length) { OIC_LOG(DEBUG, TAG, "IN"); u_arraylist_t *list = CAGetSelectedNetworkList(); if (!list) { OIC_LOG(DEBUG, TAG, "No selected network"); return CA_SEND_FAILED; } CATransportFlags_t requestedAdapter = endpoint->adapter ? endpoint->adapter : CA_ALL_ADAPTERS; for (uint32_t i = 0; i < u_arraylist_length(list); i++) { void* ptrType = u_arraylist_get(list, i); if(ptrType == NULL) { continue; } CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType; if ((connType & requestedAdapter) == 0) { continue; } int index = CAGetAdapterIndex(connType); if (index == -1) { OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); continue; } uint32_t sentDataLen = 0; if (g_adapterHandler[index].sendDataToAll != NULL) { void *payload = (void *) OICMalloc(length); if (!payload) { OIC_LOG(ERROR, TAG, "Out of memory!"); return CA_MEMORY_ALLOC_FAILED; } memcpy(payload, data, length); sentDataLen = g_adapterHandler[index].sendDataToAll(endpoint, payload, length); OICFree(payload); } if (sentDataLen != length) { OIC_LOG(ERROR, TAG, "sendDataToAll failed! Error will be reported from adapter"); #ifdef SINGLE_THREAD //in case of single thread, no error handler. Report error immediately return CA_SEND_FAILED; #endif } } OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; }
CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep) { if (NULL == rep) { OIC_LOG(ERROR, TAG, "parameter is null"); return NULL; } // allocate the request info structure. CARequestInfo_t *clone = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t)); if (!clone) { OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory"); return NULL; } *clone = *rep; if (rep->info.token) { char *temp = NULL; // allocate token field uint8_t len = rep->info.tokenLength; if (len) { temp = (char *) OICCalloc(len, sizeof(char)); if (!temp) { OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory"); CADestroyRequestInfoInternal(clone); return NULL; } memcpy(temp, rep->info.token, len); } // save the token clone->info.token = temp; clone->info.tokenLength = len; } if (NULL != rep->info.options && 0 < rep->info.numOptions) { // save the options clone->info.options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions); if (NULL == clone->info.options) { OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory"); OICFree(clone->info.token); OICFree(clone); return NULL; } memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t) * rep->info.numOptions); } else { clone->info.options = NULL; clone->info.numOptions = 0; } if (NULL != rep->info.payload) { // allocate payload field uint8_t *temp = OICMalloc(rep->info.payloadSize); if (NULL == temp) { OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory"); CADestroyRequestInfoInternal(clone); return NULL; } memcpy(temp, rep->info.payload, rep->info.payloadSize); // save the payload clone->info.payload = temp; } if (NULL != rep->info.resourceUri) { // allocate payload field char *temp = OICStrdup(rep->info.resourceUri); if (NULL == temp) { OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory"); CADestroyRequestInfoInternal(clone); return NULL; } // save the resourceUri clone->info.resourceUri = temp; } return clone; }
/** * function to provision credentials between two devices and ACLs for the devices who act as a server. * * @param[in] ctx Application context would be returned in result callback. * @param[in] type Type of credentials to be provisioned to the device. * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned. * @param[in] acl ACL for device 1. If this is not required set NULL. * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned. * @param[in] acl ACL for device 2. If this is not required set NULL. * @param[in] resultCallback callback provided by API user, callback will be called when * provisioning request recieves a response from first resource server. * @return OC_STACK_OK in case of success and other value otherwise. */ OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize, const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl, const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl, OCProvisionResultCB resultCallback) { if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm) { OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters"); return OC_STACK_INVALID_PARAM; } if (!resultCallback) { OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback"); return OC_STACK_INVALID_CALLBACK; } if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256)) { OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size"); return OC_STACK_INVALID_PARAM; } if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t))) { OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID"); return OC_STACK_INVALID_PARAM; } OIC_LOG(DEBUG, TAG, "Checking link in DB"); bool linkExists = true; OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists); if(res != OC_STACK_OK) { OIC_LOG(ERROR, TAG, "Internal Error Occured"); return res; } if (linkExists) { OIC_LOG(ERROR, TAG, "Link already exists"); return OC_STACK_INVALID_PARAM; } int noOfResults = 2; // Initial Value if (NULL != pDev1Acl) { ++noOfResults; } if (NULL != pDev2Acl) { ++noOfResults; } Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t)); if (!link) { OIC_LOG(ERROR, TAG, "Failed to memory allocation"); return OC_STACK_NO_MEMORY; } OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults); link->pDev1 = pDev1; link->pDev1Acl = pDev1Acl; link->pDev2 = pDev2; link->pDev2Acl = pDev2Acl; link->ctx = ctx; // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2. link->numOfResults = noOfResults; link->resultCallback = resultCallback; link->currentCountResults = 0; link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults); res = SRPProvisionCredentials(link, type, keySize, pDev1, pDev2, &ProvisionCredsCB); if (res != OC_STACK_OK) { OICFree(link->resArr); OICFree(link); } return res; }
CAInterface_t *CAFindInterfaceChange() { char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 }; struct ifconf ifc = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf }; int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd; if (ioctl(s, SIOCGIFCONF, &ifc) < 0) { OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno)); return NULL; } CAInterface_t *foundNewInterface = NULL; struct ifreq* ifr = ifc.ifc_req; size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]); size_t ifreqsize = ifc.ifc_len; CAIfItem_t *previous = (CAIfItem_t *)OICMalloc(ifreqsize); if (!previous) { OIC_LOG(ERROR, TAG, "OICMalloc failed"); return NULL; } memcpy(previous, caglobals.ip.nm.ifItems, ifreqsize); size_t numprevious = caglobals.ip.nm.numIfItems; if (ifreqsize > caglobals.ip.nm.sizeIfItems) { CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize); if (!items) { OIC_LOG(ERROR, TAG, "OICRealloc failed"); OICFree(previous); return NULL; } caglobals.ip.nm.ifItems = items; caglobals.ip.nm.sizeIfItems = ifreqsize; } caglobals.ip.nm.numIfItems = 0; for (size_t i = 0; i < interfaces; i++) { struct ifreq* item = &ifr[i]; char *name = item->ifr_name; struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr; uint32_t ipv4addr = sa4->sin_addr.s_addr; if (ioctl(s, SIOCGIFFLAGS, item) < 0) { OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno)); continue; } int16_t flags = item->ifr_flags; if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING)) { continue; } if (ioctl(s, SIOCGIFINDEX, item) < 0) { OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno)); continue; } int ifIndex = item->ifr_ifindex; caglobals.ip.nm.ifItems[i].ifIndex = ifIndex; // refill interface list caglobals.ip.nm.numIfItems++; if (foundNewInterface) { continue; // continue updating interface list } // see if this interface didn't previously exist bool found = false; for (size_t j = 0; j < numprevious; j++) { if (ifIndex == previous[j].ifIndex) { found = true; break; } } if (found) { OIC_LOG_V(INFO, TAG, "Interface found: %s", name); continue; } foundNewInterface = CANewInterfaceItem(ifIndex, name, AF_INET, ipv4addr, flags); } OICFree(previous); return foundNewInterface; }
void SendRequest() { char buf[MAX_BUF_LEN] = {0}; char address[MAX_BUF_LEN] = {0}; char resourceUri[MAX_BUF_LEN] = {0}; char port[PORT_LENGTH] = {0}; CATransportAdapter_t selectedNetwork; selectedNetwork = GetConnectivityType(); Serial.println("============"); Serial.println("10.11.12.13:4545/res_uri (for IP)"); Serial.println("10:11:12:13:45:45/res_uri (for BT)"); Serial.println("uri: "); size_t len = 0; GetData(buf, sizeof(buf), &len); if (0 >= len) { Serial.println("i/p err"); return; } if (!ParseData(buf, address, port, resourceUri)) { Serial.println("bad uri"); return; } // create remote endpoint CAEndpoint_t *endpoint = NULL; CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port), &endpoint); if (res != CA_STATUS_OK) { Serial.println("Out of memory"); CADestroyEndpoint(endpoint); return; } memset(buf, 0, sizeof(buf)); Serial.println("\n=============================================\n"); Serial.println("0:CON, 1:NON\n"); Serial.println("select message type : "); GetData(buf, sizeof(buf), &len); CAMessageType_t msgType = CA_MSG_CONFIRM; if (0 >= len) { Serial.println("i/p err,default: 0"); } else if(buf[0] == '1') { msgType = CA_MSG_NONCONFIRM; } // create token CAToken_t token = NULL; uint8_t tokenLength = CA_MAX_TOKEN_LEN; res = CAGenerateToken(&token, tokenLength); if (res != CA_STATUS_OK || (!token)) { Serial.println("token error"); return; } Serial.println(token); CAInfo_t requestData = {CA_MSG_RESET}; requestData.token = token; requestData.tokenLength = tokenLength; requestData.payload = (CAPayload_t)"Json Payload"; requestData.payloadSize = strlen((const char *) requestData.payload); requestData.type = msgType; requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1); strcpy(requestData.resourceUri, resourceUri); CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}}; requestInfo.method = CA_GET; requestInfo.isMulticast = false; requestInfo.info = requestData; requestInfo.isMulticast = false; // send request CASendRequest(endpoint, &requestInfo); if (NULL != token) { CADestroyToken(token); } // destroy remote endpoint if (endpoint != NULL) { CADestroyEndpoint(endpoint); } Serial.println("============"); }
void SendRequestAll() { char buf[MAX_BUF_LEN] = {0}; char address[MAX_BUF_LEN] = {0}; char resourceUri[MAX_BUF_LEN] = {0}; char port[PORT_LENGTH] = {0}; CATransportAdapter_t selectedNetwork; selectedNetwork = GetConnectivityType(); Serial.println("\n=============================================\n"); Serial.println("ex) /a/light\n"); Serial.println("resource uri : "); size_t len = 0; GetData(buf, sizeof(buf), &len); if (0 >= len) { Serial.println("i/p err"); return; } if (!ParseData(buf, address, port, resourceUri)) { Serial.println("bad uri"); return; } // create remote endpoint CAEndpoint_t *endpoint = NULL; CAResult_t res = CACreateEndpoint(CA_IPV4, selectedNetwork, address, atoi(port), &endpoint); if (res != CA_STATUS_OK) { Serial.println("create remote endpoint error"); CADestroyEndpoint(endpoint); return; } // create token CAToken_t token = NULL; uint8_t tokenLength = CA_MAX_TOKEN_LEN; res = CAGenerateToken(&token, tokenLength); if (res != CA_STATUS_OK || (!token)) { Serial.println("token error"); return; } Serial.println(token); CAInfo_t requestData = {CA_MSG_RESET}; requestData.token = token; requestData.tokenLength = tokenLength; requestData.payload = (CAPayload_t)"Temp Json Payload"; requestData.payloadSize = strlen((const char *) requestData.payload); requestData.type = CA_MSG_NONCONFIRM; requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1); strcpy(requestData.resourceUri, resourceUri); CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}}; requestInfo.method = CA_GET; requestInfo.isMulticast = true; requestInfo.info = requestData; // send request CASendRequest(endpoint, &requestInfo); if (NULL != token) { CADestroyToken(token); } // destroy remote endpoint if (endpoint != NULL) { CADestroyEndpoint(endpoint); } Serial.println("=========="); }
OCStackResult AddClientCB (ClientCB** clientCB, OCCallbackData* cbData, CAToken_t token, uint8_t tokenLength, OCDoHandle *handle, OCMethod method, OCDevAddr *devAddr, char * requestUri, char * resourceTypeName, uint32_t ttl) { if(!clientCB || !cbData || !handle || !requestUri || tokenLength > CA_MAX_TOKEN_LEN) { return OC_STACK_INVALID_PARAM; } ClientCB *cbNode = NULL; #ifdef WITH_PRESENCE if(method == OC_REST_PRESENCE) { // Retrieve the presence callback structure for this specific requestUri. cbNode = GetClientCB(NULL, 0, NULL, requestUri); } #endif // WITH_PRESENCE if(!cbNode)// If it does not already exist, create new node. { cbNode = (ClientCB*) OICMalloc(sizeof(ClientCB)); if(!cbNode) { *clientCB = NULL; goto exit; } else { OC_LOG(INFO, TAG, "Adding client callback with token"); OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, tokenLength); cbNode->callBack = cbData->cb; cbNode->context = cbData->context; cbNode->deleteCallback = cbData->cd; //Note: token memory is allocated in the caller OCDoResource //but freed in DeleteClientCB cbNode->token = token; cbNode->tokenLength = tokenLength; cbNode->handle = *handle; cbNode->method = method; cbNode->sequenceNumber = 0; #ifdef WITH_PRESENCE cbNode->presence = NULL; cbNode->filterResourceType = NULL; #endif // WITH_PRESENCE if (method == OC_REST_PRESENCE || method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL) { cbNode->TTL = 0; } else { cbNode->TTL = ttl; } cbNode->requestUri = requestUri; // I own it now cbNode->devAddr = devAddr; // I own it now OC_LOG_V(INFO, TAG, "Added Callback for uri : %s", requestUri); LL_APPEND(cbList, cbNode); *clientCB = cbNode; } } else { // Ensure that the handle the SDK hands back up to the application layer for the // OCDoResource call matches the found ClientCB Node. *clientCB = cbNode; if (cbData->cd) { cbData->cd(cbData->context); } OICFree(token); OICFree(*handle); OICFree(requestUri); OICFree(devAddr); *handle = cbNode->handle; } #ifdef WITH_PRESENCE if(method == OC_REST_PRESENCE && resourceTypeName) { // Amend the found or created node by adding a new resourceType to it. return InsertResourceTypeFilter(cbNode,(char *)resourceTypeName); // I own resourceTypName now. } else { OICFree(resourceTypeName); } #else OICFree(resourceTypeName); #endif return OC_STACK_OK; exit: return OC_STACK_NO_MEMORY; }
CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep) { if (NULL == rep) { OIC_LOG(ERROR, TAG, "Response pointer is NULL"); return NULL; } // check the result value of response info. // Keep this check in sync with CAResponseResult_t switch (rep->result) { case CA_EMPTY: case CA_SUCCESS: case CA_CREATED: case CA_DELETED: case CA_VALID: case CA_CHANGED: case CA_CONTENT: case CA_BAD_REQ: case CA_UNAUTHORIZED_REQ: case CA_BAD_OPT: case CA_FORBIDDEN_REQ: case CA_NOT_FOUND: case CA_INTERNAL_SERVER_ERROR: case CA_RETRANSMIT_TIMEOUT: break; default: OIC_LOG_V(ERROR, TAG, "Response code %u is invalid", rep->result); return NULL; } // allocate the response info structure. CAResponseInfo_t *clone = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t)); if (NULL == clone) { OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory"); return NULL; } *clone = *rep; if (rep->info.token) { char *temp = NULL; // allocate token field uint8_t len = rep->info.tokenLength; if (len) { temp = (char *) OICCalloc(len, sizeof(char)); if (!temp) { OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory"); CADestroyResponseInfoInternal(clone); return NULL; } memcpy(temp, rep->info.token, len); } // save the token clone->info.token = temp; clone->info.tokenLength = len; } if (NULL != rep->info.options && rep->info.numOptions) { // save the options clone->info.options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions); if (NULL == clone->info.options) { OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory"); OICFree(clone->info.token); OICFree(clone); return NULL; } memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t) * rep->info.numOptions); } else { clone->info.options = NULL; clone->info.numOptions = 0; } if (NULL != rep->info.payload) { // allocate payload field uint8_t *temp = (uint8_t *) OICMalloc(rep->info.payloadSize); if (NULL == temp) { OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory"); CADestroyResponseInfoInternal(clone); return NULL; } memcpy(temp, rep->info.payload, rep->info.payloadSize); // save the payload clone->info.payload = temp; } if (NULL != rep->info.resourceUri) { // allocate payload field char *temp = OICStrdup(rep->info.resourceUri); if (NULL == temp) { OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory"); CADestroyResponseInfoInternal(clone); return NULL; } // save the resourceUri clone->info.resourceUri = temp; } return clone; }
OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr) { if (NULL == jsonStr) { return NULL; } OCStackResult ret = OC_STACK_ERROR; OicSecDoxm_t *doxm = NULL; cJSON *jsonDoxm = NULL; cJSON *jsonObj = NULL; size_t jsonObjLen = 0; unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {}; uint32_t outLen = 0; B64Result b64Ret = B64_OK; cJSON *jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME); VERIFY_NON_NULL(TAG, jsonDoxm, ERROR); doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t)); VERIFY_NON_NULL(TAG, doxm, ERROR); //OxmType -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME); if ((jsonObj) && (cJSON_Array == jsonObj->type)) { doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR); doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *)); VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR); for (size_t i = 0; i < doxm->oxmTypeLen ; i++) { cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR); jsonObjLen = strlen(jsonOxmTy->valuestring) + 1; doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen); VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR); strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen); } } //Oxm -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME); if (jsonObj && cJSON_Array == jsonObj->type) { doxm->oxmLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR); doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t)); VERIFY_NON_NULL(TAG, doxm->oxm, ERROR); for (size_t i = 0; i < doxm->oxmLen ; i++) { cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxm, ERROR); doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint; } } //OxmSel -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint; } else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->oxmSel = gDoxm->oxmSel; } //sct -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->sct = (OicSecCredType_t)jsonObj->valueint; } else // PUT/POST JSON may not have sct so set it to the gDoxm->sct { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->sct = gDoxm->sct; } //Owned -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->owned = jsonObj->valueint; } else // PUT/POST JSON may not have owned so set it to the gDomx->owned { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->owned = gDoxm->owned; } //DeviceId -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); if(cJSON_String == jsonObj->type) { //Check for empty string, in case DeviceId field has not been set yet if (jsonObj->valuestring[0]) { outLen = 0; b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)), ERROR); memcpy(doxm->deviceID.id, base64Buff, outLen); } } } else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id { VERIFY_NON_NULL(TAG, gDoxm, ERROR); memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id)); } //DPC -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->dpc = jsonObj->valueint; } else // PUT/POST JSON may not have owned so set it to the gDomx->dpc { if(NULL != gDoxm) { doxm->dpc = gDoxm->dpc; } else { doxm->dpc = false; // default is false } } //Owner -- will be empty when device status is unowned. jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME); if(true == doxm->owned) { VERIFY_NON_NULL(TAG, jsonObj, ERROR); } if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR); outLen = 0; b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR); memcpy(doxm->owner.id, base64Buff, outLen); } ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { DeleteDoxmBinData(doxm); doxm = NULL; } return doxm; }
static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info) { VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false); ca_mutex_lock(g_networkMonitorContextMutex); uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); for (uint32_t list_index = 0; list_index < list_length; list_index++) { CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get( g_networkMonitorContext->netInterfaceList, list_index); if (!netInfo) { continue; } if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0) { if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0) { ca_mutex_unlock(g_networkMonitorContextMutex); return false; } else { OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed"); if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index)) { if (g_networkMonitorContext->networkChangeCb) { g_networkMonitorContext->networkChangeCb(netInfo->ipAddress, CA_INTERFACE_DOWN); } OICFree(netInfo); } else { OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); } break; } } } CANetInfo_t *newNetInfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t)); if (!newNetInfo) { OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed"); ca_mutex_unlock(g_networkMonitorContextMutex); return false; } *newNetInfo = *info; OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found"); CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList, (void *) newNetInfo); if (CA_STATUS_OK != result) { OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); OICFree(newNetInfo); ca_mutex_unlock(g_networkMonitorContextMutex); return false; } ca_mutex_unlock(g_networkMonitorContextMutex); /*Callback will be unset only at the time of termination. By that time, all the threads will be stopped gracefully. This callback is properly protected*/ if (g_networkMonitorContext->networkChangeCb) { g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP); } return true; }
void foundZigbeeCallback(TWDevice *device) { int count = device->endpointOfInterest->clusterList->count; size_t lenSeparator = strlen ("/"); int ret = 0; for(int i=0; i < count; i++) { PIResource_Zigbee *piResource = (PIResource_Zigbee *) OICMalloc(sizeof(*piResource)); if (!piResource) { OC_LOG (ERROR, TAG, "Out of memory"); return; } piResource->header.plugin = (PIPluginBase *)gPlugin; size_t newUriSize = strlen(PI_ZIGBEE_PREFIX) + lenSeparator + sizeof(device->nodeId) + lenSeparator + sizeof(device->endpointOfInterest->endpointId) + lenSeparator + sizeof(device->endpointOfInterest->clusterList->clusterIds[i].clusterId) + 1; // NULL Terminator char * newUri = (char *) OICCalloc(newUriSize, 1); if (!newUri) { OC_LOG (ERROR, TAG, "Out of memory"); return; } ret = snprintf(newUri, newUriSize, "%s/%s/%s/%s", PI_ZIGBEE_PREFIX, device->nodeId, device->endpointOfInterest->endpointId, device->endpointOfInterest->clusterList->clusterIds[i].clusterId); if(ret < 0) { OC_LOG (ERROR, TAG, "Encoding error occurred trying to build Zigbee URI."); } else if(ret > newUriSize) { OC_LOG_V (ERROR, TAG, "Did not allocate enough memory to build URI. Required Size: %d", ret); } piResource->header.piResource.uri = newUri; piResource->header.piResource.resourceTypeName = (char *) ZigBeeClusterIDToOICResourceType( device->endpointOfInterest->clusterList->clusterIds[i].clusterId); if(piResource->header.piResource.resourceTypeName == NULL) { OC_LOG_V (ERROR, TAG, "unsupported clusterId : %d", device->endpointOfInterest->clusterList->clusterIds[i].clusterId); OICFree(piResource->header.piResource.uri); OICFree(piResource); continue; } piResource->header.piResource.resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT; piResource->header.piResource.callbackParam = NULL; piResource->header.piResource.resourceProperties = 0; piResource->eui = OICStrdup(device->eui); piResource->nodeId = OICStrdup(device->nodeId); piResource->endpointId = OICStrdup(device->endpointOfInterest->endpointId); piResource->clusterId = OICStrdup(device->endpointOfInterest->clusterList->clusterIds[i].clusterId); (*gPlugin)->header.NewResourceFoundCB(&(*gPlugin)->header, &piResource->header); } }
static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName) { char *jsonStr = NULL; FILE *fp = NULL; FILE *fp1 = NULL; uint8_t *aclCbor = NULL; uint8_t *pstatCbor = NULL; uint8_t *doxmCbor = NULL; uint8_t *amaclCbor = NULL; uint8_t *svcCbor = NULL; uint8_t *credCbor = NULL; cJSON *jsonRoot = NULL; OCStackResult ret = OC_STACK_ERROR; size_t size = GetJSONFileSize(jsonFileName); if (0 == size) { OIC_LOG (ERROR, TAG, "Failed converting to JSON"); return; } jsonStr = (char *)OICMalloc(size + 1); VERIFY_NON_NULL(TAG, jsonStr, FATAL); fp = fopen(jsonFileName, "r"); if (fp) { size_t bytesRead = fread(jsonStr, 1, size, fp); jsonStr[bytesRead] = '\0'; OIC_LOG_V(DEBUG, TAG, "Read %zu bytes", bytesRead); fclose(fp); fp = NULL; } else { OIC_LOG (ERROR, TAG, "Unable to open JSON file!!"); goto exit; } jsonRoot = cJSON_Parse(jsonStr); cJSON *value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME); //printf("ACL json : \n%s\n", cJSON_PrintUnformatted(value)); size_t aclCborSize = 0; if (NULL != value) { OicSecAcl_t *acl = JSONToAclBin(jsonStr); VERIFY_NON_NULL(TAG, acl, FATAL); ret = AclToCBORPayload(acl, &aclCbor, &aclCborSize); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Acl to Cbor Payload"); DeleteACLList(acl); goto exit; } printf("ACL Cbor Size: %zd\n", aclCborSize); DeleteACLList(acl); } value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME); size_t pstatCborSize = 0; if (NULL != value) { OicSecPstat_t *pstat = JSONToPstatBin(jsonStr); VERIFY_NON_NULL(TAG, pstat, FATAL); ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Pstat to Cbor Payload"); DeletePstatBinData(pstat); goto exit; } printf("PSTAT Cbor Size: %zd\n", pstatCborSize); DeletePstatBinData(pstat); } value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME); size_t doxmCborSize = 0; if (NULL != value) { OicSecDoxm_t *doxm = JSONToDoxmBin(jsonStr); VERIFY_NON_NULL(TAG, doxm, FATAL); ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Doxm to Cbor Payload"); DeleteDoxmBinData(doxm); goto exit; } printf("DOXM Cbor Size: %zd\n", doxmCborSize); DeleteDoxmBinData(doxm); } value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME); size_t amaclCborSize = 0; if (NULL != value) { OicSecAmacl_t *amacl = JSONToAmaclBin(jsonStr); VERIFY_NON_NULL(TAG, amacl, FATAL); ret = AmaclToCBORPayload(amacl, &amaclCbor, &amaclCborSize); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Amacl to Cbor Payload"); DeleteAmaclList(amacl); goto exit; } printf("AMACL Cbor Size: %zd\n", amaclCborSize); DeleteAmaclList(amacl); } value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME); size_t svcCborSize = 0; if (NULL != value) { OicSecSvc_t *svc = JSONToSvcBin(jsonStr); VERIFY_NON_NULL(TAG, svc, FATAL); ret = SVCToCBORPayload(svc, &svcCbor, &svcCborSize); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Svc to Cbor Payload"); DeleteSVCList(svc); goto exit; } printf("SVC Cbor Size: %zd\n", svcCborSize); DeleteSVCList(svc); } value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME); //printf("CRED json : \n%s\n", cJSON_PrintUnformatted(value)); size_t credCborSize = 0; int secureFlag = 0; if (NULL != value) { OicSecCred_t *cred = JSONToCredBin(jsonStr); VERIFY_NON_NULL(TAG, cred, FATAL); ret = CredToCBORPayload(cred, &credCbor, &credCborSize, secureFlag); if(OC_STACK_OK != ret) { OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload"); DeleteCredList(cred); goto exit; } printf("CRED Cbor Size: %zd\n", credCborSize); DeleteCredList(cred); } CborEncoder encoder; size_t cborSize = aclCborSize + pstatCborSize + doxmCborSize + svcCborSize + credCborSize + amaclCborSize; printf("Total Cbor Size : %zd\n", cborSize); cborSize += 255; // buffer margin for adding map and byte string uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize); VERIFY_NON_NULL(TAG, outPayload, ERROR); cbor_encoder_init(&encoder, outPayload, cborSize, 0); CborEncoder map; CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Main Map."); if (aclCborSize > 0) { cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name."); cborEncoderResult = cbor_encode_byte_string(&map, aclCbor, aclCborSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value."); } if (pstatCborSize > 0) { cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name."); cborEncoderResult = cbor_encode_byte_string(&map, pstatCbor, pstatCborSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value."); } if (doxmCborSize > 0) { cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Name."); cborEncoderResult = cbor_encode_byte_string(&map, doxmCbor, doxmCborSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Value."); } if (amaclCborSize > 0) { cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Name."); cborEncoderResult = cbor_encode_byte_string(&map, amaclCbor, amaclCborSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Value."); } if (svcCborSize > 0) { cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name."); cborEncoderResult = cbor_encode_byte_string(&map, svcCbor, svcCborSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value."); } if (credCborSize > 0) { cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name."); cborEncoderResult = cbor_encode_byte_string(&map, credCbor, credCborSize); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value."); } cborEncoderResult = cbor_encoder_close_container(&encoder, &map); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Container."); size_t s = encoder.ptr - outPayload; OIC_LOG_V(DEBUG, TAG, "Payload size %zu", s); fp1 = fopen(cborFileName, "w"); if (fp1) { size_t bytesWritten = fwrite(outPayload, 1, s, fp1); if (bytesWritten == s) { OIC_LOG_V(DEBUG, TAG, "Written %zu bytes", bytesWritten); } else { OIC_LOG_V(ERROR, TAG, "Failed writing %zu bytes", s); } fclose(fp1); fp1 = NULL; } exit: cJSON_Delete(jsonRoot); OICFree(aclCbor); OICFree(doxmCbor); OICFree(pstatCbor); OICFree(amaclCbor); OICFree(svcCbor); OICFree(credCbor); OICFree(jsonStr); return ; }
void SendNotification() { char buf[MAX_BUF_LEN] = {0}; char address[MAX_BUF_LEN] = {0}; char resourceUri[MAX_BUF_LEN] = {0}; char port[PORT_LENGTH] = {0}; CATransportAdapter_t selectedNetwork; selectedNetwork = GetConnectivityType(); Serial.println("============"); Serial.println("10.11.12.13:4545/res_uri (for IP)"); Serial.println("10:11:12:13:45:45/res_uri (for BT)"); Serial.println("uri: "); size_t len = 0; GetData(buf, sizeof(buf), &len); if (0 >= len) { Serial.println("i/p err"); return; } if (!ParseData(buf, address, port, resourceUri)) { Serial.println("bad uri"); return; } // create remote endpoint CAEndpoint_t *endpoint = NULL; CAResult_t res = CACreateEndpoint(CA_DEFAULT_FLAGS, selectedNetwork, address, atoi(port), &endpoint); if (CA_STATUS_OK != res) { Serial.println("Out of memory"); CADestroyEndpoint(endpoint); return; } // create token CAToken_t token = NULL; uint8_t tokenLength = CA_MAX_TOKEN_LEN; res = CAGenerateToken(&token, tokenLength); if (res != CA_STATUS_OK || (!token)) { Serial.println("token error"); return; } CAInfo_t respondData = {CA_MSG_NONCONFIRM}; respondData.token = token; respondData.tokenLength = tokenLength; respondData.payload = (CAPayload_t)"Notification Data"; respondData.payloadSize = strlen((const char *) respondData.payload); respondData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1); strcpy(respondData.resourceUri, resourceUri); CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}}; responseInfo.result = CA_CONTENT; responseInfo.info = respondData; // send request CASendNotification(endpoint, &responseInfo); // destroy remote endpoint if (NULL != endpoint) { CADestroyEndpoint(endpoint); } CADestroyToken(token); Serial.println("============"); }
static OicSecAmacl_t* JSONToAmaclBin(const char * jsonStr) { OCStackResult ret = OC_STACK_ERROR; OicSecAmacl_t * headAmacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t)); cJSON *jsonRoot = NULL; cJSON *jsonAmacl = NULL; VERIFY_NON_NULL(TAG, jsonStr, ERROR); jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); jsonAmacl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME); VERIFY_NON_NULL(TAG, jsonAmacl, INFO); cJSON *jsonObj = NULL; // Resources -- Mandatory jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); // Rlist cJSON *jsonRlistArray = cJSON_GetObjectItem(jsonObj, OIC_JSON_RLIST_NAME); VERIFY_NON_NULL(TAG, jsonRlistArray, ERROR); VERIFY_SUCCESS(TAG, cJSON_Array == jsonRlistArray->type, ERROR); headAmacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonRlistArray); headAmacl->resources = (char**)OICCalloc(headAmacl->resourcesLen, sizeof(char*)); size_t idxx = 0; do { cJSON *jsonRsrc = cJSON_GetArrayItem(jsonRlistArray, idxx); VERIFY_NON_NULL(TAG, jsonRsrc, ERROR); cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME); VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR); size_t jsonRsrcObjLen = 0; jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1; headAmacl->resources[idxx] = (char*)OICMalloc(jsonRsrcObjLen); VERIFY_NON_NULL(TAG, (headAmacl->resources[idxx]), ERROR); OICStrcpy(headAmacl->resources[idxx], jsonRsrcObjLen, jsonRsrcObj->valuestring); } while ( ++idxx < headAmacl->resourcesLen); // Ams -- Mandatory jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_AMS_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR); headAmacl->amssLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, headAmacl->amssLen > 0, ERROR); headAmacl->amss = (OicUuid_t*)OICCalloc(headAmacl->amssLen, sizeof(OicUuid_t)); VERIFY_NON_NULL(TAG, headAmacl->amss, ERROR); idxx = 0; do { cJSON *jsonAms = cJSON_GetArrayItem(jsonObj, idxx); VERIFY_NON_NULL(TAG, jsonAms, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonAms->type, ERROR); memcpy(headAmacl->amss[idxx].id, (OicUuid_t *)jsonAms->valuestring, strlen(jsonAms->valuestring)); } while ( ++idxx < headAmacl->amssLen); // Rowner -- Mandatory jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_ROWNERID_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); ret = ConvertStrToUuid(jsonObj->valuestring, &headAmacl->rownerID); VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR); ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { DeleteAmaclList(headAmacl); headAmacl = NULL; } return headAmacl; }
CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo) { OIC_LOG(DEBUG, TAG, "IN"); if (!pdu || !outCode || !outInfo) { OIC_LOG(ERROR, TAG, "NULL pointer param"); return CA_STATUS_INVALID_PARAM; } coap_opt_iterator_t opt_iter; coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL); if (outCode) { (*outCode) = (uint32_t) CA_RESPONSE_CODE(pdu->hdr->code); } // init HeaderOption list uint32_t count = CAGetOptionCount(opt_iter); memset(outInfo, 0, sizeof(*outInfo)); outInfo->numOptions = count; // set type outInfo->type = pdu->hdr->type; // set message id outInfo->messageId = pdu->hdr->id; outInfo->payloadFormat = CA_FORMAT_UNDEFINED; if (count > 0) { outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t)); if (NULL == outInfo->options) { OIC_LOG(ERROR, TAG, "Out of memory"); return CA_MEMORY_ALLOC_FAILED; } } coap_opt_t *option; char optionResult[CA_MAX_URI_LENGTH] = {0}; uint32_t idx = 0; uint32_t optionLength = 0; bool isfirstsetflag = false; bool isQueryBeingProcessed = false; while ((option = coap_option_next(&opt_iter))) { char buf[COAP_MAX_PDU_SIZE] = {0}; uint32_t bufLength = CAGetOptionData(opt_iter.type, (uint8_t *)(COAP_OPT_VALUE(option)), COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf)); if (bufLength) { OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf); if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type) { if (false == isfirstsetflag) { isfirstsetflag = true; optionResult[optionLength] = '/'; optionLength++; // Make sure there is enough room in the optionResult buffer if ((optionLength + bufLength) < sizeof(optionResult)) { memcpy(&optionResult[optionLength], buf, bufLength); optionLength += bufLength; } else { goto exit; } } else { if (COAP_OPTION_URI_PATH == opt_iter.type) { // Make sure there is enough room in the optionResult buffer if (optionLength < sizeof(optionResult)) { optionResult[optionLength] = '/'; optionLength++; } else { goto exit; } } else if (COAP_OPTION_URI_QUERY == opt_iter.type) { if (false == isQueryBeingProcessed) { // Make sure there is enough room in the optionResult buffer if (optionLength < sizeof(optionResult)) { optionResult[optionLength] = '?'; optionLength++; isQueryBeingProcessed = true; } else { goto exit; } } else { // Make sure there is enough room in the optionResult buffer if (optionLength < sizeof(optionResult)) { optionResult[optionLength] = ';'; optionLength++; } else { goto exit; } } } // Make sure there is enough room in the optionResult buffer if ((optionLength + bufLength) < sizeof(optionResult)) { memcpy(&optionResult[optionLength], buf, bufLength); optionLength += bufLength; } else { goto exit; } } } else if (COAP_OPTION_BLOCK1 == opt_iter.type || COAP_OPTION_BLOCK2 == opt_iter.type || COAP_OPTION_SIZE1 == opt_iter.type || COAP_OPTION_SIZE2 == opt_iter.type) { OIC_LOG_V(DEBUG, TAG, "option[%d] will be filtering", opt_iter.type); } else if (COAP_OPTION_CONTENT_FORMAT == opt_iter.type) { if (1 == COAP_OPT_LENGTH(option) && COAP_MEDIATYPE_APPLICATION_CBOR == buf[0]) { outInfo->payloadFormat = CA_FORMAT_CBOR; } else { outInfo->payloadFormat = CA_FORMAT_UNSUPPORTED; } OIC_LOG_V(DEBUG, TAG, "option[%d] has format [%d]", opt_iter.type, (uint8_t)buf[0]); } else { if (idx < count) { uint32_t length = bufLength; if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH) { outInfo->options[idx].optionID = opt_iter.type; outInfo->options[idx].optionLength = length; outInfo->options[idx].protocolID = CA_COAP_ID; memcpy(outInfo->options[idx].optionData, buf, length); idx++; } } } } } // set token data if (pdu->hdr->token_length > 0) { OIC_LOG_V(DEBUG, TAG, "inside token length : %d", pdu->hdr->token_length); outInfo->token = (char *) OICMalloc(pdu->hdr->token_length); if (NULL == outInfo->token) { OIC_LOG(ERROR, TAG, "Out of memory"); OICFree(outInfo->options); return CA_MEMORY_ALLOC_FAILED; } memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length); } outInfo->tokenLength = pdu->hdr->token_length; // set payload data size_t dataSize; uint8_t *data; if (coap_get_data(pdu, &dataSize, &data)) { OIC_LOG(DEBUG, TAG, "inside pdu->data"); outInfo->payload = (uint8_t *) OICMalloc(dataSize); if (NULL == outInfo->payload) { OIC_LOG(ERROR, TAG, "Out of memory"); OICFree(outInfo->options); OICFree(outInfo->token); return CA_MEMORY_ALLOC_FAILED; } memcpy(outInfo->payload, pdu->data, dataSize); outInfo->payloadSize = dataSize; } if (optionResult[0] != '\0') { OIC_LOG_V(DEBUG, TAG, "URL length:%d", strlen(optionResult)); outInfo->resourceUri = OICStrdup(optionResult); if (!outInfo->resourceUri) { OIC_LOG(ERROR, TAG, "Out of memory"); OICFree(outInfo->options); OICFree(outInfo->token); return CA_MEMORY_ALLOC_FAILED; } } OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; exit: OIC_LOG(ERROR, TAG, "buffer too small"); OICFree(outInfo->options); return CA_STATUS_FAILED; }