X-Git-Url: http://review.tizen.org/git/?a=blobdiff_plain;f=resource%2Fcsdk%2Fstack%2Fsrc%2Focstack.c;h=474da869071f44c2d67868bee109692bc3885ce6;hb=966700a71110e415e8d3049cbe59c624929a9dff;hp=c17b75200db34e25737e24ed2cd2487e58c28bf6;hpb=809b1b1e9be15724a6d756b403328a95894e639f;p=platform%2Fupstream%2Fiotivity.git diff --git a/resource/csdk/stack/src/ocstack.c b/resource/csdk/stack/src/ocstack.c index c17b752..474da86 100644 --- a/resource/csdk/stack/src/ocstack.c +++ b/resource/csdk/stack/src/ocstack.c @@ -40,10 +40,22 @@ #include "ocobserve.h" #include "ocrandom.h" #include "oic_malloc.h" +#include "oic_string.h" +#include "logger.h" #include "ocserverrequest.h" #include "secureresourcemanager.h" +#include "doxmresource.h" #include "cacommon.h" #include "cainterface.h" +#include "ocpayload.h" +#include "ocpayloadcbor.h" + +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) +#include "routingutility.h" +#ifdef ROUTING_GATEWAY +#include "routingmanager.h" +#endif +#endif #ifdef WITH_ARDUINO #include "Time.h" @@ -53,7 +65,6 @@ #include "coap_time.h" #include "utlist.h" #include "pdu.h" -#include "cJSON.h" #ifndef ARDUINO #include @@ -96,17 +107,27 @@ static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100}; #endif static OCMode myStackMode; +#ifdef RA_ADAPTER +//TODO: revisit this design +static bool gRASetInfo = false; +#endif OCDeviceEntityHandler defaultDeviceHandler; +void* defaultDeviceHandlerCallbackParameter = NULL; +#ifdef TCP_ADAPTER +static const char COAP_TCP[] = "coap+tcp:"; +#endif //----------------------------------------------------------------------------- // Macros //----------------------------------------------------------------------------- -#define TAG PCF("OCStack") +#define TAG "OCStack" #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \ {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} } #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \ - TAG, PCF(#arg " is NULL")); return (retVal); } } + TAG, #arg " is NULL"); return (retVal); } } +#define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \ + TAG, #arg " is NULL"); return; } } #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\ goto exit;} } @@ -114,17 +135,6 @@ OCDeviceEntityHandler defaultDeviceHandler; #define MAX_OBSERVE_AGE (0x2FFFFUL) #define MILLISECONDS_PER_SECOND (1000) -/** - * Parse the presence payload and extract various parameters. - * Note: Caller should invoke OICFree after done with resType pointer. - * - * @param payload Presence payload. - * @param seqNum Sequence number. - * @param maxAge Time To Live (in seconds). - * @param resType Resource type. - */ -void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, - OCPresenceTrigger *presenceTrigger, char** resType); //----------------------------------------------------------------------------- // Private internal function prototypes @@ -260,36 +270,6 @@ static void incrementSequenceNumber(OCResource * resPtr); static OCStackResult verifyUriQueryLength(const char * inputUri, uint16_t uriLen); -/** - * Determine if a request/response must be sent in a block transfer because it is too large to be - * sent in a single PDU. This function can be used for either a request or a response. - * Note: Either the request or response parameter should be non-NULL (i.e. only one, not both). - * - * @param request NULL or pointer to request. - * @param response NULL or pointer to response. - * @param size 0 or size of the request/response. If 0, strlen is used for determining - * the length of the request/response. - * - * @return - * false - packet transfer NOT required (i.e. normal request/response). - * true - packet transfer required (i.e. block transfer needed). - */ -static bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size); - -/** - * Retrieves a resource type based upon a query contains only just one - * resource attribute (and that has to be of type "rt"). - * - * @remark This API malloc's memory for the resource type. Do not malloc resourceType - * before passing in. - * - * @param query The query part of the URI. - * @param resourceType The resource type to be populated; pass by reference. - * - * @return ::OC_STACK_OK on success, some other value upon failure. - */ -static OCStackResult getResourceType(const char * query, char** resourceType); - /* * Attempts to initialize every network interface that the CA Layer might have compiled in. * @@ -310,22 +290,6 @@ static CAResult_t OCSelectNetwork(); static uint32_t GetTicks(uint32_t afterMilliSeconds); /** - * This method is used to create the IPv4 dev_addr structure. - * Builds a socket interface address using IP address and port number. - * TODO: Remove in future. Temporary helper function. - * - * @param a IPv4 octet 0. - * @param b IPv4 octet 1. - * @param c IPv4 octet 2. - * @param d IPv4 octet 3. - * @param port Port number. - * @param ipAddr - IPv4 address. - * @return ::OC_STACK_OK on success, some other value upon failure. - */ -static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, - uint16_t port, OCDevAddr *ipAddr); - -/** * Convert CAResponseResult_t to OCStackResult. * * @param caCode CAResponseResult_t code. @@ -337,38 +301,26 @@ static OCStackResult CAToOCStackResult(CAResponseResult_t caCode); * Convert OCStackResult to CAResponseResult_t. * * @param caCode OCStackResult code. - * @return ::CA_SUCCESS on success, some other value upon failure. - */ -static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode); - -/** - * Convert OCConnectivityType to CATransportType_t. - * - * @param ocConType OCConnectivityType input. - * @param caConType CATransportType_t output. - * @return ::OC_STACK_OK on success, some other value upon failure. + * @param method OCMethod method the return code replies to. + * @return ::CA_CONTENT on OK, some other value upon failure. */ -static OCStackResult OCToCATransportType(OCConnectivityType ocConType, - CATransportType_t* caConType); +static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method); /** - * Convert CATransportType_t to OCConnectivityType. + * Convert OCTransportFlags_t to CATransportModifiers_t. * - * @param caConType CATransportType_t input. - * @param ocConType OCConnectivityType output. - * @return ::OC_STACK_OK on success, some other value upon failure. + * @param ocConType OCTransportFlags_t input. + * @return CATransportFlags */ -static OCStackResult CAToOCConnectivityType(CATransportType_t caConType, - OCConnectivityType *ocConType); +static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType); /** - * Update response.addr appropriately from endPoint.addressInfo. + * Convert CATransportFlags_t to OCTransportModifiers_t. * - * @param address OCDevAddr output. - * @param endPoint CARemoteEndpoint_t input. - * @return ::OC_STACK_OK on success, some other value upon failure. + * @param caConType CATransportFlags_t input. + * @return OCTransportFlags */ -static OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint); +static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType); /** * Handle response from presence request. @@ -377,8 +329,8 @@ static OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoi * @param responseInfo CA response info. * @return ::OC_STACK_OK on success, some other value upon failure. */ -static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, - const CAResponseInfo_t* responseInfo); +static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint, + const CAResponseInfo_t *responseInfo); /** * This function will be called back by CA layer when a response is received. @@ -386,7 +338,7 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, * @param endPoint CA remote endpoint. * @param responseInfo CA response info. */ -static void HandleCAResponses(const CARemoteEndpoint_t* endPoint, +static void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo); /** @@ -395,7 +347,7 @@ static void HandleCAResponses(const CARemoteEndpoint_t* endPoint, * @param endPoint CA remote endpoint. * @param requestInfo CA request info. */ -static void HandleCARequests(const CARemoteEndpoint_t* endPoint, +static void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo); /** @@ -431,6 +383,17 @@ static OCResourceType *findResourceType(OCResourceType * resourceTypeList, */ static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds); +/** + * Ensure the accept header option is set appropriatly before sending the requests and routing + * header option is updated with destination. + * + * @param object CA remote endpoint. + * @param requestInfo CA request info. + * + * @return ::OC_STACK_OK on success, some other value upon failure. + */ +static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo); + //----------------------------------------------------------------------------- // Internal functions //----------------------------------------------------------------------------- @@ -451,53 +414,71 @@ uint32_t GetTicks(uint32_t afterMilliSeconds) return UINT32_MAX; } } -/** - * Clones a string IFF its pointer value is not NULL. - * - * Note: The caller to this function is responsible for calling @ref OICFree - * for the destination parameter. - * - * @param dest The destination string for the string value to be cloned. - * - * @param src The source for the string value to be to cloned. - */ -OCStackResult CloneStringIfNonNull(char **dest, const char *src) + +void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out) { - if (src) - { - *dest = (char*) OICMalloc(strlen(src) + 1); - if (!*dest) - { - return OC_STACK_NO_MEMORY; - } - strcpy(*dest, src); - } - else - { - *dest = NULL; - } - return OC_STACK_OK; + VERIFY_NON_NULL_NR(in, FATAL); + VERIFY_NON_NULL_NR(out, FATAL); + + out->adapter = (OCTransportAdapter)in->adapter; + out->flags = CAToOCTransportFlags(in->flags); + OICStrcpy(out->addr, sizeof(out->addr), in->addr); + out->port = in->port; + out->interface = in->interface; +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) + memcpy(out->routeData, in->routeData, sizeof(out->routeData)); +#endif +} + +void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out) +{ + VERIFY_NON_NULL_NR(in, FATAL); + VERIFY_NON_NULL_NR(out, FATAL); + + out->adapter = (CATransportAdapter_t)in->adapter; + out->flags = OCToCATransportFlags(in->flags); + OICStrcpy(out->addr, sizeof(out->addr), in->addr); +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) + memcpy(out->routeData, in->routeData, sizeof(out->routeData)); +#endif + out->port = in->port; + out->interface = in->interface; +} + +void FixUpClientResponse(OCClientResponse *cr) +{ + VERIFY_NON_NULL_NR(cr, FATAL); + + cr->addr = &cr->devAddr; + cr->connType = (OCConnectivityType) + ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS)); } -OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, - uint16_t port, OCDevAddr *ipAddr) +static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo) { - if (!ipAddr ) + VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM); + +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) + OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options), + &(requestInfo->info.numOptions)); + if (OC_STACK_OK != rmResult) { - OC_LOG(FATAL, TAG, PCF("Invalid argument")); - return OC_STACK_INVALID_PARAM; + OC_LOG(ERROR, TAG, "Add destination option failed"); + return rmResult; } +#endif - ipAddr->addr[0] = a; - ipAddr->addr[1] = b; - ipAddr->addr[2] = c; - ipAddr->addr[3] = d; - ipAddr->addr[4] = (uint8_t)port; - ipAddr->addr[5] = (uint8_t)(port >> 8); - + // OC stack prefer CBOR encoded payloads. + requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR; + CAResult_t result = CASendRequest(object, requestInfo); + if(CA_STATUS_OK != result) + { + OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result); + return CAResultToOCResult(result); + } return OC_STACK_OK; } - //----------------------------------------------------------------------------- // Internal API function //----------------------------------------------------------------------------- @@ -508,40 +489,46 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat { OCStackResult result = OC_STACK_ERROR; ResourceObserver * observer = NULL; - OCEntityHandlerRequest ehRequest = {}; + OCEntityHandlerRequest ehRequest = {0}; switch(status) { case OC_OBSERVER_NOT_INTERESTED: - OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore")); + OC_LOG(DEBUG, TAG, "observer not interested in our notifications"); observer = GetObserverUsingToken (token, tokenLength); if(observer) { - result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL, - OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, - NULL, OC_OBSERVE_DEREGISTER, observer->observeId); + result = FormOCEntityHandlerRequest(&ehRequest, + (OCRequestHandle)NULL, + OC_REST_NOMETHOD, + &observer->devAddr, + (OCResourceHandle)NULL, + NULL, PAYLOAD_TYPE_REPRESENTATION, + NULL, 0, 0, NULL, + OC_OBSERVE_DEREGISTER, + observer->observeId); if(result != OC_STACK_OK) { return result; } - observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest); + observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest, + observer->resource->entityHandlerCallbackParam); } - //observer is not observing anymore + result = DeleteObserverUsingToken (token, tokenLength); if(result == OC_STACK_OK) { - OC_LOG(DEBUG, TAG, PCF("Removed observer successfully")); + OC_LOG(DEBUG, TAG, "Removed observer successfully"); } else { result = OC_STACK_OK; - OC_LOG(DEBUG, TAG, PCF("Observer Removal failed")); + OC_LOG(DEBUG, TAG, "Observer Removal failed"); } break; + case OC_OBSERVER_STILL_INTERESTED: - //observer is still interested - OC_LOG(DEBUG, TAG, PCF("observer is interested in our \ - notifications, reset the failedCount")); + OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount"); observer = GetObserverUsingToken (token, tokenLength); if(observer) { @@ -554,32 +541,39 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat result = OC_STACK_OBSERVER_NOT_FOUND; } break; + case OC_OBSERVER_FAILED_COMM: - //observer is not reachable - OC_LOG(DEBUG, TAG, PCF("observer is unreachable")); + OC_LOG(DEBUG, TAG, "observer is unreachable"); observer = GetObserverUsingToken (token, tokenLength); if(observer) { if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM) { - result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL, - OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, - NULL, OC_OBSERVE_DEREGISTER, observer->observeId); + result = FormOCEntityHandlerRequest(&ehRequest, + (OCRequestHandle)NULL, + OC_REST_NOMETHOD, + &observer->devAddr, + (OCResourceHandle)NULL, + NULL, PAYLOAD_TYPE_REPRESENTATION, + NULL, 0, 0, NULL, + OC_OBSERVE_DEREGISTER, + observer->observeId); if(result != OC_STACK_OK) { return OC_STACK_ERROR; } - observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest); - //observer is unreachable + observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest, + observer->resource->entityHandlerCallbackParam); + result = DeleteObserverUsingToken (token, tokenLength); if(result == OC_STACK_OK) { - OC_LOG(DEBUG, TAG, PCF("Removed observer successfully")); + OC_LOG(DEBUG, TAG, "Removed observer successfully"); } else { result = OC_STACK_OK; - OC_LOG(DEBUG, TAG, PCF("Observer Removal failed")); + OC_LOG(DEBUG, TAG, "Observer Removal failed"); } } else @@ -592,7 +586,7 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat } break; default: - OC_LOG(ERROR, TAG, PCF("Unknown status")); + OC_LOG(ERROR, TAG, "Unknown status"); result = OC_STACK_ERROR; break; } @@ -604,18 +598,22 @@ OCStackResult CAToOCStackResult(CAResponseResult_t caCode) switch(caCode) { - case CA_SUCCESS: - ret = OC_STACK_OK; - break; case CA_CREATED: ret = OC_STACK_RESOURCE_CREATED; break; case CA_DELETED: ret = OC_STACK_RESOURCE_DELETED; break; + case CA_CHANGED: + case CA_CONTENT: + ret = OC_STACK_OK; + break; case CA_BAD_REQ: ret = OC_STACK_INVALID_QUERY; break; + case CA_UNAUTHORIZED_REQ: + ret = OC_STACK_UNAUTHORIZED_REQ; + break; case CA_BAD_OPT: ret = OC_STACK_INVALID_OPTION; break; @@ -631,14 +629,32 @@ OCStackResult CAToOCStackResult(CAResponseResult_t caCode) return ret; } -CAResponseResult_t OCToCAStackResult(OCStackResult ocCode) +CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method) { CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR; switch(ocCode) { case OC_STACK_OK: - ret = CA_SUCCESS; + switch (method) + { + case OC_REST_PUT: + case OC_REST_POST: + // This Response Code is like HTTP 204 "No Content" but only used in + // response to POST and PUT requests. + ret = CA_CHANGED; + break; + case OC_REST_GET: + // This Response Code is like HTTP 200 "OK" but only used in response to + // GET requests. + ret = CA_CONTENT; + break; + default: + // This should not happen but, + // give it a value just in case but output an error + ret = CA_CONTENT; + OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [d].", method); + } break; case OC_STACK_RESOURCE_CREATED: ret = CA_CREATED; @@ -658,100 +674,34 @@ CAResponseResult_t OCToCAStackResult(OCStackResult ocCode) case OC_STACK_COMM_ERROR: ret = CA_RETRANSMIT_TIMEOUT; break; + case OC_STACK_UNAUTHORIZED_REQ: + ret = CA_UNAUTHORIZED_REQ; + break; default: break; } return ret; } -OCStackResult OCToCATransportType(OCConnectivityType ocConType, CATransportType_t* caConType) +CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags) { - OCStackResult ret = OC_STACK_OK; + CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags; - switch(ocConType) + // supply default behavior. + if ((caFlags & (CA_IPV6|CA_IPV4)) == 0) { - case OC_IPV4: - *caConType = CA_IPV4; - break; - case OC_IPV6: - *caConType = CA_IPV6; - break; - case OC_EDR: - *caConType = CA_EDR; - break; - case OC_LE: - *caConType = CA_LE; - break; - case OC_ALL: - // Currently OC_ALL represents IPv4 - // Add other connectivity types as they are enabled in future - *caConType = (CATransportType_t) (CA_IPV4); - break; - default: - ret = OC_STACK_INVALID_PARAM; - break; + caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4); } - return ret; -} - -OCStackResult CAToOCConnectivityType(CATransportType_t caConType, OCConnectivityType *ocConType) -{ - OCStackResult ret = OC_STACK_OK; - - switch(caConType) + if ((caFlags & OC_MASK_SCOPE) == 0) { - case CA_IPV4: - *ocConType = OC_IPV4; - break; - case CA_IPV6: - *ocConType = OC_IPV6; - break; - case CA_EDR: - *ocConType = OC_EDR; - break; - case CA_LE: - *ocConType = OC_LE; - break; - default: - ret = OC_STACK_INVALID_PARAM; - break; + caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK); } - return ret; + return caFlags; } -OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* endPoint) +OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags) { - OCStackResult ret = OC_STACK_ERROR; - char * tok = NULL; - char * savePtr = NULL; - char * cpAddress = (char *) OICMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1); - if(!cpAddress) - { - ret = OC_STACK_NO_MEMORY; - goto exit; - } - memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress, - strlen(endPoint->addressInfo.IP.ipAddress) + 1); - - // Grabs the first three numbers from the IPv4 address and replaces dots - for(int i=0; i<4; i++) - { - tok = strtok_r(i==0 ? cpAddress : NULL, ".", &savePtr); - - if(!tok) - { - ret = OC_STACK_ERROR; - goto exit; - } - address->addr[i] = atoi(tok); - } - - memcpy(&address->addr[4], &endPoint->addressInfo.IP.port, sizeof(uint16_t)); - ret = OC_STACK_OK; - -exit: - OICFree(cpAddress); - return ret; + return (OCTransportFlags)caFlags; } static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds) @@ -768,7 +718,7 @@ static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds) cbNode->presence->TTL = maxAgeSeconds; - for(int index = 0; index < PresenceTimeOutSize; index++) + for (int index = 0; index < PresenceTimeOutSize; index++) { // Guard against overflow if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index])) @@ -810,11 +760,11 @@ static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds) const char *convertTriggerEnumToString(OCPresenceTrigger trigger) { - if(trigger == OC_PRESENCE_TRIGGER_CREATE) + if (trigger == OC_PRESENCE_TRIGGER_CREATE) { return OC_RSRVD_TRIGGER_CREATE; } - else if(trigger == OC_PRESENCE_TRIGGER_CHANGE) + else if (trigger == OC_PRESENCE_TRIGGER_CHANGE) { return OC_RSRVD_TRIGGER_CHANGE; } @@ -826,7 +776,11 @@ const char *convertTriggerEnumToString(OCPresenceTrigger trigger) OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr) { - if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0) + if(!triggerStr) + { + return OC_PRESENCE_TRIGGER_CREATE; + } + else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0) { return OC_PRESENCE_TRIGGER_CREATE; } @@ -840,237 +794,149 @@ OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr) } } -void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, - OCPresenceTrigger *presenceTrigger, char** resType) +/** + * The cononical presence allows constructed URIs to be string compared. + * + * requestUri must be a char array of size CA_MAX_URI_LENGTH + */ +static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri, + char *presenceUri) { - if(!payload || !seqNum || !maxAge || !presenceTrigger || !resType) - { - return; - } + VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM); - cJSON *repObj = cJSON_Parse(payload); - cJSON *ocObj = NULL; - cJSON *presenceObj = NULL; - cJSON *seqNumObj = NULL; - cJSON *maxAgeObj = NULL; - cJSON *triggerObj = NULL; - cJSON *resObj = NULL; - size_t size = 0; - if(repObj) + CAEndpoint_t *ep = (CAEndpoint_t *)endpoint; + + if (ep->adapter == CA_ADAPTER_IP) { - ocObj = cJSON_GetObjectItem(repObj, OC_RSRVD_OC); - if(ocObj) + if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4)) { - //Presence payloads should only carry one JSON payload. The first - // & only array item is retrieved. - presenceObj = cJSON_GetArrayItem(ocObj, 0); - if(presenceObj) + if ('\0' == ep->addr[0]) // multicast { - seqNumObj = cJSON_GetObjectItem(presenceObj, OC_RSRVD_NONCE); - if(seqNumObj) - { - *seqNum = seqNumObj->valueint; - } - else - { - OC_LOG(ERROR, TAG, PCF("Nonce (AKA SeqNum) not found in" - " JSON Presence Payload.")); - goto exit; - } - maxAgeObj = cJSON_GetObjectItem(presenceObj, OC_RSRVD_TTL); - if(maxAgeObj) - { - *maxAge = maxAgeObj->valueint; - } - else - { - OC_LOG(ERROR, TAG, PCF("TTL (AKA MaxAge) not found in" - " JSON Presence Payload.")); - goto exit; - } - triggerObj = cJSON_GetObjectItem(presenceObj, - OC_RSRVD_TRIGGER); - if(triggerObj) - { - char * triggerStr = triggerObj->valuestring; - *presenceTrigger = convertTriggerStringToEnum(triggerStr); - } - else - { - OC_LOG(ERROR, TAG, PCF("Trigger Reason not found in" - " JSON Presence Payload.")); - goto exit; - } - resObj = cJSON_GetObjectItem(presenceObj, - OC_RSRVD_RESOURCE_TYPE); - if(resObj) - { - size = strlen(resObj->valuestring) + 1; - *resType = (char *)OICMalloc(size); - if(!*resType) - { - goto exit; - } - strncpy(*resType, resObj->valuestring, size); - } - else - { - OC_LOG(ERROR, TAG, PCF("Resource Type not found in" - " JSON Presence Payload.")); - goto exit; - } + return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI); } else { - OC_LOG(ERROR, TAG, PCF("JSON Presence Object not found in" - " Presence Payload.")); - OICFree(*resType); - goto exit; + return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s", + ep->addr, ep->port, OC_RSRVD_PRESENCE_URI); } } else { - OC_LOG(ERROR, TAG, PCF("JSON Presence Payload does not contain a" - " valid \"oic\" JSON representation.")); - OICFree(*resType); - goto exit; + if ('\0' == ep->addr[0]) // multicast + { + OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP); + ep->port = OC_MULTICAST_PORT; + } + return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s", + ep->addr, ep->port, OC_RSRVD_PRESENCE_URI); } } - else - { - OC_LOG(ERROR, TAG, PCF("JSON Presence Payload does map to a valid JSON" - " representation.")); - OICFree(*resType); - goto exit; - } -exit: - cJSON_Delete(repObj); + // might work for other adapters (untested, but better than nothing) + return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr, + OC_RSRVD_PRESENCE_URI); } -static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, - const CAResponseInfo_t* responseInfo) + +OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint, + const CAResponseInfo_t *responseInfo) { + VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM); + OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION; ClientCB * cbNode = NULL; char *resourceTypeName = NULL; - OCClientResponse response = {}; - OCDevAddr address = {}; + OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}}; OCStackResult result = OC_STACK_ERROR; uint32_t maxAge = 0; - OCPresenceTrigger presenceTrigger = OC_PRESENCE_TRIGGER_CHANGE; - char *fullUri = NULL; - char *ipAddress = NULL; + int uriLen; + char presenceUri[CA_MAX_URI_LENGTH]; + int presenceSubscribe = 0; int multicastPresenceSubscribe = 0; - size_t addressLen = 0; - if (responseInfo->result != CA_SUCCESS) + if (responseInfo->result != CA_CONTENT) { OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result); return OC_STACK_ERROR; } - fullUri = (char *) OICMalloc(MAX_URI_LENGTH); - - if(!fullUri) - { - OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for fullUri")); - result = OC_STACK_NO_MEMORY; - goto exit; - } - - addressLen = strlen(endPoint->addressInfo.IP.ipAddress); - ipAddress = (char *) OICMalloc(addressLen + 1); - - if(!ipAddress) + // check for unicast presence + uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri); + if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri)) { - OC_LOG(ERROR, TAG, PCF("Memory could not be allocated for ipAddress")); - result = OC_STACK_NO_MEMORY; - goto exit; + return OC_STACK_INVALID_URI; } - strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen); - ipAddress[addressLen] = '\0'; - - snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port, - OC_PRESENCE_URI); - - cbNode = GetClientCB(NULL, 0, NULL, fullUri); - - if(cbNode) + cbNode = GetClientCB(NULL, 0, NULL, presenceUri); + if (cbNode) { presenceSubscribe = 1; } else { - snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", OC_MULTICAST_IP, OC_MULTICAST_PORT, - endPoint->resourceUri); - cbNode = GetClientCB(NULL, 0, NULL, fullUri); - if(cbNode) + // check for multiicast presence + CAEndpoint_t ep = { .adapter = endpoint->adapter, + .flags = endpoint->flags }; + + uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri); + + cbNode = GetClientCB(NULL, 0, NULL, presenceUri); + if (cbNode) { multicastPresenceSubscribe = 1; } } - if(!presenceSubscribe && !multicastPresenceSubscribe) + if (!presenceSubscribe && !multicastPresenceSubscribe) { - OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring")); + OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring"); goto exit; } - response.resJSONPayload = responseInfo->info.payload; + response.payload = NULL; response.result = OC_STACK_OK; - result = UpdateResponseAddr(&address, endPoint); - if(result != OC_STACK_OK) - { - goto exit; - } - - response.addr = &address; + CopyEndpointToDevAddr(endpoint, &response.devAddr); + FixUpClientResponse(&response); - result = CAToOCConnectivityType(endPoint->transportType, &(response.connType)); - if(result != OC_STACK_OK) + if (responseInfo->info.payload) { - OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint")); - goto exit; - } + result = OCParsePayload(&response.payload, + PAYLOAD_TYPE_PRESENCE, + responseInfo->info.payload, + responseInfo->info.payloadSize); - if(responseInfo->info.payload) - { - parsePresencePayload(responseInfo->info.payload, - &(response.sequenceNumber), - &maxAge, - &presenceTrigger, - &resourceTypeName); + if(result != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "Presence parse failed"); + goto exit; + } + if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE) + { + OC_LOG(ERROR, TAG, "Presence payload was wrong type"); + result = OC_STACK_ERROR; + goto exit; + } + response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber; + resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType; + maxAge = ((OCPresencePayload*)response.payload)->maxAge; } - if(presenceSubscribe) + if (presenceSubscribe) { if(cbNode->sequenceNumber == response.sequenceNumber) { - if (cbNode->presence) - { - OC_LOG(INFO, TAG, PCF("No presence change. Updating TTL.")); - - result = ResetPresenceTTL(cbNode, maxAge); - - if (result != OC_STACK_OK) - { - OC_LOG_V(ERROR, TAG, "ResetPresenceTTL failed with error: %u", result); - } - } - else - { - OC_LOG(INFO, TAG, PCF("Not subscribed to presence.")); - } - + OC_LOG(INFO, TAG, "No presence change"); goto exit; } + if(maxAge == 0) { - OC_LOG(INFO, TAG, PCF("Stopping presence")); + OC_LOG(INFO, TAG, "Stopping presence"); response.result = OC_STACK_PRESENCE_STOPPED; if(cbNode->presence) { @@ -1083,10 +949,11 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, { if(!cbNode->presence) { - cbNode->presence = (OCPresence *) OICMalloc(sizeof(OCPresence)); + cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence)); + if(!(cbNode->presence)) { - OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence")); + OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence"); result = OC_STACK_NO_MEMORY; goto exit; } @@ -1097,7 +964,7 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, OICMalloc(PresenceTimeOutSize * sizeof(uint32_t)); if(!(cbNode->presence->timeOut)){ OC_LOG(ERROR, TAG, - PCF("Could not allocate memory for cbNode->presence->timeOut")); + "Could not allocate memory for cbNode->presence->timeOut"); OICFree(cbNode->presence); result = OC_STACK_NO_MEMORY; goto exit; @@ -1109,7 +976,7 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, cbNode->sequenceNumber = response.sequenceNumber; // Ensure that a filter is actually applied. - if(resourceTypeName && cbNode->filterResourceType) + if( resourceTypeName && cbNode->filterResourceType) { if(!findResourceType(cbNode->filterResourceType, resourceTypeName)) { @@ -1121,48 +988,44 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, else { // This is the multicast case - OCMulticastNode* mcNode = NULL; - mcNode = GetMCPresenceNode(fullUri); + mcNode = GetMCPresenceNode(presenceUri); if(mcNode != NULL) { if(mcNode->nonce == response.sequenceNumber) { - OC_LOG(INFO, TAG, PCF("No presence change (Multicast)")); + OC_LOG(INFO, TAG, "No presence change (Multicast)"); goto exit; } mcNode->nonce = response.sequenceNumber; if(maxAge == 0) { - OC_LOG(INFO, TAG, PCF("Stopping presence")); + OC_LOG(INFO, TAG, "Stopping presence"); response.result = OC_STACK_PRESENCE_STOPPED; } } else { - uint32_t uriLen = strlen(fullUri); - char* uri = (char *) OICMalloc(uriLen + 1); - if(uri) + char* uri = OICStrdup(presenceUri); + if (!uri) { - memcpy(uri, fullUri, (uriLen + 1)); - } - else - { - OC_LOG(ERROR, TAG, - PCF("No Memory for URI to store in the presence node")); + OC_LOG(INFO, TAG, + "No Memory for URI to store in the presence node"); result = OC_STACK_NO_MEMORY; goto exit; } + result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber); - if(result != OC_STACK_OK) + if(result == OC_STACK_NO_MEMORY) { - OC_LOG(ERROR, TAG, - PCF("Unable to add Multicast Presence Node")); + OC_LOG(INFO, TAG, + "No Memory for Multicast Presence Node"); OICFree(uri); goto exit; } + // presence node now owns uri } // Ensure that a filter is actually applied. @@ -1183,29 +1046,47 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, } exit: -OICFree(fullUri); -OICFree(ipAddress); -OICFree(resourceTypeName); -return result; + OCPayloadDestroy(response.payload); + return result; } -void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo) +void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo) { - OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses")); + VERIFY_NON_NULL_NR(endPoint, FATAL); + VERIFY_NON_NULL_NR(responseInfo, FATAL); - if(NULL == endPoint) - { - OC_LOG(ERROR, TAG, PCF("endPoint is NULL")); - return; - } + OC_LOG(INFO, TAG, "Enter HandleCAResponses"); - if(NULL == responseInfo) +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) +#ifdef ROUTING_GATEWAY + bool needRIHandling = false; + /* + * Routing manager is going to update either of endpoint or response or both. + * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo + * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper + * destination. + */ + OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint, + &needRIHandling); + if(ret != OC_STACK_OK || !needRIHandling) { - OC_LOG(ERROR, TAG, PCF("responseInfo is NULL")); + OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret); return; } +#endif + + /* + * Put source in sender endpoint so that the next packet from application can be routed to + * proper destination and remove "RM" coap header option before passing request / response to + * RI as this option will make no sense to either RI or application. + */ + RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options), + (uint8_t *) &(responseInfo->info.numOptions), + (CAEndpoint_t *) endPoint); +#endif - if(strcmp(endPoint->resourceUri, OC_PRESENCE_URI) == 0) + if(responseInfo->info.resourceUri && + strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0) { HandlePresenceResponse(endPoint, responseInfo); return; @@ -1213,45 +1094,38 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ ClientCB *cbNode = GetClientCB(responseInfo->info.token, responseInfo->info.tokenLength, NULL, NULL); - OC_LOG_V(DEBUG, TAG, "Response has the token %s", responseInfo->info.token); + ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token, responseInfo->info.tokenLength); if(cbNode) { - OC_LOG(INFO, TAG, PCF("There is a cbNode associated with the response token")); + OC_LOG(INFO, TAG, "There is a cbNode associated with the response token"); if(responseInfo->result == CA_EMPTY) { - OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token")); + OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token"); // We do not have a case for the client to receive a RESET if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE) { //This is the case of receiving an ACK on a request to a slow resource! - OC_LOG(INFO, TAG, PCF("This is a pure ACK")); + OC_LOG(INFO, TAG, "This is a pure ACK"); //TODO: should we inform the client // app that at least the request was received at the server? } } else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT) { - OC_LOG(INFO, TAG, PCF("Receiving A Timeout for this token")); - OC_LOG(INFO, TAG, PCF("Calling into application address space")); - OCClientResponse response = {}; - OCDevAddr address = {}; - OCStackResult result = UpdateResponseAddr(&address, endPoint); - if(result != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr")); - return; - } - - result = UpdateResponseAddr(&address, endPoint); - if(result != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint")); - return; - } - response.addr = &address; + OC_LOG(INFO, TAG, "Receiving A Timeout for this token"); + OC_LOG(INFO, TAG, "Calling into application address space"); + + OCClientResponse response = + {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}}; + CopyEndpointToDevAddr(endPoint, &response.devAddr); + FixUpClientResponse(&response); + response.resourceUri = responseInfo->info.resourceUri; + memcpy(response.identity.id, responseInfo->info.identity.id, + sizeof (response.identity.id)); + response.identity.id_length = responseInfo->info.identity.id_length; response.result = CAToOCStackResult(responseInfo->result); cbNode->callBack(cbNode->context, @@ -1260,42 +1134,102 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ } else { - OC_LOG(INFO, TAG, PCF("This is a regular response, A client call back is found")); - OC_LOG(INFO, TAG, PCF("Calling into application address space")); - OCClientResponse response = {}; - OCDevAddr address = {}; - - OCStackResult result = UpdateResponseAddr(&address, endPoint); - if(result != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("Error parsing IP address in UpdateResponseAddr")); - return; - } - response.addr = &address; - // Populate the connectivity type. If this is a discovery response, - // the resource that will be constructed from this response will make - // further API calls from this interface. - result = CAToOCConnectivityType(endPoint->transportType, - &(response.connType)); - if(result != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint")); - return; - } + OC_LOG(INFO, TAG, "This is a regular response, A client call back is found"); + OC_LOG(INFO, TAG, "Calling into application address space"); + + OCClientResponse response = + {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}}; + response.sequenceNumber = OC_OBSERVE_NO_OPTION; + CopyEndpointToDevAddr(endPoint, &response.devAddr); + FixUpClientResponse(&response); + response.resourceUri = responseInfo->info.resourceUri; + memcpy(response.identity.id, responseInfo->info.identity.id, + sizeof (response.identity.id)); + response.identity.id_length = responseInfo->info.identity.id_length; response.result = CAToOCStackResult(responseInfo->result); - response.resJSONPayload = (const char*)responseInfo->info.payload; - response.numRcvdVendorSpecificHeaderOptions = 0; - if(responseInfo->info.numOptions > 0) + + if(responseInfo->info.payload && + responseInfo->info.payloadSize) { - int start = 0; - //First option always with option ID is COAP_OPTION_OBSERVE if it is available. - if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE) + OCPayloadType type = PAYLOAD_TYPE_INVALID; + // check the security resource + if (SRMIsSecurityResourceURI(cbNode->requestUri)) { - memcpy (&(response.sequenceNumber), - &(responseInfo->info.options[0].optionData), sizeof(uint32_t)); - response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1; - start = 1; + type = PAYLOAD_TYPE_SECURITY; + } + else if (cbNode->method == OC_REST_DISCOVER) + { + if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri, + sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0) + { + type = PAYLOAD_TYPE_DISCOVERY; + } + else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0) + { + type = PAYLOAD_TYPE_DEVICE; + } + else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0) + { + type = PAYLOAD_TYPE_PLATFORM; + } + else + { + OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s", + cbNode->method, cbNode->requestUri); + return; + } + } + else if (cbNode->method == OC_REST_GET || + cbNode->method == OC_REST_PUT || + cbNode->method == OC_REST_POST || + cbNode->method == OC_REST_OBSERVE || + cbNode->method == OC_REST_OBSERVE_ALL || + cbNode->method == OC_REST_DELETE) + { + OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s", + cbNode->method, cbNode->requestUri); + type = PAYLOAD_TYPE_REPRESENTATION; + } + else + { + OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s", + cbNode->method, cbNode->requestUri); + return; + } + + if(OC_STACK_OK != OCParsePayload(&response.payload, + type, + responseInfo->info.payload, + responseInfo->info.payloadSize)) + { + OC_LOG(ERROR, TAG, "Error converting payload"); + OCPayloadDestroy(response.payload); + return; + } + } + + response.numRcvdVendorSpecificHeaderOptions = 0; + if(responseInfo->info.numOptions > 0) + { + int start = 0; + //First option always with option ID is COAP_OPTION_OBSERVE if it is available. + if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE) + { + size_t i; + uint32_t observationOption; + uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData; + for (observationOption=0, i=0; + iinfo.options[0].optionLength; + i++) + { + observationOption = + (observationOption << 8) | optionData[i]; + } + response.sequenceNumber = observationOption; + + response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1; + start = 1; } else { @@ -1304,7 +1238,8 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS) { - OC_LOG(ERROR, TAG, PCF("#header options are more than MAX_HEADER_OPTIONS")); + OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS"); + OCPayloadDestroy(response.payload); return; } @@ -1319,7 +1254,7 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER && response.sequenceNumber <= cbNode->sequenceNumber) { - OC_LOG_V(INFO, TAG, PCF("Received stale notification. Number :%d"), + OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d", response.sequenceNumber); } else @@ -1345,34 +1280,36 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ if(responseInfo->info.type == CA_MSG_CONFIRM) { SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY, - CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0); + CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL); } + + OCPayloadDestroy(response.payload); } return; } if(observer) { - OC_LOG(INFO, TAG, PCF("There is an observer associated with the response token")); + OC_LOG(INFO, TAG, "There is an observer associated with the response token"); if(responseInfo->result == CA_EMPTY) { - OC_LOG(INFO, TAG, PCF("Receiving A ACK/RESET for this token")); + OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token"); if(responseInfo->info.type == CA_MSG_RESET) { - OC_LOG(INFO, TAG, PCF("This is a RESET")); + OC_LOG(INFO, TAG, "This is a RESET"); OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength, OC_OBSERVER_NOT_INTERESTED); } else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE) { - OC_LOG(INFO, TAG, PCF("This is a pure ACK")); + OC_LOG(INFO, TAG, "This is a pure ACK"); OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength, OC_OBSERVER_STILL_INTERESTED); } } else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT) { - OC_LOG(INFO, TAG, PCF("Receiving Time Out for an observer")); + OC_LOG(INFO, TAG, "Receiving Time Out for an observer"); OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength, OC_OBSERVER_FAILED_COMM); } @@ -1381,63 +1318,64 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ if(!cbNode && !observer) { - if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER) + if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER + || myStackMode == OC_GATEWAY) { - OC_LOG(INFO, TAG, PCF("This is a client, but no cbNode was found for token")); + OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token"); if(responseInfo->result == CA_EMPTY) { - OC_LOG(INFO, TAG, PCF("Receiving CA_EMPTY in the ocstack")); + OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack"); } else { - OC_LOG(INFO, TAG, PCF("Received a response or notification,\ - but I do not have callback. Sending RESET")); + OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET"); SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY, - CA_MSG_RESET, 0, NULL, NULL, 0); + CA_MSG_RESET, 0, NULL, NULL, 0, NULL); } } - if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER) + if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER + || myStackMode == OC_GATEWAY) { - OC_LOG(INFO, TAG, PCF("This is a server, but no observer was found for token")); + OC_LOG(INFO, TAG, "This is a server, but no observer was found for token"); if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE) { - OC_LOG_V(INFO, TAG, PCF("Received ACK at server for messageId : %d"), + OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d", responseInfo->info.messageId); } if (responseInfo->info.type == CA_MSG_RESET) { - OC_LOG_V(INFO, TAG, PCF("Received RESET at server for messageId : %d"), + OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d", responseInfo->info.messageId); } } + return; } - OC_LOG_V(INFO, TAG, PCF("Received payload: %s\n"), (char*)responseInfo->info.payload); - OC_LOG(INFO, TAG, PCF("Exit HandleCAResponses")); + OC_LOG(INFO, TAG, "Exit HandleCAResponses"); } /* * This function handles error response from CA * code shall be added to handle the errors */ -void HandleCAErrorResponse(const CARemoteEndpoint_t* endPoint, const CAErrorInfo_t* errrorInfo) +void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo) { - OC_LOG(INFO, TAG, PCF("Enter HandleCAErrorResponse")); + OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse"); if(NULL == endPoint) { - OC_LOG(ERROR, TAG, PCF("endPoint is NULL")); + OC_LOG(ERROR, TAG, "endPoint is NULL"); return; } if(NULL == errrorInfo) { - OC_LOG(ERROR, TAG, PCF("errrorInfo is NULL")); + OC_LOG(ERROR, TAG, "errrorInfo is NULL"); return; } - OC_LOG(INFO, TAG, PCF("Exit HandleCAErrorResponse")); + OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse"); } /* @@ -1445,13 +1383,14 @@ void HandleCAErrorResponse(const CARemoteEndpoint_t* endPoint, const CAErrorInfo * from the application entity handler. These responses have no payload and are usually ACKs, * RESETs or some error conditions that were caught by the stack. */ -OCStackResult SendDirectStackResponse(const CARemoteEndpoint_t* endPoint, const uint16_t coapID, +OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID, const CAResponseResult_t responseResult, const CAMessageType_t type, const uint8_t numOptions, const CAHeaderOption_t *options, - CAToken_t token, uint8_t tokenLength) + CAToken_t token, uint8_t tokenLength, const char *resourceUri) { - CAResponseInfo_t respInfo = {}; - respInfo.result = responseResult; + CAResponseInfo_t respInfo = { + .result = responseResult + }; respInfo.info.messageId = coapID; respInfo.info.numOptions = numOptions; respInfo.info.options = (CAHeaderOption_t*)options; @@ -1459,32 +1398,79 @@ OCStackResult SendDirectStackResponse(const CARemoteEndpoint_t* endPoint, const respInfo.info.token = token; respInfo.info.tokenLength = tokenLength; respInfo.info.type = type; + respInfo.info.resourceUri = OICStrdup (resourceUri); + respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED; + +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) + // Add the destination to route option from the endpoint->routeData. + OCStackResult result = RMAddInfo(endPoint->routeData, + &(respInfo.info.options), + &(respInfo.info.numOptions)); + if(OC_STACK_OK != result) + { + OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result); + return result; + } +#endif CAResult_t caResult = CASendResponse(endPoint, &respInfo); - if(caResult != CA_STATUS_OK) + + // resourceUri in the info field is cloned in the CA layer and + // thus ownership is still here. + OICFree (respInfo.info.resourceUri); + + if(CA_STATUS_OK != caResult) { - OC_LOG(ERROR, TAG, PCF("CASendResponse error")); - return OC_STACK_ERROR; + OC_LOG(ERROR, TAG, "CASendResponse error"); + return CAResultToOCResult(caResult); } return OC_STACK_OK; } //This function will be called back by CA layer when a request is received -void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* requestInfo) +void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo) { - OC_LOG(INFO, TAG, PCF("Enter HandleCARequests")); + OC_LOG(INFO, TAG, "Enter HandleCARequests"); if(!endPoint) { - OC_LOG(ERROR, TAG, PCF("endPoint is NULL")); + OC_LOG(ERROR, TAG, "endPoint is NULL"); return; } if(!requestInfo) { - OC_LOG(ERROR, TAG, PCF("requestInfo is NULL")); + OC_LOG(ERROR, TAG, "requestInfo is NULL"); return; } +#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP) +#ifdef ROUTING_GATEWAY + bool needRIHandling = false; + /* + * Routing manager is going to update either of endpoint or request or both. + * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo + * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper + * destination. It can also remove "RM" coap header option before passing request / response to + * RI as this option will make no sense to either RI or application. + */ + OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint, + &needRIHandling); + if(OC_STACK_OK != ret || !needRIHandling) + { + OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret); + return; + } +#endif + + /* + * Put source in sender endpoint so that the next packet from application can be routed to + * proper destination and remove RM header option. + */ + RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options), + (uint8_t *) &(requestInfo->info.numOptions), + (CAEndpoint_t *) endPoint); +#endif + OCStackResult requestResult = OC_STACK_ERROR; if(myStackMode == OC_CLIENT) @@ -1493,116 +1479,116 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* return; } - OCServerProtocolRequest serverRequest = {}; + OCServerProtocolRequest serverRequest = {0}; - OC_LOG_V(INFO, TAG, PCF("Endpoint URI : %s\n"), (char*)endPoint->resourceUri); + OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri); - char * newUri = NULL; + char * uriWithoutQuery = NULL; char * query = NULL; - requestResult = getQueryFromUri(endPoint->resourceUri, &query, &newUri); + requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery); - if (requestResult != OC_STACK_OK) + if (requestResult != OC_STACK_OK || !uriWithoutQuery) { OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult); return; } - OC_LOG_V(INFO, TAG, PCF("URI without query: %s\n"), newUri); - OC_LOG_V(INFO, TAG, PCF("Query : %s\n"), query); + OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery); + OC_LOG_V(INFO, TAG, "Query : %s", query); - if(strlen(newUri) < MAX_URI_LENGTH) + if(strlen(uriWithoutQuery) < MAX_URI_LENGTH) { - //copy URI - memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri)); - OICFree(newUri); + OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery); + OICFree(uriWithoutQuery); } else { - OC_LOG(ERROR, TAG, PCF("URI length exceeds MAX_URI_LENGTH.")); - OICFree(newUri); + OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH."); + OICFree(uriWithoutQuery); OICFree(query); return; } - //copy query + if(query) { if(strlen(query) < MAX_QUERY_LENGTH) { - memcpy (&(serverRequest.query), query, strlen(query)); + OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query); OICFree(query); } else { - OC_LOG(ERROR, TAG, PCF("Query length exceeds MAX_QUERY_LENGTH.")); + OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH."); OICFree(query); return; } } - //copy request payload - if (requestInfo->info.payload) + + if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize)) { - size_t payloadLen = strlen(requestInfo->info.payload); - serverRequest.reqTotalSize = payloadLen + 1; - memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload, - payloadLen); + serverRequest.reqTotalSize = requestInfo->info.payloadSize; + serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize); + memcpy (serverRequest.payload, requestInfo->info.payload, + requestInfo->info.payloadSize); } else { - serverRequest.reqTotalSize = 1; - serverRequest.reqJSONPayload[0] = '\0'; + serverRequest.reqTotalSize = 0; } switch (requestInfo->method) { case CA_GET: - { - serverRequest.method = OC_REST_GET; - break; - } + serverRequest.method = OC_REST_GET; + break; case CA_PUT: - { - serverRequest.method = OC_REST_PUT; - break; - } + serverRequest.method = OC_REST_PUT; + break; case CA_POST: - { - serverRequest.method = OC_REST_POST; - break; - } + serverRequest.method = OC_REST_POST; + break; case CA_DELETE: - { - serverRequest.method = OC_REST_DELETE; - break; - } + serverRequest.method = OC_REST_DELETE; + break; default: - { - OC_LOG(ERROR, TAG, PCF("Received CA method %d not supported")); - SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ, + OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method); + SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ, requestInfo->info.type, requestInfo->info.numOptions, requestInfo->info.options, requestInfo->info.token, - requestInfo->info.tokenLength); - return; - } + requestInfo->info.tokenLength, requestInfo->info.resourceUri); + OICFree(serverRequest.payload); + return; } - OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", - requestInfo->info.tokenLength); OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, requestInfo->info.tokenLength); serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength); serverRequest.tokenLength = requestInfo->info.tokenLength; - // Module Name + if (!serverRequest.requestToken) { - OC_LOG(FATAL, TAG, "Server Request Token is NULL"); + OC_LOG(FATAL, TAG, "Allocation for token failed."); SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR, requestInfo->info.type, requestInfo->info.numOptions, requestInfo->info.options, requestInfo->info.token, - requestInfo->info.tokenLength); + requestInfo->info.tokenLength, requestInfo->info.resourceUri); + OICFree(serverRequest.payload); return; } memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength); + switch (requestInfo->info.acceptFormat) + { + case CA_FORMAT_APPLICATION_CBOR: + serverRequest.acceptFormat = OC_FORMAT_CBOR; + break; + case CA_FORMAT_UNDEFINED: + serverRequest.acceptFormat = OC_FORMAT_UNDEFINED; + break; + default: + serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED; + } + if (requestInfo->info.type == CA_MSG_CONFIRM) { serverRequest.qos = OC_HIGH_QOS; @@ -1611,16 +1597,13 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* { serverRequest.qos = OC_LOW_QOS; } - // CA does not need the following 2 fields + // CA does not need the following field // Are we sure CA does not need them? how is it responding to multicast serverRequest.delayedResNeeded = 0; - serverRequest.secured = endPoint->isSecured; serverRequest.coapID = requestInfo->info.messageId; - // copy the address - serverRequest.addressInfo = endPoint->addressInfo; - serverRequest.connectivityType = endPoint->transportType; + CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr); // copy vendor specific header options uint8_t tempNum = (requestInfo->info.numOptions); @@ -1628,11 +1611,12 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS) { OC_LOG(ERROR, TAG, - PCF("The request info numOptions is greater than MAX_HEADER_OPTIONS")); + "The request info numOptions is greater than MAX_HEADER_OPTIONS"); SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT, requestInfo->info.type, requestInfo->info.numOptions, requestInfo->info.options, requestInfo->info.token, - requestInfo->info.tokenLength); + requestInfo->info.tokenLength, requestInfo->info.resourceUri); + OICFree(serverRequest.payload); OICFree(serverRequest.requestToken); return; } @@ -1649,34 +1633,36 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* if(requestResult == OC_STACK_SLOW_RESOURCE) { SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY, - CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0); + CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL); } else if(requestResult != OC_STACK_OK) { - OC_LOG_V(ERROR, TAG, PCF("HandleStackRequests failed. error: %d"), requestResult); + OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult); - CAResponseResult_t stackResponse = OCToCAStackResult(requestResult); + CAResponseResult_t stackResponse = + OCToCAStackResult(requestResult, serverRequest.method); SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse, requestInfo->info.type, requestInfo->info.numOptions, requestInfo->info.options, requestInfo->info.token, - requestInfo->info.tokenLength); + requestInfo->info.tokenLength, requestInfo->info.resourceUri); } // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest. // The token is copied in there, and is thus still owned by this function. + OICFree(serverRequest.payload); OICFree(serverRequest.requestToken); - OC_LOG(INFO, TAG, PCF("Exit HandleCARequests")); + OC_LOG(INFO, TAG, "Exit HandleCARequests"); } OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest) { - OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)")); + OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)"); OCStackResult result = OC_STACK_ERROR; ResourceHandling resHandling; OCResource *resource; if(!protocolRequest) { - OC_LOG(ERROR, TAG, PCF("protocolRequest is NULL")); + OC_LOG(ERROR, TAG, "protocolRequest is NULL"); return OC_STACK_INVALID_PARAM; } @@ -1684,25 +1670,25 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest) protocolRequest->tokenLength); if(!request) { - OC_LOG(INFO, TAG, PCF("This is a new Server Request")); + OC_LOG(INFO, TAG, "This is a new Server Request"); result = AddServerRequest(&request, protocolRequest->coapID, - protocolRequest->delayedResNeeded, protocolRequest->secured, 0, - protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions, + protocolRequest->delayedResNeeded, 0, protocolRequest->method, + protocolRequest->numRcvdVendorSpecificHeaderOptions, protocolRequest->observationOption, protocolRequest->qos, protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions, - protocolRequest->reqJSONPayload, protocolRequest->requestToken, - protocolRequest->tokenLength, - protocolRequest->resourceUrl,protocolRequest->reqTotalSize, - &protocolRequest->addressInfo, protocolRequest->connectivityType); + protocolRequest->payload, protocolRequest->requestToken, + protocolRequest->tokenLength, protocolRequest->resourceUrl, + protocolRequest->reqTotalSize, protocolRequest->acceptFormat, + &protocolRequest->devAddr); if (OC_STACK_OK != result) { - OC_LOG(ERROR, TAG, PCF("Error adding server request")); + OC_LOG(ERROR, TAG, "Error adding server request"); return result; } if(!request) { - OC_LOG(ERROR, TAG, PCF("Out of Memory")); + OC_LOG(ERROR, TAG, "Out of Memory"); return OC_STACK_NO_MEMORY; } @@ -1713,13 +1699,12 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest) } else { - OC_LOG(INFO, TAG, - PCF("This is either a repeated or blocked Server Request")); + OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request"); } if(request->requestComplete) { - OC_LOG(INFO, TAG, PCF("This Server Request is complete")); + OC_LOG(INFO, TAG, "This Server Request is complete"); result = DetermineResourceHandling (request, &resHandling, &resource); if (result == OC_STACK_OK) { @@ -1728,78 +1713,18 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest) } else { - OC_LOG(INFO, TAG, PCF("This Server Request is incomplete")); + OC_LOG(INFO, TAG, "This Server Request is incomplete"); result = OC_STACK_CONTINUE; } return result; } -bool ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port) -{ - size_t index = 0; - char *itr, *coap; - uint8_t dotCount = 0; - - ipAddr[index] = 0; - *port = 0; - /* search for scheme */ - itr = ipAddrStr; - if (!isdigit((char) *ipAddrStr)) - { - coap = OC_COAP_SCHEME; - while (*coap && tolower(*itr) == *coap) - { - coap++; - itr++; - } - } - ipAddrStr = itr; - - while (*ipAddrStr) - { - if (isdigit(*ipAddrStr)) - { - ipAddr[index] *= 10; - ipAddr[index] += *ipAddrStr - '0'; - } - else if (*ipAddrStr == '.') - { - index++; - dotCount++; - ipAddr[index] = 0; - } - else - { - break; - } - ipAddrStr++; - } - if(*ipAddrStr == ':') - { - ipAddrStr++; - while (*ipAddrStr){ - if (isdigit(*ipAddrStr)) - { - *port *= 10; - *port += *ipAddrStr - '0'; - } - else - { - break; - } - ipAddrStr++; - } - } - - return (3 == dotCount); -} - bool validatePlatformInfo(OCPlatformInfo info) { if (!info.platformID) { - OC_LOG(ERROR, TAG, PCF("No platform ID found.")); + OC_LOG(ERROR, TAG, "No platform ID found."); return false; } @@ -1809,13 +1734,13 @@ bool validatePlatformInfo(OCPlatformInfo info) if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH) { - OC_LOG(ERROR, TAG, PCF("Manufacturer name fails length requirements.")); + OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements."); return false; } } else { - OC_LOG(ERROR, TAG, PCF("No manufacturer name present")); + OC_LOG(ERROR, TAG, "No manufacturer name present"); return false; } @@ -1823,39 +1748,111 @@ bool validatePlatformInfo(OCPlatformInfo info) { if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH) { - OC_LOG(ERROR, TAG, PCF("Manufacturer url fails length requirements.")); + OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements."); return false; } } return true; } + //----------------------------------------------------------------------------- // Public APIs //----------------------------------------------------------------------------- +#ifdef RA_ADAPTER +OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo) +{ + if (!raInfo || + !raInfo->username || + !raInfo->hostname || + !raInfo->xmpp_domain) + { + + return OC_STACK_INVALID_PARAM; + } + OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo)); + gRASetInfo = (result == OC_STACK_OK)? true : false; + + return result; +} +#endif OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode) { + (void) ipAddr; + (void) port; + return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS); +} + +OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags) +{ if(stackState == OC_STACK_INITIALIZED) { - OC_LOG(INFO, TAG, PCF("Subsequent calls to OCInit() without calling \ - OCStop() between them are ignored.")); + OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \ + OCStop() between them are ignored."); return OC_STACK_OK; } - (void) ipAddr; - (void) port; +#ifndef ROUTING_GATEWAY + if (OC_GATEWAY == mode) + { + OC_LOG(ERROR, TAG, "Routing Manager not supported"); + return OC_STACK_INVALID_PARAM; + } +#endif + +#ifdef RA_ADAPTER + if(!gRASetInfo) + { + OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit"); + return OC_STACK_ERROR; + } +#endif + OCStackResult result = OC_STACK_ERROR; - OC_LOG(INFO, TAG, PCF("Entering OCInit")); + OC_LOG(INFO, TAG, "Entering OCInit"); // Validate mode - if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER))) + if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER) + || (mode == OC_GATEWAY))) { - OC_LOG(ERROR, TAG, PCF("Invalid mode")); + OC_LOG(ERROR, TAG, "Invalid mode"); return OC_STACK_ERROR; } myStackMode = mode; + if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY) + { + caglobals.client = true; + } + if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY) + { + caglobals.server = true; + } + + caglobals.serverFlags = (CATransportFlags_t)serverFlags; + if (!(caglobals.serverFlags & CA_IPFAMILY_MASK)) + { + caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6); + } + caglobals.clientFlags = (CATransportFlags_t)clientFlags; + if (!(caglobals.clientFlags & CA_IPFAMILY_MASK)) + { + caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6); + } + +#ifdef TCP_ADAPTER + if (!(caglobals.serverFlags & CA_IPFAMILY_MASK)) + { + caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4); + } + if (!(caglobals.clientFlags & CA_IPFAMILY_MASK)) + { + caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4); + } +#endif + defaultDeviceHandler = NULL; + defaultDeviceHandlerCallbackParameter = NULL; OCSeedRandom(); result = CAResultToOCResult(CAInitialize()); @@ -1869,14 +1866,15 @@ OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode) case OC_CLIENT: CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse); result = CAResultToOCResult(CAStartDiscoveryServer()); - OC_LOG(INFO, TAG, PCF("Client mode: CAStartDiscoveryServer")); + OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer"); break; case OC_SERVER: SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse); result = CAResultToOCResult(CAStartListeningServer()); - OC_LOG(INFO, TAG, PCF("Server mode: CAStartListeningServer")); + OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer"); break; case OC_CLIENT_SERVER: + case OC_GATEWAY: SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse); result = CAResultToOCResult(CAStartListeningServer()); if(result == OC_STACK_OK) @@ -1888,7 +1886,7 @@ OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode) VERIFY_SUCCESS(result, OC_STACK_OK); #ifdef WITH_PRESENCE - PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1; + PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1; #endif // WITH_PRESENCE //Update Stack state to initialized @@ -1907,10 +1905,17 @@ OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode) // TODO after BeachHead delivery: consolidate into single SRMInit() } +#ifdef ROUTING_GATEWAY + if (OC_GATEWAY == myStackMode) + { + result = RMInitialize(); + } +#endif + exit: if(result != OC_STACK_OK) { - OC_LOG(ERROR, TAG, PCF("Stack initialization error")); + OC_LOG(ERROR, TAG, "Stack initialization error"); deleteAllResources(); CATerminate(); stackState = OC_STACK_UNINITIALIZED; @@ -1920,26 +1925,33 @@ exit: OCStackResult OCStop() { - OC_LOG(INFO, TAG, PCF("Entering OCStop")); + OC_LOG(INFO, TAG, "Entering OCStop"); if (stackState == OC_STACK_UNINIT_IN_PROGRESS) { - OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting")); + OC_LOG(DEBUG, TAG, "Stack already stopping, exiting"); return OC_STACK_OK; } else if (stackState != OC_STACK_INITIALIZED) { - OC_LOG(ERROR, TAG, PCF("Stack not initialized")); + OC_LOG(ERROR, TAG, "Stack not initialized"); return OC_STACK_ERROR; } stackState = OC_STACK_UNINIT_IN_PROGRESS; - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE // Ensure that the TTL associated with ANY and ALL presence notifications originating from // here send with the code "OC_STACK_PRESENCE_STOPPED" result. presenceResource.presenceTTL = 0; - #endif // WITH_PRESENCE +#endif // WITH_PRESENCE + +#ifdef ROUTING_GATEWAY + if (OC_GATEWAY == myStackMode) + { + RMTerminate(); + } +#endif // Free memory dynamically allocated for resources deleteAllResources(); @@ -1955,6 +1967,7 @@ OCStackResult OCStop() // TODO after BeachHead delivery: consolidate into single SRMDeInit() SRMDeInitPolicyEngine(); + stackState = OC_STACK_UNINITIALIZED; return OC_STACK_OK; } @@ -1998,259 +2011,491 @@ OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen) return OC_STACK_OK; } -OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri, - const char *referenceUri, const char *request, OCConnectivityType conType, - OCQualityOfService qos, OCCallbackData *cbData, - OCHeaderOption * options, uint8_t numOptions) +/** + * A request uri consists of the following components in order: + * example + * optionally one of + * CoAP over UDP prefix "coap://" + * CoAP over TCP prefix "coap+tcp://" + * optionally one of + * IPv6 address "[1234::5678]" + * IPv4 address "192.168.1.1" + * optional port ":5683" + * resource uri "/oc/core..." + * + * for PRESENCE requests, extract resource type. + */ +static OCStackResult ParseRequestUri(const char *fullUri, + OCTransportAdapter adapter, + OCTransportFlags flags, + OCDevAddr **devAddr, + char **resourceUri, + char **resourceType) { - OCStackResult result = OC_STACK_ERROR; - ClientCB *clientCB = NULL; - char * requestUri = NULL; - char * resourceType = NULL; - char * query = NULL; - char * newUri = (char *)requiredUri; - (void) referenceUri; - CARemoteEndpoint_t* endpoint = NULL; - CAResult_t caResult; - CAToken_t token = NULL; - uint8_t tokenLength = CA_MAX_TOKEN_LEN; - OCDoHandle resHandle = NULL; - CAInfo_t requestData ={}; - CARequestInfo_t requestInfo ={}; - CAGroupEndpoint_t grpEnd = {}; - - OC_LOG(INFO, TAG, PCF("Entering OCDoResource")); + VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK); - // Validate input parameters - VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK); - VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK); + OCStackResult result = OC_STACK_OK; + OCDevAddr *da = NULL; + char *colon = NULL; + char *end; - //TODO ("Need to form the final query by concatenating require and reference URI's"); - VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI); + // provide defaults for all returned values + if (devAddr) + { + *devAddr = NULL; + } + if (resourceUri) + { + *resourceUri = NULL; + } + if (resourceType) + { + *resourceType = NULL; + } - uint16_t uriLen = strlen(requiredUri); + // delimit url prefix, if any + const char *start = fullUri; + char *slash2 = strstr(start, "//"); + if (slash2) + { + start = slash2 + 2; + } + char *slash = strchr(start, '/'); + if (!slash) + { + return OC_STACK_INVALID_URI; + } - // ToDo: We should also check if the requiredUri has a mutlicast address, - // then qos has to be OC_Low_QOS - switch (method) +#ifdef TCP_ADAPTER + // process url scheme + size_t prefixLen = slash2 - fullUri; + bool istcp = false; + if (prefixLen) { - case OC_REST_GET: - case OC_REST_OBSERVE: - case OC_REST_OBSERVE_ALL: - case OC_REST_CANCEL_OBSERVE: - requestInfo.method = CA_GET; - break; + if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen))) + { + istcp = true; + } + } +#endif - case OC_REST_PUT: - requestInfo.method = CA_PUT; - break; + // TODO: this logic should come in with unit tests exercising the various strings + // processs url prefix, if any + size_t urlLen = slash - start; + // port + uint16_t port = 0; + size_t len = 0; + if (urlLen && devAddr) + { // construct OCDevAddr + if (start[0] == '[') + { // ipv6 address + char *close = strchr(++start, ']'); + if (!close || close > slash) + { + return OC_STACK_INVALID_URI; + } + end = close; + if (close[1] == ':') + { + colon = close + 1; + } + adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP); + flags = (OCTransportFlags)(flags | OC_IP_USE_V6); + } + else + { + char *dot = strchr(start, '.'); + if (dot && dot < slash) + { // ipv4 address + colon = strchr(start, ':'); + end = (colon && colon < slash) ? colon : slash; +#ifdef TCP_ADAPTER + if (istcp) + { // coap over tcp + adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP); + } + else +#endif + { + adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP); + flags = (OCTransportFlags)(flags | OC_IP_USE_V4); + } + } + else + { // MAC address + end = slash; + } + } + len = end - start; + if (len >= sizeof(da->addr)) + { + return OC_STACK_INVALID_URI; + } + // collect port, if any + if (colon && colon < slash) + { + for (colon++; colon < slash; colon++) + { + char c = colon[0]; + if (c < '0' || c > '9') + { + return OC_STACK_INVALID_URI; + } + port = 10 * port + c - '0'; + } + } - case OC_REST_POST: - requestInfo.method = CA_POST; - break; + len = end - start; + if (len >= sizeof(da->addr)) + { + return OC_STACK_INVALID_URI; + } - case OC_REST_DELETE: - requestInfo.method = CA_DELETE; - break; + da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1); + if (!da) + { + return OC_STACK_NO_MEMORY; + } + OICStrcpyPartial(da->addr, sizeof(da->addr), start, len); + da->port = port; + da->adapter = adapter; + da->flags = flags; + if (!strncmp(fullUri, "coaps:", 6)) + { + da->flags = (OCTransportFlags)(da->flags|CA_SECURE); + } + *devAddr = da; + } - #ifdef WITH_PRESENCE - case OC_REST_PRESENCE: - // Replacing method type with GET because "presence" - // is a stack layer only implementation. - requestInfo.method = CA_GET; - break; - #endif + // process resource uri, if any + if (slash) + { // request uri and query + size_t ulen = strlen(slash); // resource uri length + size_t tlen = 0; // resource type length + char *type = NULL; - default: - result = OC_STACK_INVALID_METHOD; - goto exit; + static const char strPresence[] = "/oic/ad?rt="; + static const size_t lenPresence = sizeof(strPresence) - 1; + if (!strncmp(slash, strPresence, lenPresence)) + { + type = slash + lenPresence; + tlen = ulen - lenPresence; + } + // resource uri + if (resourceUri) + { + *resourceUri = (char *)OICMalloc(ulen + 1); + if (!*resourceUri) + { + result = OC_STACK_NO_MEMORY; + goto error; + } + strcpy(*resourceUri, slash); + } + // resource type + if (type && resourceType) + { + *resourceType = (char *)OICMalloc(tlen + 1); + if (!*resourceType) + { + result = OC_STACK_NO_MEMORY; + goto error; + } + + OICStrcpy(*resourceType, (tlen+1), type); + } } - if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK) + return OC_STACK_OK; + +error: + // free all returned values + if (devAddr) { - goto exit; + OICFree(*devAddr); + } + if (resourceUri) + { + OICFree(*resourceUri); + } + if (resourceType) + { + OICFree(*resourceType); } + return result; +} + +static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint, + char *resourceUri, char **requestUri) +{ + char uri[CA_MAX_URI_LENGTH]; + + FormCanonicalPresenceUri(endpoint, resourceUri, uri); - if((request) && (strlen(request) > MAX_REQUEST_LENGTH)) + *requestUri = OICStrdup(uri); + if (!*requestUri) { - result = OC_STACK_INVALID_PARAM; - goto exit; + return OC_STACK_NO_MEMORY; } -#ifdef WITH_PRESENCE - if(method == OC_REST_PRESENCE) + return OC_STACK_OK; +} + +/** + * Discover or Perform requests on a specified resource + */ +OCStackResult OCDoResource(OCDoHandle *handle, + OCMethod method, + const char *requestUri, + const OCDevAddr *destination, + OCPayload* payload, + OCConnectivityType connectivityType, + OCQualityOfService qos, + OCCallbackData *cbData, + OCHeaderOption *options, + uint8_t numOptions) +{ + OC_LOG(INFO, TAG, "Entering OCDoResource"); + + // Validate input parameters + VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK); + VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK); + VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI); + + OCStackResult result = OC_STACK_ERROR; + CAResult_t caResult; + CAToken_t token = NULL; + uint8_t tokenLength = CA_MAX_TOKEN_LEN; + ClientCB *clientCB = NULL; + OCDoHandle resHandle = NULL; + CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER}; + OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER }; + uint32_t ttl = 0; + OCTransportAdapter adapter; + OCTransportFlags flags; + // the request contents are put here + CARequestInfo_t requestInfo = {.method = CA_GET}; + // requestUri will be parsed into the following three variables + OCDevAddr *devAddr = NULL; + char *resourceUri = NULL; + char *resourceType = NULL; + + // To track if memory is allocated for additional header options + uint8_t hdrOptionMemAlloc = 0; + + // This validation is broken, but doesn't cause harm + size_t uriLen = strlen(requestUri ); + if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK) { - result = getQueryFromUri(requiredUri, &query, &newUri); + goto exit; + } - if(result != OC_STACK_OK) - { - OC_LOG_V(ERROR, TAG, "Invalid Param from getQueryFromUri: %d, URI is %s", - result, requiredUri); - goto exit; - } + /* + * Support original behavior with address on resourceUri argument. + */ + adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT); + flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS); - if(query) + result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType); + + if (result != OC_STACK_OK) + { + OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri); + goto exit; + } + + switch (method) + { + case OC_REST_GET: + case OC_REST_OBSERVE: + case OC_REST_OBSERVE_ALL: + case OC_REST_CANCEL_OBSERVE: + requestInfo.method = CA_GET; + break; + case OC_REST_PUT: + requestInfo.method = CA_PUT; + break; + case OC_REST_POST: + requestInfo.method = CA_POST; + break; + case OC_REST_DELETE: + requestInfo.method = CA_DELETE; + break; + case OC_REST_DISCOVER: + qos = OC_LOW_QOS; + if (destination || devAddr) { - result = getResourceType((char *) query, &resourceType); - OICFree(query); - if(resourceType) - { - OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType); - } - else - { - OC_LOG(DEBUG, TAG, PCF("Resource type is NULL.")); - } + requestInfo.isMulticast = false; } else { - OC_LOG(DEBUG, TAG, PCF("Query string is NULL.")); - } - if(result != OC_STACK_OK) - { - goto exit; + tmpDevAddr.adapter = adapter; + tmpDevAddr.flags = flags; + destination = &tmpDevAddr; + requestInfo.isMulticast = true; } + // CA_DISCOVER will become GET and isMulticast + requestInfo.method = CA_GET; + break; +#ifdef WITH_PRESENCE + case OC_REST_PRESENCE: + // Replacing method type with GET because "presence" + // is a stack layer only implementation. + requestInfo.method = CA_GET; + break; +#endif + default: + result = OC_STACK_INVALID_METHOD; + goto exit; } -#endif // WITH_PRESENCE - requestUri = (char *) OICMalloc(uriLen + 1); - if(requestUri) + if (!devAddr && !destination) { - memcpy(requestUri, newUri, (uriLen + 1)); + OC_LOG(DEBUG, TAG, "no devAddr and no destination"); + result = OC_STACK_INVALID_PARAM; + goto exit; } - else + + /* If not original behavior, use destination argument */ + if (destination && !devAddr) { - result = OC_STACK_NO_MEMORY; - goto exit; + devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr)); + if (!devAddr) + { + result = OC_STACK_NO_MEMORY; + goto exit; + } + *devAddr = *destination; } resHandle = GenerateInvocationHandle(); - if(!resHandle) + if (!resHandle) { result = OC_STACK_NO_MEMORY; goto exit; } - // create token caResult = CAGenerateToken(&token, tokenLength); if (caResult != CA_STATUS_OK) { - OC_LOG(ERROR, TAG, PCF("CAGenerateToken error")); - CADestroyToken(token); - result = CAResultToOCResult (caResult); + OC_LOG(ERROR, TAG, "CAGenerateToken error"); + result= OC_STACK_ERROR; goto exit; } - requestData.type = qualityOfServiceToMessageType(qos); - - requestData.token = token; - requestData.tokenLength = tokenLength; + // fill in request data + requestInfo.info.type = qualityOfServiceToMessageType(qos); + requestInfo.info.token = token; + requestInfo.info.tokenLength = tokenLength; + requestInfo.info.resourceUri = resourceUri; if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL)) { - result = CreateObserveHeaderOption (&(requestData.options), options, - numOptions, OC_OBSERVE_REGISTER); + result = CreateObserveHeaderOption (&(requestInfo.info.options), + options, numOptions, OC_OBSERVE_REGISTER); if (result != OC_STACK_OK) { - CADestroyToken(token); goto exit; } - requestData.numOptions = numOptions + 1; + hdrOptionMemAlloc = 1; + requestInfo.info.numOptions = numOptions + 1; } else { - requestData.options = (CAHeaderOption_t*)options; - requestData.numOptions = numOptions; + requestInfo.info.options = (CAHeaderOption_t*)options; + requestInfo.info.numOptions = numOptions; } - requestData.payload = (char *)request; - - requestInfo.info = requestData; - - CATransportType_t caConType; - - result = OCToCATransportType((OCConnectivityType) conType, &caConType); - if (result != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type")); - goto exit; - } + CopyDevAddrToEndpoint(devAddr, &endpoint); - // send request - if(conType == OC_ALL) + if(payload) { - grpEnd.transportType = caConType; - - grpEnd.resourceUri = (CAURI_t) OICMalloc(uriLen + 1); - if(!grpEnd.resourceUri) + if((result = + OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize)) + != OC_STACK_OK) { - result = OC_STACK_NO_MEMORY; - CADestroyToken(token); + OC_LOG(ERROR, TAG, "Failed to create CBOR Payload"); goto exit; } - strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1)); - - caResult = CASendRequestToAll(&grpEnd, &requestInfo); + requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR; + } + else + { + requestInfo.info.payload = NULL; + requestInfo.info.payloadSize = 0; + requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED; } - else + + if (result != OC_STACK_OK) { - caResult = CACreateRemoteEndpoint(newUri, caConType, &endpoint); + OC_LOG(ERROR, TAG, "CACreateEndpoint error"); + goto exit; + } - if (caResult != CA_STATUS_OK) + // prepare for response +#ifdef WITH_PRESENCE + if (method == OC_REST_PRESENCE) + { + char *presenceUri = NULL; + result = OCPreparePresence(&endpoint, resourceUri, &presenceUri); + if (OC_STACK_OK != result) { - OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error")); - result = CAResultToOCResult (caResult); - CADestroyToken(token); goto exit; } - caResult = CASendRequest(endpoint, &requestInfo); + // Assign full presence uri as coap://ip:port/oic/ad to add to callback list. + // Presence notification will form a canonical uri to + // look for callbacks into the application. + resourceUri = presenceUri; } +#endif - if (caResult != CA_STATUS_OK) + ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND); + result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle, + method, devAddr, resourceUri, resourceType, ttl); + if (OC_STACK_OK != result) { - OC_LOG(ERROR, TAG, PCF("CASendRequest")); - result = CAResultToOCResult (caResult); - CADestroyToken(token); goto exit; } - result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle, method, - requestUri, resourceType, conType, - GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND)); - if(result != OC_STACK_OK) + devAddr = NULL; // Client CB list entry now owns it + resourceUri = NULL; // Client CB list entry now owns it + resourceType = NULL; // Client CB list entry now owns it + + // send request + result = OCSendRequest(&endpoint, &requestInfo); + if (OC_STACK_OK != result) { - result = OC_STACK_NO_MEMORY; goto exit; } - if(handle) + if (handle) { *handle = resHandle; } exit: - if(newUri != requiredUri) - { - OICFree(newUri); - } if (result != OC_STACK_OK) { - OC_LOG_V(ERROR, TAG, PCF("OCDoResource error no %d"), result); + OC_LOG(ERROR, TAG, "OCDoResource error"); FindAndDeleteClientCB(clientCB); + CADestroyToken(token); + if (handle) + { + *handle = NULL; + } OICFree(resHandle); - OICFree(requestUri); - OICFree(resourceType); } - CADestroyRemoteEndpoint(endpoint); - OICFree(grpEnd.resourceUri); - if (requestData.options && requestData.numOptions > 0) + // This is the owner of the payload object, so we free it + OCPayloadDestroy(payload); + OICFree(requestInfo.info.payload); + OICFree(devAddr); + OICFree(resourceUri); + OICFree(resourceType); + if (hdrOptionMemAlloc) { - if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL)) - { - OICFree(requestData.options); - } + OICFree(requestInfo.info.options); } return result; } @@ -2276,94 +2521,78 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * Remove the callback associated on client side. */ OCStackResult ret = OC_STACK_OK; - CARemoteEndpoint_t* endpoint = NULL; - CAResult_t caResult; - CAInfo_t requestData = {}; - CARequestInfo_t requestInfo = {}; + CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER}; + CAInfo_t requestData = {.type = CA_MSG_CONFIRM}; + CARequestInfo_t requestInfo = {.method = CA_GET}; if(!handle) { return OC_STACK_INVALID_PARAM; } - OC_LOG(INFO, TAG, PCF("Entering OCCancel")); - ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL); + if (!clientCB) + { + OC_LOG(ERROR, TAG, "Client callback not found. Called OCCancel twice?"); + goto Error; + } - if(clientCB) + switch (clientCB->method) { - switch (clientCB->method) - { - case OC_REST_OBSERVE: - case OC_REST_OBSERVE_ALL: - if(qos == OC_HIGH_QOS) - { - requestData.type = qualityOfServiceToMessageType(qos); - requestData.token = clientCB->token; - requestData.tokenLength = clientCB->tokenLength; + case OC_REST_OBSERVE: + case OC_REST_OBSERVE_ALL: + OC_LOG_V(INFO, TAG, "Canceling observation for resource %s", + clientCB->requestUri); + if (qos != OC_HIGH_QOS) + { + FindAndDeleteClientCB(clientCB); + break; + } + else + { + OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE"); + } - if (CreateObserveHeaderOption (&(requestData.options), - options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK) - { - return OC_STACK_ERROR; - } - requestData.numOptions = numOptions + 1; - requestInfo.method = CA_GET; - requestInfo.info = requestData; + requestData.type = qualityOfServiceToMessageType(qos); + requestData.token = clientCB->token; + requestData.tokenLength = clientCB->tokenLength; + if (CreateObserveHeaderOption (&(requestData.options), + options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK) + { + return OC_STACK_ERROR; + } + requestData.numOptions = numOptions + 1; + requestData.resourceUri = OICStrdup (clientCB->requestUri); - CATransportType_t caConType; - ret = OCToCATransportType(clientCB->conType, &caConType); - if(ret != OC_STACK_OK) - { - goto Error; - } + requestInfo.method = CA_GET; + requestInfo.info = requestData; - caResult = CACreateRemoteEndpoint((char *)clientCB->requestUri, - caConType, &endpoint); - if (caResult != CA_STATUS_OK) - { - OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error")); - ret = OC_STACK_ERROR; - goto Error; - } + CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint); - // send request - caResult = CASendRequest(endpoint, &requestInfo); - if (caResult != CA_STATUS_OK) - { - OC_LOG(ERROR, TAG, PCF("CASendRequest error")); - ret = OC_STACK_ERROR; - } - ret = CAResultToOCResult (caResult); - } - else - { - FindAndDeleteClientCB(clientCB); - } - break; + // send request + ret = OCSendRequest(&endpoint, &requestInfo); + break; - #ifdef WITH_PRESENCE - case OC_REST_PRESENCE: - FindAndDeleteClientCB(clientCB); - break; - #endif - default: - ret = OC_STACK_INVALID_METHOD; - break; - } - } - else - { - OC_LOG(ERROR, TAG, PCF("Client callback not found. Called OCCancel twice?")); +#ifdef WITH_PRESENCE + case OC_REST_PRESENCE: + FindAndDeleteClientCB(clientCB); + break; +#endif + + default: + ret = OC_STACK_INVALID_METHOD; + break; } - Error: - CADestroyRemoteEndpoint(endpoint); +Error: if (requestData.numOptions > 0) { OICFree(requestData.options); } - + if (requestData.resourceUri) + { + OICFree (requestData.resourceUri); + } return ret; } @@ -2376,10 +2605,10 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption */ OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler) { - OC_LOG(INFO, TAG, PCF("RegisterPersistentStorageHandler !!")); + OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!"); if(!persistentStorageHandler) { - OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid")); + OC_LOG(ERROR, TAG, "The persistent storage handler is invalid"); return OC_STACK_INVALID_PARAM; } else @@ -2390,7 +2619,7 @@ OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistent !persistentStorageHandler->unlink || !persistentStorageHandler->write) { - OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid")); + OC_LOG(ERROR, TAG, "The persistent storage handler is invalid"); return OC_STACK_INVALID_PARAM; } } @@ -2398,131 +2627,112 @@ OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistent } #ifdef WITH_PRESENCE + OCStackResult OCProcessPresence() { OCStackResult result = OC_STACK_OK; - uint8_t ipAddr[4] = { 0 }; - uint16_t port = 0; - OC_LOG(INFO, TAG, PCF("Entering RequestPresence")); + // the following line floods the log with messages that are irrelevant + // to most purposes. Uncomment as needed. + //OC_LOG(INFO, TAG, "Entering RequestPresence"); ClientCB* cbNode = NULL; - OCDevAddr dst = {}; - OCClientResponse clientResponse ={}; + OCClientResponse clientResponse; OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION; LL_FOREACH(cbList, cbNode) { - if(OC_REST_PRESENCE == cbNode->method) + if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence) { - if(cbNode->presence) - { - uint32_t now = GetTicks(0); - OC_LOG_V(DEBUG, TAG, "this TTL level %d", - cbNode->presence->TTLlevel); - OC_LOG_V(DEBUG, TAG, "current ticks %d", now); - - - if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1)) - { - goto exit; - } - - if(cbNode->presence->TTLlevel < PresenceTimeOutSize) - { - OC_LOG_V(DEBUG, TAG, "timeout ticks %d", - cbNode->presence->timeOut[cbNode->presence->TTLlevel]); - } + continue; + } - if(cbNode->presence->TTLlevel >= PresenceTimeOutSize) - { - OC_LOG(DEBUG, TAG, PCF("No more timeout ticks")); - if (ParseIPv4Address(cbNode->requestUri, ipAddr, &port)) - { - OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port, - &dst); - - clientResponse.sequenceNumber = 0; - clientResponse.result = OC_STACK_PRESENCE_TIMEOUT; - clientResponse.addr = (OCDevAddr *) &dst; - clientResponse.resJSONPayload = NULL; - - // Increment the TTLLevel (going to a next state), so we don't keep - // sending presence notification to client. - cbNode->presence->TTLlevel++; - OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", + uint32_t now = GetTicks(0); + OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel); - } - else - { - result = OC_STACK_INVALID_IP; - goto exit; - } - - cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse); - if (cbResult == OC_STACK_DELETE_TRANSACTION) - { - FindAndDeleteClientCB(cbNode); - } - } + OC_LOG_V(DEBUG, TAG, "current ticks %d", now); - if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel]) - { - CAResult_t caResult = CA_STATUS_OK; - CARemoteEndpoint_t* endpoint = NULL; - CAInfo_t requestData ={}; - CARequestInfo_t requestInfo = {}; + if (cbNode->presence->TTLlevel > PresenceTimeOutSize) + { + goto exit; + } - OC_LOG(DEBUG, TAG, PCF("time to test server presence")); + if (cbNode->presence->TTLlevel < PresenceTimeOutSize) + { + OC_LOG_V(DEBUG, TAG, "timeout ticks %d", + cbNode->presence->timeOut[cbNode->presence->TTLlevel]); + } + if (cbNode->presence->TTLlevel >= PresenceTimeOutSize) + { + OC_LOG(DEBUG, TAG, "No more timeout ticks"); + + clientResponse.sequenceNumber = 0; + clientResponse.result = OC_STACK_PRESENCE_TIMEOUT; + clientResponse.devAddr = *cbNode->devAddr; + FixUpClientResponse(&clientResponse); + clientResponse.payload = NULL; + + // Increment the TTLLevel (going to a next state), so we don't keep + // sending presence notification to client. + cbNode->presence->TTLlevel++; + OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", + cbNode->presence->TTLlevel); + + cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse); + if (cbResult == OC_STACK_DELETE_TRANSACTION) + { + FindAndDeleteClientCB(cbNode); + } + } + if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel]) + { + continue; + } - CATransportType_t caConType; - result = OCToCATransportType(cbNode->conType, &caConType); - caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, caConType, - &endpoint); - if (caResult != CA_STATUS_OK || result != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("CACreateRemoteEndpoint error")); - goto exit; - } + CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER}; + CAInfo_t requestData = {.type = CA_MSG_CONFIRM}; + CARequestInfo_t requestInfo = {.method = CA_GET}; - requestData.type = CA_MSG_NONCONFIRM; - requestData.token = cbNode->token; - requestData.tokenLength = cbNode->tokenLength; - requestInfo.method = CA_GET; - requestInfo.info = requestData; + OC_LOG(DEBUG, TAG, "time to test server presence"); - caResult = CASendRequest(endpoint, &requestInfo); - CADestroyRemoteEndpoint(endpoint); + CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint); - if (caResult != CA_STATUS_OK) - { - OC_LOG(ERROR, TAG, PCF("CASendRequest error")); - goto exit; - } + requestData.type = CA_MSG_NONCONFIRM; + requestData.token = cbNode->token; + requestData.tokenLength = cbNode->tokenLength; + requestData.resourceUri = OC_RSRVD_PRESENCE_URI; + requestInfo.method = CA_GET; + requestInfo.info = requestData; - cbNode->presence->TTLlevel++; - OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", - cbNode->presence->TTLlevel); - } - } + result = OCSendRequest(&endpoint, &requestInfo); + if (OC_STACK_OK != result) + { + goto exit; } + + cbNode->presence->TTLlevel++; + OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel); } exit: if (result != OC_STACK_OK) { - OC_LOG_V(ERROR, TAG, PCF("OCProcessPresence error no %d"), result); + OC_LOG(ERROR, TAG, "OCProcessPresence error"); } + return result; } #endif // WITH_PRESENCE OCStackResult OCProcess() { - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE OCProcessPresence(); - #endif +#endif CAHandleRequestResponse(); +#ifdef ROUTING_GATEWAY + RMProcess(); +#endif return OC_STACK_OK; } @@ -2537,12 +2747,12 @@ OCStackResult OCStartPresence(const uint32_t ttl) if (OC_MAX_PRESENCE_TTL_SECONDS < ttl) { presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS; - OC_LOG(INFO, TAG, PCF("Setting Presence TTL to max value")); + OC_LOG(INFO, TAG, "Setting Presence TTL to max value"); } else if (0 == ttl) { presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS; - OC_LOG(INFO, TAG, PCF("Setting Presence TTL to default value")); + OC_LOG(INFO, TAG, "Setting Presence TTL to default value"); } else { @@ -2554,24 +2764,19 @@ OCStackResult OCStartPresence(const uint32_t ttl) { presenceState = OC_PRESENCE_INITIALIZED; - CAAddress_t addressInfo; - strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE); - addressInfo.IP.port = OC_MULTICAST_PORT; + OCDevAddr devAddr = { OC_DEFAULT_ADAPTER }; CAToken_t caToken = NULL; CAResult_t caResult = CAGenerateToken(&caToken, tokenLength); if (caResult != CA_STATUS_OK) { - OC_LOG(ERROR, TAG, PCF("CAGenerateToken error")); + OC_LOG(ERROR, TAG, "CAGenerateToken error"); CADestroyToken(caToken); return OC_STACK_ERROR; } - CATransportType_t connType; - OCToCATransportType(OC_ALL, &connType ); - AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength, - (OCResource *)presenceResource.handle, OC_LOW_QOS, - &addressInfo, connType); + AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength, + (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr); CADestroyToken(caToken); } @@ -2590,17 +2795,17 @@ OCStackResult OCStopPresence() if(presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); - } // make resource inactive result = OCChangeResourceProperty( &(((OCResource *) presenceResource.handle)->resourceProperties), OC_ACTIVE, 0); + } if(result != OC_STACK_OK) { OC_LOG(ERROR, TAG, - PCF("Changing the presence resource properties to ACTIVE not successful")); + "Changing the presence resource properties to ACTIVE not successful"); return result; } @@ -2608,18 +2813,20 @@ OCStackResult OCStopPresence() } #endif -OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler) +OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, + void* callbackParameter) { defaultDeviceHandler = entityHandler; + defaultDeviceHandlerCallbackParameter = callbackParameter; return OC_STACK_OK; } OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo) { - OC_LOG(INFO, TAG, PCF("Entering OCSetPlatformInfo")); + OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo"); - if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER) + if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY) { if (validatePlatformInfo(platformInfo)) { @@ -2638,11 +2845,11 @@ OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo) OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo) { - OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo")); + OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo"); if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0') { - OC_LOG(ERROR, TAG, PCF("Null or empty device name.")); + OC_LOG(ERROR, TAG, "Null or empty device name."); return OC_STACK_INVALID_PARAM; } @@ -2653,15 +2860,15 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, const char *resourceTypeName, const char *resourceInterfaceName, const char *uri, OCEntityHandler entityHandler, + void* callbackParam, uint8_t resourceProperties) { OCResource *pointer = NULL; char *str = NULL; - size_t size = 0; OCStackResult result = OC_STACK_ERROR; - OC_LOG(INFO, TAG, PCF("Entering OCCreateResource")); + OC_LOG(INFO, TAG, "Entering OCCreateResource"); if(myStackMode == OC_CLIENT) { @@ -2670,13 +2877,13 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, // Validate parameters if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH ) { - OC_LOG(ERROR, TAG, PCF("URI is invalid")); + OC_LOG(ERROR, TAG, "URI is empty or too long"); return OC_STACK_INVALID_URI; } // Is it presented during resource discovery? - if (!handle || !resourceTypeName) + if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' ) { - OC_LOG(ERROR, TAG, PCF("Input parameter is NULL")); + OC_LOG(ERROR, TAG, "Input parameter is NULL"); return OC_STACK_INVALID_PARAM; } @@ -2687,9 +2894,10 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, // Make sure resourceProperties bitmask has allowed properties specified if (resourceProperties - > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) + > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE | + OC_EXPLICIT_DISCOVERABLE)) { - OC_LOG(ERROR, TAG, PCF("Invalid property")); + OC_LOG(ERROR, TAG, "Invalid property"); return OC_STACK_INVALID_PARAM; } @@ -2703,7 +2911,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, { if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0) { - OC_LOG(ERROR, TAG, PCF("URI already in use")); + OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri); return OC_STACK_INVALID_PARAM; } pointer = pointer->next; @@ -2721,14 +2929,12 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, insertResource(pointer); // Set the uri - size = strlen(uri) + 1; - str = (char *) OICMalloc(size); + str = OICStrdup(uri); if (!str) { result = OC_STACK_NO_MEMORY; goto exit; } - strncpy(str, uri, size); pointer->uri = str; // Set properties. Set OC_ACTIVE @@ -2739,7 +2945,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, result = BindResourceTypeToResource(pointer, resourceTypeName); if (result != OC_STACK_OK) { - OC_LOG(ERROR, TAG, PCF("Error adding resourcetype")); + OC_LOG(ERROR, TAG, "Error adding resourcetype"); goto exit; } @@ -2747,7 +2953,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, result = BindResourceInterfaceToResource(pointer, resourceInterfaceName); if (result != OC_STACK_OK) { - OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface")); + OC_LOG(ERROR, TAG, "Error adding resourceinterface"); goto exit; } @@ -2756,22 +2962,24 @@ OCStackResult OCCreateResource(OCResourceHandle *handle, if (entityHandler) { pointer->entityHandler = entityHandler; + pointer->entityHandlerCallbackParam = callbackParam; } else { pointer->entityHandler = defaultResourceEHandler; + pointer->entityHandlerCallbackParam = NULL; } *handle = pointer; result = OC_STACK_OK; - #ifdef WITH_PRESENCE - if(presenceResource.handle) +#ifdef WITH_PRESENCE + if (presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE); } - #endif +#endif exit: if (result != OC_STACK_OK) { @@ -2789,7 +2997,7 @@ OCStackResult OCBindResource( OCResource *resource = NULL; uint8_t i = 0; - OC_LOG(INFO, TAG, PCF("Entering OCBindResource")); + OC_LOG(INFO, TAG, "Entering OCBindResource"); // Validate parameters VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR); @@ -2797,7 +3005,7 @@ OCStackResult OCBindResource( // Container cannot contain itself if (collectionHandle == resourceHandle) { - OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle")); + OC_LOG(ERROR, TAG, "Added handle equals collection handle"); return OC_STACK_INVALID_PARAM; } @@ -2805,7 +3013,7 @@ OCStackResult OCBindResource( resource = findResource((OCResource *) collectionHandle); if (!resource) { - OC_LOG(ERROR, TAG, PCF("Collection handle not found")); + OC_LOG(ERROR, TAG, "Collection handle not found"); return OC_STACK_INVALID_PARAM; } @@ -2816,16 +3024,16 @@ OCStackResult OCBindResource( if (!resource->rsrcResources[i]) { resource->rsrcResources[i] = (OCResource *) resourceHandle; - OC_LOG(INFO, TAG, PCF("resource bound")); + OC_LOG(INFO, TAG, "resource bound"); - #ifdef WITH_PRESENCE - if(presenceResource.handle) +#ifdef WITH_PRESENCE + if (presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType, OC_PRESENCE_TRIGGER_CHANGE); } - #endif +#endif return OC_STACK_OK; } @@ -2841,7 +3049,7 @@ OCStackResult OCUnBindResource( OCResource *resource = NULL; uint8_t i = 0; - OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource")); + OC_LOG(INFO, TAG, "Entering OCUnBindResource"); // Validate parameters VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR); @@ -2849,7 +3057,7 @@ OCStackResult OCUnBindResource( // Container cannot contain itself if (collectionHandle == resourceHandle) { - OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle")); + OC_LOG(ERROR, TAG, "removing handle equals collection handle"); return OC_STACK_INVALID_PARAM; } @@ -2857,7 +3065,7 @@ OCStackResult OCUnBindResource( resource = findResource((OCResource *) collectionHandle); if (!resource) { - OC_LOG(ERROR, TAG, PCF("Collection handle not found")); + OC_LOG(ERROR, TAG, "Collection handle not found"); return OC_STACK_INVALID_PARAM; } @@ -2868,22 +3076,22 @@ OCStackResult OCUnBindResource( if (resourceHandle == resource->rsrcResources[i]) { resource->rsrcResources[i] = (OCResource *) NULL; - OC_LOG(INFO, TAG, PCF("resource unbound")); + OC_LOG(INFO, TAG, "resource unbound"); // Send notification when resource is unbounded successfully. - #ifdef WITH_PRESENCE - if(presenceResource.handle) +#ifdef WITH_PRESENCE + if (presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType, OC_PRESENCE_TRIGGER_CHANGE); } - #endif +#endif return OC_STACK_OK; } } - OC_LOG(INFO, TAG, PCF("resource not found in collection")); + OC_LOG(INFO, TAG, "resource not found in collection"); // Unable to add resourceHandle, so return error return OC_STACK_ERROR; @@ -2894,17 +3102,10 @@ OCStackResult BindResourceTypeToResource(OCResource* resource, { OCResourceType *pointer = NULL; char *str = NULL; - size_t size = 0; OCStackResult result = OC_STACK_ERROR; - OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource")); - - // Validate parameters VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM); - // TODO: Does resource attribute representation really have to be maintained in stack? - // Is it presented during resource discovery? - // Create the resourcetype and insert it into the resource list pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType)); if (!pointer) { @@ -2912,15 +3113,12 @@ OCStackResult BindResourceTypeToResource(OCResource* resource, goto exit; } - // Set the resourceTypeName - size = strlen(resourceTypeName) + 1; - str = (char *) OICMalloc(size); + str = OICStrdup(resourceTypeName); if (!str) { result = OC_STACK_NO_MEMORY; goto exit; } - strncpy(str, resourceTypeName, size); pointer->resourcetypename = str; insertResourceType(resource, pointer); @@ -2941,17 +3139,12 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource, { OCResourceInterface *pointer = NULL; char *str = NULL; - size_t size = 0; OCStackResult result = OC_STACK_ERROR; - OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource")); - - // Validate parameters VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM); - //TODO ("Make sure that the resourceinterface name doesn't already exist in the resource"); + OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri); - // Create the resourceinterface and insert it into the resource list pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface)); if (!pointer) { @@ -2959,15 +3152,12 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource, goto exit; } - // Set the resourceinterface name - size = strlen(resourceInterfaceName) + 1; - str = (char *) OICMalloc(size); + str = OICStrdup(resourceInterfaceName); if (!str) { result = OC_STACK_NO_MEMORY; goto exit; } - strncpy(str, resourceInterfaceName, size); pointer->name = str; // Bind the resourceinterface to the resource @@ -2992,24 +3182,22 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle, OCStackResult result = OC_STACK_ERROR; OCResource *resource = NULL; - // Make sure resource exists resource = findResource((OCResource *) handle); if (!resource) { - OC_LOG(ERROR, TAG, PCF("Resource not found")); + OC_LOG(ERROR, TAG, "Resource not found"); return OC_STACK_ERROR; } - // call internal function result = BindResourceTypeToResource(resource, resourceTypeName); - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE if(presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE); } - #endif +#endif return result; } @@ -3021,24 +3209,22 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle, OCStackResult result = OC_STACK_ERROR; OCResource *resource = NULL; - // Make sure resource exists resource = findResource((OCResource *) handle); if (!resource) { - OC_LOG(ERROR, TAG, PCF("Resource not found")); + OC_LOG(ERROR, TAG, "Resource not found"); return OC_STACK_ERROR; } - // call internal function result = BindResourceInterfaceToResource(resource, resourceInterfaceName); - #ifdef WITH_PRESENCE - if(presenceResource.handle) +#ifdef WITH_PRESENCE + if (presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE); } - #endif +#endif return result; } @@ -3047,7 +3233,6 @@ OCStackResult OCGetNumberOfResources(uint8_t *numResources) { OCResource *pointer = headResource; - OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources")); VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM); *numResources = 0; while (pointer) @@ -3062,9 +3247,6 @@ OCResourceHandle OCGetResourceHandle(uint8_t index) { OCResource *pointer = headResource; - OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle")); - - // Iterate through the list for( uint8_t i = 0; i < index && pointer; ++i) { pointer = pointer->next; @@ -3074,24 +3256,22 @@ OCResourceHandle OCGetResourceHandle(uint8_t index) OCStackResult OCDeleteResource(OCResourceHandle handle) { - OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource")); - if (!handle) { - OC_LOG(ERROR, TAG, PCF("Invalid param")); + OC_LOG(ERROR, TAG, "Invalid handle for deletion"); return OC_STACK_INVALID_PARAM; } OCResource *resource = findResource((OCResource *) handle); if (resource == NULL) { - OC_LOG(ERROR, TAG, PCF("Resource not found")); + OC_LOG(ERROR, TAG, "Resource not found"); return OC_STACK_NO_RESOURCE; } if (deleteResource((OCResource *) handle) != OC_STACK_OK) { - OC_LOG(ERROR, TAG, PCF("Error deleting resource")); + OC_LOG(ERROR, TAG, "Error deleting resource"); return OC_STACK_ERROR; } @@ -3101,7 +3281,6 @@ OCStackResult OCDeleteResource(OCResourceHandle handle) const char *OCGetResourceUri(OCResourceHandle handle) { OCResource *resource = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri")); resource = findResource((OCResource *) handle); if (resource) @@ -3114,7 +3293,6 @@ const char *OCGetResourceUri(OCResourceHandle handle) OCResourceProperty OCGetResourceProperties(OCResourceHandle handle) { OCResource *resource = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties")); resource = findResource((OCResource *) handle); if (resource) @@ -3130,7 +3308,6 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, OCResource *resource = NULL; OCResourceType *pointer = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes")); VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM); @@ -3153,8 +3330,6 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) { OCResourceType *resourceType = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName")); - resourceType = findResourceTypeAtIndex(handle, index); if (resourceType) { @@ -3169,8 +3344,6 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, OCResourceInterface *pointer = NULL; OCResource *resource = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces")); - VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM); @@ -3192,8 +3365,6 @@ const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) { OCResourceInterface *resourceInterface = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName")); - resourceInterface = findResourceInterfaceAtIndex(handle, index); if (resourceInterface) { @@ -3207,8 +3378,6 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa { OCResource *resource = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource")); - if (index >= MAX_CONTAINED_RESOURCES) { return NULL; @@ -3224,12 +3393,11 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa } OCStackResult OCBindResourceHandler(OCResourceHandle handle, - OCEntityHandler entityHandler) + OCEntityHandler entityHandler, + void* callbackParam) { OCResource *resource = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler")); - // Validate parameters VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM); @@ -3237,20 +3405,21 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle, resource = findResource((OCResource *)handle); if (!resource) { - OC_LOG(ERROR, TAG, PCF("Resource not found")); + OC_LOG(ERROR, TAG, "Resource not found"); return OC_STACK_ERROR; } // Bind the handler resource->entityHandler = entityHandler; + resource->entityHandlerCallbackParam = callbackParam; - #ifdef WITH_PRESENCE - if(presenceResource.handle) +#ifdef WITH_PRESENCE + if (presenceResource.handle) { ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE); } - #endif +#endif return OC_STACK_OK; } @@ -3259,13 +3428,10 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) { OCResource *resource = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler")); - - // Use the handle to find the resource in the resource linked list resource = findResource((OCResource *)handle); if (!resource) { - OC_LOG(ERROR, TAG, PCF("Resource not found")); + OC_LOG(ERROR, TAG, "Resource not found"); return NULL; } @@ -3330,21 +3496,18 @@ OCStackResult SendStopNotification() #endif // WITH_PRESENCE OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) { - - OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers")); - OCResource *resPtr = NULL; OCStackResult result = OC_STACK_ERROR; OCMethod method = OC_REST_NOMETHOD; uint32_t maxAge = 0; - OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers")); - #ifdef WITH_PRESENCE + OC_LOG(INFO, TAG, "Notifying all observers"); +#ifdef WITH_PRESENCE if(handle == presenceResource.handle) { return OC_STACK_OK; } - #endif // WITH_PRESENCE +#endif // WITH_PRESENCE VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR); // Verify that the resource exists @@ -3359,12 +3522,12 @@ OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService q incrementSequenceNumber(resPtr); method = OC_REST_OBSERVE; maxAge = MAX_OBSERVE_AGE; - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE result = SendAllObserverNotification (method, resPtr, maxAge, OC_PRESENCE_TRIGGER_DELETE, NULL, qos); - #else +#else result = SendAllObserverNotification (method, resPtr, maxAge, qos); - #endif +#endif return result; } } @@ -3373,10 +3536,10 @@ OCStackResult OCNotifyListOfObservers (OCResourceHandle handle, OCObservationId *obsIdList, uint8_t numberOfIds, - const char *notificationJSONPayload, + const OCRepPayload *payload, OCQualityOfService qos) { - OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers")); + OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers"); OCResource *resPtr = NULL; //TODO: we should allow the server to define this @@ -3384,9 +3547,8 @@ OCNotifyListOfObservers (OCResourceHandle handle, VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR); VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR); - VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR); + VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR); - // Verify that the resource exists resPtr = findResource ((OCResource *) handle); if (NULL == resPtr || myStackMode == OC_CLIENT) { @@ -3397,7 +3559,7 @@ OCNotifyListOfObservers (OCResourceHandle handle, incrementSequenceNumber(resPtr); } return (SendListObserverNotification(resPtr, obsIdList, numberOfIds, - notificationJSONPayload, maxAge, qos)); + payload, maxAge, qos)); } OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse) @@ -3405,41 +3567,21 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse) OCStackResult result = OC_STACK_ERROR; OCServerRequest *serverRequest = NULL; - OC_LOG(INFO, TAG, PCF("Entering OCDoResponse")); + OC_LOG(INFO, TAG, "Entering OCDoResponse"); // Validate input parameters VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM); VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM); - // TODO: Placeholder for creating a response entry when implementing - // block transfer feature - - // If a response payload is present, check if block transfer is required - if (ehResponse->payload && OCIsPacketTransferRequired(NULL, - (const char *)ehResponse->payload, ehResponse->payloadSize)) - { - OC_LOG(INFO, TAG, PCF("Block transfer required")); - - // Persistent response buffer is needed for block transfer - if (!ehResponse->persistentBufferFlag) - { - OC_LOG(WARNING, TAG, PCF("Persistent response buffer required")); - return OC_STACK_PERSISTENT_BUFFER_REQUIRED; - } - // TODO: Placeholder for block transfer handling - // TODO: Placeholder for setting the the response handle in the OCServerResponse struct - // when implementing the block transfer feature - } - else + // Normal response + // Get pointer to request info + serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle); + if(serverRequest) { - // Normal response - // Get pointer to request info - serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle); - if(serverRequest) - { - result = serverRequest->ehResponseHandler(ehResponse); - } + // response handler in ocserverrequest.c. Usually HandleSingleResponse. + result = serverRequest->ehResponseHandler(ehResponse); } + return result; } @@ -3470,7 +3612,7 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty, if (resourceProperties > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) { - OC_LOG(ERROR, TAG, PCF("Invalid property")); + OC_LOG(ERROR, TAG, "Invalid property"); return OC_STACK_INVALID_PARAM; } if(!enable) @@ -3488,24 +3630,25 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty, OCStackResult initResources() { OCStackResult result = OC_STACK_OK; - // Init application resource vars + headResource = NULL; tailResource = NULL; // Init Virtual Resources - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS; - //presenceResource.token = OCGenerateCoAPToken(); + result = OCCreateResource(&presenceResource.handle, OC_RSRVD_RESOURCE_TYPE_PRESENCE, "core.r", - OC_PRESENCE_URI, + OC_RSRVD_PRESENCE_URI, + NULL, NULL, OC_OBSERVABLE); //make resource inactive result = OCChangeResourceProperty( &(((OCResource *) presenceResource.handle)->resourceProperties), OC_ACTIVE, 0); - #endif +#endif if (result == OC_STACK_OK) { @@ -3553,30 +3696,37 @@ void deleteAllResources() while (pointer) { temp = pointer->next; - #ifdef WITH_PRESENCE - if(pointer != (OCResource *) presenceResource.handle) +#ifdef WITH_PRESENCE + if (pointer != (OCResource *) presenceResource.handle) { - #endif // WITH_PRESENCE +#endif // WITH_PRESENCE deleteResource(pointer); - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE } - #endif // WITH_PRESENCE +#endif // WITH_PRESENCE pointer = temp; } SRMDeInitSecureResources(); - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE // Ensure that the last resource to be deleted is the presence resource. This allows for all // presence notification attributed to their deletion to be processed. deleteResource((OCResource *) presenceResource.handle); - #endif // WITH_PRESENCE +#endif // WITH_PRESENCE } OCStackResult deleteResource(OCResource *resource) { OCResource *prev = NULL; OCResource *temp = NULL; + if(!resource) + { + OC_LOG(DEBUG,TAG,"resource is NULL"); + return OC_STACK_INVALID_PARAM; + } + + OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri); temp = headResource; while (temp) @@ -3585,12 +3735,12 @@ OCStackResult deleteResource(OCResource *resource) { // Invalidate all Resource Properties. resource->resourceProperties = (OCResourceProperty) 0; - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE if(resource != (OCResource *) presenceResource.handle) { - #endif // WITH_PRESENCE +#endif // WITH_PRESENCE OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS); - #ifdef WITH_PRESENCE +#ifdef WITH_PRESENCE } if(presenceResource.handle) @@ -3598,7 +3748,7 @@ OCStackResult deleteResource(OCResource *resource) ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE); } - #endif +#endif // Only resource in list. if (temp == headResource && temp == tailResource) { @@ -3642,13 +3792,8 @@ void deleteResourceElements(OCResource *resource) return; } - // remove URI OICFree(resource->uri); - - // Delete resourcetype linked list deleteResourceType(resource->rsrcType); - - // Delete resourceinterface linked list deleteResourceInterface(resource->rsrcInterface); } @@ -3699,9 +3844,9 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType) while (pointer) { - // resource type already exists. Free 2nd arg and return. if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename)) { + OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename); OICFree(resourceType->resourcetypename); OICFree(resourceType); return; @@ -3712,6 +3857,8 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType) previous->next = resourceType; } resourceType->next = NULL; + + OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri); } OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) @@ -3840,58 +3987,6 @@ OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle, return pointer; } -bool OCIsPacketTransferRequired(const char *request, const char *response, size_t size) -{ - bool result = false; - - // Determine if we are checking a request or a response - if (request) - { - // If size is greater than 0, use it for the request size value, otherwise - // assume request is null terminated and use strlen for size value - if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH)) - { - result = true; - } - } - else if (response) - { - // If size is greater than 0, use it for the response size value, otherwise - // assume response is null terminated and use strlen for size value - if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH)) - { - result = true; - } - } - return result; -} - -OCStackResult getResourceType(const char * query, char** resourceType) -{ - if(!query) - { - return OC_STACK_INVALID_PARAM; - } - - OCStackResult result = OC_STACK_ERROR; - - if(strncmp(query, "rt=", 3) == 0) - { - *resourceType = (char *) OICMalloc(strlen(query)-3 + 1); - if(!*resourceType) - { - result = OC_STACK_NO_MEMORY; - } - else - { - strcpy((char *)*resourceType, ((const char *)&query[3])); - result = OC_STACK_OK; - } - } - - return result; -} - /* * This function splits the uri using the '?' delimiter. * "uriWithoutQuery" is the block of characters between the beginning @@ -3925,7 +4020,7 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout char *pointerToDelimiter = strstr(uri, "?"); - uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : pointerToDelimiter - uri; + uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri); queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1; if (uriWithoutQueryLen) @@ -3935,13 +4030,8 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout { goto exit; } - strncpy(*uriWithoutQuery, uri, uriWithoutQueryLen); - } - else - { - return OC_STACK_INVALID_PARAM; + OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri); } - if (queryLen) { *query = (char *) OICCalloc(queryLen + 1, 1); @@ -3951,7 +4041,7 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout *uriWithoutQuery = NULL; goto exit; } - strncpy(*query, pointerToDelimiter + 1, queryLen); + OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1); } return OC_STACK_OK; @@ -3960,22 +4050,22 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout return OC_STACK_NO_MEMORY; } -const uint8_t* OCGetServerInstanceID(void) +const OicUuid_t* OCGetServerInstanceID(void) { static bool generated = false; - static ServerID sid; - if(generated) + static OicUuid_t sid; + if (generated) { - return sid; + return &sid; } - if (OCGenerateUuid(sid) != RAND_UUID_OK) + if (GetDoxmDeviceID(&sid) != OC_STACK_OK) { - OC_LOG(FATAL, TAG, PCF("Generate UUID for Server Instance failed!")); + OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!"); return NULL; } generated = true; - return sid; + return &sid; } const char* OCGetServerInstanceIDString(void) @@ -3988,11 +4078,11 @@ const char* OCGetServerInstanceIDString(void) return sidStr; } - const uint8_t* sid = OCGetServerInstanceID(); + const OicUuid_t* sid = OCGetServerInstanceID(); - if(OCConvertUuidToString(sid, sidStr) != RAND_UUID_OK) + if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK) { - OC_LOG(FATAL, TAG, PCF("Generate UUID String for Server Instance failed!")); + OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!"); return NULL; } @@ -4000,45 +4090,20 @@ const char* OCGetServerInstanceIDString(void) return sidStr; } -int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b, - uint8_t *c, uint8_t *d ) -{ - if ( !ipAddr || !a || !b || !c || !d ) - { - OC_LOG(FATAL, TAG, PCF("Invalid argument")); - return OC_STACK_INVALID_PARAM; - } - - *a = ipAddr->addr[0]; - *b = ipAddr->addr[1]; - *c = ipAddr->addr[2]; - *d = ipAddr->addr[3]; - - return OC_STACK_OK; -} - -int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port) -{ - if ( !ipAddr || !port ) - { - OC_LOG(FATAL, TAG, PCF("Invalid argument")); - return OC_STACK_INVALID_PARAM; - } - - *port = (ipAddr->addr[5]<< 8) | ipAddr->addr[4]; - - return OC_STACK_OK; -} - CAResult_t OCSelectNetwork() { CAResult_t retResult = CA_STATUS_FAILED; CAResult_t caResult = CA_STATUS_OK; - CATransportType_t connTypes[] = { - CA_IPV4, - CA_EDR, - CA_LE}; + CATransportAdapter_t connTypes[] = { + CA_ADAPTER_IP, + CA_ADAPTER_RFCOMM_BTEDR, + CA_ADAPTER_GATT_BTLE + +#ifdef RA_ADAPTER + ,CA_ADAPTER_REMOTE_ACCESS +#endif + }; int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]); for(int i = 0; i