1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #define __STDC_FORMAT_MACROS
34 #define __STDC_LIMIT_MACROS
40 #include "ocstackinternal.h"
41 #include "ocresourcehandler.h"
42 #include "occlientcb.h"
43 #include "ocobserve.h"
45 #include "oic_malloc.h"
46 #include "oic_string.h"
48 #include "ocserverrequest.h"
49 #include "secureresourcemanager.h"
50 #include "doxmresource.h"
52 #include "cainterface.h"
53 #include "ocpayload.h"
54 #include "ocpayloadcbor.h"
56 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
57 #include "routingutility.h"
58 #ifdef ROUTING_GATEWAY
59 #include "routingmanager.h"
68 #include "coap_time.h"
73 #include <arpa/inet.h>
77 #define UINT32_MAX (0xFFFFFFFFUL)
80 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
85 OC_STACK_UNINITIALIZED = 0,
87 OC_STACK_UNINIT_IN_PROGRESS
93 OC_PRESENCE_UNINITIALIZED = 0,
94 OC_PRESENCE_INITIALIZED
98 //-----------------------------------------------------------------------------
100 //-----------------------------------------------------------------------------
101 static OCStackState stackState = OC_STACK_UNINITIALIZED;
103 OCResource *headResource = NULL;
104 static OCResource *tailResource = NULL;
106 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
107 static PresenceResource presenceResource;
108 static uint8_t PresenceTimeOutSize = 0;
109 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
112 static OCMode myStackMode;
114 //TODO: revisit this design
115 static bool gRASetInfo = false;
117 OCDeviceEntityHandler defaultDeviceHandler;
118 void* defaultDeviceHandlerCallbackParameter = NULL;
119 static const char COAP_TCP[] = "coap+tcp:";
122 //-----------------------------------------------------------------------------
124 //-----------------------------------------------------------------------------
125 #define TAG "OCStack"
126 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
127 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
128 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
129 TAG, #arg " is NULL"); return (retVal); } }
130 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
131 TAG, #arg " is NULL"); return; } }
132 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
135 //TODO: we should allow the server to define this
136 #define MAX_OBSERVE_AGE (0x2FFFFUL)
138 #define MILLISECONDS_PER_SECOND (1000)
140 //-----------------------------------------------------------------------------
141 // Private internal function prototypes
142 //-----------------------------------------------------------------------------
145 * Generate handle of OCDoResource invocation for callback management.
147 * @return Generated OCDoResource handle.
149 static OCDoHandle GenerateInvocationHandle();
152 * Initialize resource data structures, variables, etc.
154 * @return ::OC_STACK_OK on success, some other value upon failure.
156 static OCStackResult initResources();
159 * Add a resource to the end of the linked list of resources.
161 * @param resource Resource to be added
163 static void insertResource(OCResource *resource);
166 * Find a resource in the linked list of resources.
168 * @param resource Resource to be found.
169 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
172 static OCResource *findResource(OCResource *resource);
175 * Insert a resource type into a resource's resource type linked list.
176 * If resource type already exists, it will not be inserted and the
177 * resourceType will be free'd.
178 * resourceType->next should be null to avoid memory leaks.
179 * Function returns silently for null args.
181 * @param resource Resource where resource type is to be inserted.
182 * @param resourceType Resource type to be inserted.
184 static void insertResourceType(OCResource *resource,
185 OCResourceType *resourceType);
188 * Get a resource type at the specified index within a resource.
190 * @param handle Handle of resource.
191 * @param index Index of resource type.
193 * @return Pointer to resource type if found, NULL otherwise.
195 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
199 * Insert a resource interface into a resource's resource interface linked list.
200 * If resource interface already exists, it will not be inserted and the
201 * resourceInterface will be free'd.
202 * resourceInterface->next should be null to avoid memory leaks.
204 * @param resource Resource where resource interface is to be inserted.
205 * @param resourceInterface Resource interface to be inserted.
207 static void insertResourceInterface(OCResource *resource,
208 OCResourceInterface *resourceInterface);
211 * Get a resource interface at the specified index within a resource.
213 * @param handle Handle of resource.
214 * @param index Index of resource interface.
216 * @return Pointer to resource interface if found, NULL otherwise.
218 static OCResourceInterface *findResourceInterfaceAtIndex(
219 OCResourceHandle handle, uint8_t index);
222 * Delete all of the dynamically allocated elements that were created for the resource type.
224 * @param resourceType Specified resource type.
226 static void deleteResourceType(OCResourceType *resourceType);
229 * Delete all of the dynamically allocated elements that were created for the resource interface.
231 * @param resourceInterface Specified resource interface.
233 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
236 * Delete all of the dynamically allocated elements that were created for the resource.
238 * @param resource Specified resource.
240 static void deleteResourceElements(OCResource *resource);
243 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
246 * @param handle Handle of resource to be deleted.
248 * @return ::OC_STACK_OK on success, some other value upon failure.
250 static OCStackResult deleteResource(OCResource *resource);
253 * Delete all of the resources in the resource list.
255 static void deleteAllResources();
258 * Increment resource sequence number. Handles rollover.
260 * @param resPtr Pointer to resource.
262 static void incrementSequenceNumber(OCResource * resPtr);
265 * Verify the lengths of the URI and the query separately.
267 * @param inputUri Input URI and query.
268 * @param uriLen The length of the initial URI with query.
269 * @return ::OC_STACK_OK on success, some other value upon failure.
271 static OCStackResult verifyUriQueryLength(const char * inputUri,
275 * Attempts to initialize every network interface that the CA Layer might have compiled in.
277 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
278 * return something other than @ref CA_STATUS_OK, then this function fails.
280 * @return ::CA_STATUS_OK on success, some other value upon failure.
282 static CAResult_t OCSelectNetwork();
285 * Get the CoAP ticks after the specified number of milli-seconds.
287 * @param afterMilliSeconds Milli-seconds.
291 static uint32_t GetTicks(uint32_t afterMilliSeconds);
294 * Convert CAResponseResult_t to OCStackResult.
296 * @param caCode CAResponseResult_t code.
297 * @return ::OC_STACK_OK on success, some other value upon failure.
299 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
302 * Convert OCStackResult to CAResponseResult_t.
304 * @param caCode OCStackResult code.
305 * @param method OCMethod method the return code replies to.
306 * @return ::CA_CONTENT on OK, some other value upon failure.
308 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
311 * Convert OCTransportFlags_t to CATransportModifiers_t.
313 * @param ocConType OCTransportFlags_t input.
314 * @return CATransportFlags
316 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
319 * Convert CATransportFlags_t to OCTransportModifiers_t.
321 * @param caConType CATransportFlags_t input.
322 * @return OCTransportFlags
324 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
327 * Handle response from presence request.
329 * @param endPoint CA remote endpoint.
330 * @param responseInfo CA response info.
331 * @return ::OC_STACK_OK on success, some other value upon failure.
333 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
334 const CAResponseInfo_t *responseInfo);
337 * This function will be called back by CA layer when a response is received.
339 * @param endPoint CA remote endpoint.
340 * @param responseInfo CA response info.
342 static void HandleCAResponses(const CAEndpoint_t* endPoint,
343 const CAResponseInfo_t* responseInfo);
346 * This function will be called back by CA layer when a request is received.
348 * @param endPoint CA remote endpoint.
349 * @param requestInfo CA request info.
351 static void HandleCARequests(const CAEndpoint_t* endPoint,
352 const CARequestInfo_t* requestInfo);
355 * Extract query from a URI.
357 * @param uri Full URI with query.
358 * @param query Pointer to string that will contain query.
359 * @param newURI Pointer to string that will contain URI.
360 * @return ::OC_STACK_OK on success, some other value upon failure.
362 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
365 * Finds a resource type in an OCResourceType link-list.
367 * @param resourceTypeList The link-list to be searched through.
368 * @param resourceTypeName The key to search for.
370 * @return Resource type that matches the key (ie. resourceTypeName) or
371 * NULL if there is either an invalid parameter or this function was unable to find the key.
373 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
374 const char * resourceTypeName);
377 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
378 * TTL will be set to maxAge.
380 * @param cbNode Callback Node for which presence ttl is to be reset.
381 * @param maxAge New value of ttl in seconds.
383 * @return ::OC_STACK_OK on success, some other value upon failure.
385 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
388 * Ensure the accept header option is set appropriatly before sending the requests and routing
389 * header option is updated with destination.
391 * @param object CA remote endpoint.
392 * @param requestInfo CA request info.
394 * @return ::OC_STACK_OK on success, some other value upon failure.
396 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
398 //-----------------------------------------------------------------------------
399 // Internal functions
400 //-----------------------------------------------------------------------------
402 uint32_t GetTicks(uint32_t afterMilliSeconds)
407 // Guard against overflow of uint32_t
408 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
409 COAP_TICKS_PER_SECOND)
411 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
419 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
421 VERIFY_NON_NULL_NR(in, FATAL);
422 VERIFY_NON_NULL_NR(out, FATAL);
424 out->adapter = (OCTransportAdapter)in->adapter;
425 out->flags = CAToOCTransportFlags(in->flags);
426 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
427 out->port = in->port;
428 out->interface = in->interface;
429 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
430 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
434 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
436 VERIFY_NON_NULL_NR(in, FATAL);
437 VERIFY_NON_NULL_NR(out, FATAL);
439 out->adapter = (CATransportAdapter_t)in->adapter;
440 out->flags = OCToCATransportFlags(in->flags);
441 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
442 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
443 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
445 out->port = in->port;
446 out->interface = in->interface;
449 void FixUpClientResponse(OCClientResponse *cr)
451 VERIFY_NON_NULL_NR(cr, FATAL);
453 cr->addr = &cr->devAddr;
454 cr->connType = (OCConnectivityType)
455 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
458 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
460 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
461 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
463 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
464 OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
465 &(requestInfo->info.numOptions));
466 if (OC_STACK_OK != rmResult)
468 OC_LOG(ERROR, TAG, "Add destination option failed");
473 // OC stack prefer CBOR encoded payloads.
474 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
475 CAResult_t result = CASendRequest(object, requestInfo);
476 if(CA_STATUS_OK != result)
478 OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
479 return CAResultToOCResult(result);
483 //-----------------------------------------------------------------------------
484 // Internal API function
485 //-----------------------------------------------------------------------------
487 // This internal function is called to update the stack with the status of
488 // observers and communication failures
489 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
491 OCStackResult result = OC_STACK_ERROR;
492 ResourceObserver * observer = NULL;
493 OCEntityHandlerRequest ehRequest = {0};
497 case OC_OBSERVER_NOT_INTERESTED:
498 OC_LOG(DEBUG, TAG, "observer not interested in our notifications");
499 observer = GetObserverUsingToken (token, tokenLength);
502 result = FormOCEntityHandlerRequest(&ehRequest,
503 (OCRequestHandle)NULL,
506 (OCResourceHandle)NULL,
507 NULL, PAYLOAD_TYPE_REPRESENTATION,
509 OC_OBSERVE_DEREGISTER,
510 observer->observeId);
511 if(result != OC_STACK_OK)
515 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
516 observer->resource->entityHandlerCallbackParam);
519 result = DeleteObserverUsingToken (token, tokenLength);
520 if(result == OC_STACK_OK)
522 OC_LOG(DEBUG, TAG, "Removed observer successfully");
526 result = OC_STACK_OK;
527 OC_LOG(DEBUG, TAG, "Observer Removal failed");
531 case OC_OBSERVER_STILL_INTERESTED:
532 OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
533 observer = GetObserverUsingToken (token, tokenLength);
536 observer->forceHighQos = 0;
537 observer->failedCommCount = 0;
538 result = OC_STACK_OK;
542 result = OC_STACK_OBSERVER_NOT_FOUND;
546 case OC_OBSERVER_FAILED_COMM:
547 OC_LOG(DEBUG, TAG, "observer is unreachable");
548 observer = GetObserverUsingToken (token, tokenLength);
551 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
553 result = FormOCEntityHandlerRequest(&ehRequest,
554 (OCRequestHandle)NULL,
557 (OCResourceHandle)NULL,
558 NULL, PAYLOAD_TYPE_REPRESENTATION,
560 OC_OBSERVE_DEREGISTER,
561 observer->observeId);
562 if(result != OC_STACK_OK)
564 return OC_STACK_ERROR;
566 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
567 observer->resource->entityHandlerCallbackParam);
569 result = DeleteObserverUsingToken (token, tokenLength);
570 if(result == OC_STACK_OK)
572 OC_LOG(DEBUG, TAG, "Removed observer successfully");
576 result = OC_STACK_OK;
577 OC_LOG(DEBUG, TAG, "Observer Removal failed");
582 observer->failedCommCount++;
583 result = OC_STACK_CONTINUE;
585 observer->forceHighQos = 1;
586 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
590 OC_LOG(ERROR, TAG, "Unknown status");
591 result = OC_STACK_ERROR;
596 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
598 OCStackResult ret = OC_STACK_ERROR;
603 ret = OC_STACK_RESOURCE_CREATED;
606 ret = OC_STACK_RESOURCE_DELETED;
613 ret = OC_STACK_INVALID_QUERY;
615 case CA_UNAUTHORIZED_REQ:
616 ret = OC_STACK_UNAUTHORIZED_REQ;
619 ret = OC_STACK_INVALID_OPTION;
622 ret = OC_STACK_NO_RESOURCE;
624 case CA_RETRANSMIT_TIMEOUT:
625 ret = OC_STACK_COMM_ERROR;
633 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
635 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
644 // This Response Code is like HTTP 204 "No Content" but only used in
645 // response to POST and PUT requests.
649 // This Response Code is like HTTP 200 "OK" but only used in response to
654 // This should not happen but,
655 // give it a value just in case but output an error
657 OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
660 case OC_STACK_RESOURCE_CREATED:
663 case OC_STACK_RESOURCE_DELETED:
666 case OC_STACK_INVALID_QUERY:
669 case OC_STACK_INVALID_OPTION:
672 case OC_STACK_NO_RESOURCE:
675 case OC_STACK_COMM_ERROR:
676 ret = CA_RETRANSMIT_TIMEOUT;
678 case OC_STACK_UNAUTHORIZED_REQ:
679 ret = CA_UNAUTHORIZED_REQ;
687 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
689 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
691 // supply default behavior.
692 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
694 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
696 if ((caFlags & OC_MASK_SCOPE) == 0)
698 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
703 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
705 return (OCTransportFlags)caFlags;
708 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
710 uint32_t lowerBound = 0;
711 uint32_t higherBound = 0;
713 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
715 return OC_STACK_INVALID_PARAM;
718 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
720 cbNode->presence->TTL = maxAgeSeconds;
722 for (int index = 0; index < PresenceTimeOutSize; index++)
724 // Guard against overflow
725 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
728 lowerBound = GetTicks((PresenceTimeOut[index] *
729 cbNode->presence->TTL *
730 MILLISECONDS_PER_SECOND)/100);
734 lowerBound = GetTicks(UINT32_MAX);
737 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
740 higherBound = GetTicks((PresenceTimeOut[index + 1] *
741 cbNode->presence->TTL *
742 MILLISECONDS_PER_SECOND)/100);
746 higherBound = GetTicks(UINT32_MAX);
749 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
751 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
752 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
753 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
756 cbNode->presence->TTLlevel = 0;
758 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
762 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
764 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
766 return OC_RSRVD_TRIGGER_CREATE;
768 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
770 return OC_RSRVD_TRIGGER_CHANGE;
774 return OC_RSRVD_TRIGGER_DELETE;
778 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
782 return OC_PRESENCE_TRIGGER_CREATE;
784 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
786 return OC_PRESENCE_TRIGGER_CREATE;
788 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
790 return OC_PRESENCE_TRIGGER_CHANGE;
794 return OC_PRESENCE_TRIGGER_DELETE;
799 * The cononical presence allows constructed URIs to be string compared.
801 * requestUri must be a char array of size CA_MAX_URI_LENGTH
803 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
806 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
807 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
808 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
810 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
812 if (ep->adapter == CA_ADAPTER_IP)
814 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
816 if ('\0' == ep->addr[0]) // multicast
818 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
822 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
823 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
828 if ('\0' == ep->addr[0]) // multicast
830 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
831 ep->port = OC_MULTICAST_PORT;
833 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
834 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
838 // might work for other adapters (untested, but better than nothing)
839 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
840 OC_RSRVD_PRESENCE_URI);
844 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
845 const CAResponseInfo_t *responseInfo)
847 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
848 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
850 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
851 ClientCB * cbNode = NULL;
852 char *resourceTypeName = NULL;
853 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
854 OCStackResult result = OC_STACK_ERROR;
857 char presenceUri[CA_MAX_URI_LENGTH];
859 int presenceSubscribe = 0;
860 int multicastPresenceSubscribe = 0;
862 if (responseInfo->result != CA_CONTENT)
864 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
865 return OC_STACK_ERROR;
868 // check for unicast presence
869 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
870 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
872 return OC_STACK_INVALID_URI;
875 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
878 presenceSubscribe = 1;
882 // check for multiicast presence
883 CAEndpoint_t ep = { .adapter = endpoint->adapter,
884 .flags = endpoint->flags };
886 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
888 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
891 multicastPresenceSubscribe = 1;
895 if (!presenceSubscribe && !multicastPresenceSubscribe)
897 OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
901 response.payload = NULL;
902 response.result = OC_STACK_OK;
904 CopyEndpointToDevAddr(endpoint, &response.devAddr);
905 FixUpClientResponse(&response);
907 if (responseInfo->info.payload)
909 result = OCParsePayload(&response.payload,
910 PAYLOAD_TYPE_PRESENCE,
911 responseInfo->info.payload,
912 responseInfo->info.payloadSize);
914 if(result != OC_STACK_OK)
916 OC_LOG(ERROR, TAG, "Presence parse failed");
919 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
921 OC_LOG(ERROR, TAG, "Presence payload was wrong type");
922 result = OC_STACK_ERROR;
925 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
926 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
927 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
930 if (presenceSubscribe)
932 if(cbNode->sequenceNumber == response.sequenceNumber)
934 OC_LOG(INFO, TAG, "No presence change");
935 ResetPresenceTTL(cbNode, maxAge);
936 OC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
942 OC_LOG(INFO, TAG, "Stopping presence");
943 response.result = OC_STACK_PRESENCE_STOPPED;
946 OICFree(cbNode->presence->timeOut);
947 OICFree(cbNode->presence);
948 cbNode->presence = NULL;
953 if(!cbNode->presence)
955 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
957 if(!(cbNode->presence))
959 OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
960 result = OC_STACK_NO_MEMORY;
964 VERIFY_NON_NULL_V(cbNode->presence);
965 cbNode->presence->timeOut = NULL;
966 cbNode->presence->timeOut = (uint32_t *)
967 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
968 if(!(cbNode->presence->timeOut)){
970 "Could not allocate memory for cbNode->presence->timeOut");
971 OICFree(cbNode->presence);
972 result = OC_STACK_NO_MEMORY;
977 ResetPresenceTTL(cbNode, maxAge);
979 cbNode->sequenceNumber = response.sequenceNumber;
981 // Ensure that a filter is actually applied.
982 if( resourceTypeName && cbNode->filterResourceType)
984 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
993 // This is the multicast case
994 OCMulticastNode* mcNode = NULL;
995 mcNode = GetMCPresenceNode(presenceUri);
999 if(mcNode->nonce == response.sequenceNumber)
1001 OC_LOG(INFO, TAG, "No presence change (Multicast)");
1004 mcNode->nonce = response.sequenceNumber;
1008 OC_LOG(INFO, TAG, "Stopping presence");
1009 response.result = OC_STACK_PRESENCE_STOPPED;
1014 char* uri = OICStrdup(presenceUri);
1018 "No Memory for URI to store in the presence node");
1019 result = OC_STACK_NO_MEMORY;
1023 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1024 if(result == OC_STACK_NO_MEMORY)
1027 "No Memory for Multicast Presence Node");
1031 // presence node now owns uri
1034 // Ensure that a filter is actually applied.
1035 if(resourceTypeName && cbNode->filterResourceType)
1037 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1044 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1046 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1048 FindAndDeleteClientCB(cbNode);
1052 OCPayloadDestroy(response.payload);
1056 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1058 VERIFY_NON_NULL_NR(endPoint, FATAL);
1059 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1061 OC_LOG(INFO, TAG, "Enter HandleCAResponses");
1063 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1064 #ifdef ROUTING_GATEWAY
1065 bool needRIHandling = false;
1067 * Routing manager is going to update either of endpoint or response or both.
1068 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1069 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1072 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1074 if(ret != OC_STACK_OK || !needRIHandling)
1076 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1082 * Put source in sender endpoint so that the next packet from application can be routed to
1083 * proper destination and remove "RM" coap header option before passing request / response to
1084 * RI as this option will make no sense to either RI or application.
1086 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1087 (uint8_t *) &(responseInfo->info.numOptions),
1088 (CAEndpoint_t *) endPoint);
1091 if(responseInfo->info.resourceUri &&
1092 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1094 HandlePresenceResponse(endPoint, responseInfo);
1098 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1099 responseInfo->info.tokenLength, NULL, NULL);
1101 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1102 responseInfo->info.tokenLength);
1106 OC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1107 if(responseInfo->result == CA_EMPTY)
1109 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1110 // We do not have a case for the client to receive a RESET
1111 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1113 //This is the case of receiving an ACK on a request to a slow resource!
1114 OC_LOG(INFO, TAG, "This is a pure ACK");
1115 //TODO: should we inform the client
1116 // app that at least the request was received at the server?
1119 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1121 OC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1122 OC_LOG(INFO, TAG, "Calling into application address space");
1124 OCClientResponse response =
1125 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1126 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1127 FixUpClientResponse(&response);
1128 response.resourceUri = responseInfo->info.resourceUri;
1129 memcpy(response.identity.id, responseInfo->info.identity.id,
1130 sizeof (response.identity.id));
1131 response.identity.id_length = responseInfo->info.identity.id_length;
1133 response.result = CAToOCStackResult(responseInfo->result);
1134 cbNode->callBack(cbNode->context,
1135 cbNode->handle, &response);
1136 FindAndDeleteClientCB(cbNode);
1140 OC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1141 OC_LOG(INFO, TAG, "Calling into application address space");
1143 OCClientResponse response =
1144 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1145 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1146 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1147 FixUpClientResponse(&response);
1148 response.resourceUri = responseInfo->info.resourceUri;
1149 memcpy(response.identity.id, responseInfo->info.identity.id,
1150 sizeof (response.identity.id));
1151 response.identity.id_length = responseInfo->info.identity.id_length;
1153 response.result = CAToOCStackResult(responseInfo->result);
1155 if(responseInfo->info.payload &&
1156 responseInfo->info.payloadSize)
1158 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1159 // check the security resource
1160 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1162 type = PAYLOAD_TYPE_SECURITY;
1164 else if (cbNode->method == OC_REST_DISCOVER)
1166 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1167 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1169 type = PAYLOAD_TYPE_DISCOVERY;
1171 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1173 type = PAYLOAD_TYPE_DEVICE;
1175 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1177 type = PAYLOAD_TYPE_PLATFORM;
1179 #ifdef ROUTING_GATEWAY
1180 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1182 type = PAYLOAD_TYPE_REPRESENTATION;
1185 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1187 type = PAYLOAD_TYPE_RD;
1191 OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1192 cbNode->method, cbNode->requestUri);
1196 else if (cbNode->method == OC_REST_GET ||
1197 cbNode->method == OC_REST_PUT ||
1198 cbNode->method == OC_REST_POST ||
1199 cbNode->method == OC_REST_OBSERVE ||
1200 cbNode->method == OC_REST_OBSERVE_ALL ||
1201 cbNode->method == OC_REST_DELETE)
1203 char targetUri[MAX_URI_LENGTH];
1204 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
1205 OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1206 if (strcmp(targetUri, cbNode->requestUri) == 0)
1208 type = PAYLOAD_TYPE_RD;
1210 if (type == PAYLOAD_TYPE_INVALID)
1212 OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1213 cbNode->method, cbNode->requestUri);
1214 type = PAYLOAD_TYPE_REPRESENTATION;
1219 OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1220 cbNode->method, cbNode->requestUri);
1224 if(OC_STACK_OK != OCParsePayload(&response.payload,
1226 responseInfo->info.payload,
1227 responseInfo->info.payloadSize))
1229 OC_LOG(ERROR, TAG, "Error converting payload");
1230 OCPayloadDestroy(response.payload);
1235 response.numRcvdVendorSpecificHeaderOptions = 0;
1236 if(responseInfo->info.numOptions > 0)
1239 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1240 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1243 uint32_t observationOption;
1244 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1245 for (observationOption=0, i=0;
1246 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1250 (observationOption << 8) | optionData[i];
1252 response.sequenceNumber = observationOption;
1254 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1259 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1262 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1264 OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1265 OCPayloadDestroy(response.payload);
1269 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1271 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1272 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1276 if (cbNode->method == OC_REST_OBSERVE &&
1277 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1278 response.sequenceNumber <= cbNode->sequenceNumber)
1280 OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1281 response.sequenceNumber);
1285 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1288 cbNode->sequenceNumber = response.sequenceNumber;
1290 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1292 FindAndDeleteClientCB(cbNode);
1296 // To keep discovery callbacks active.
1297 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1298 MILLISECONDS_PER_SECOND);
1302 //Need to send ACK when the response is CON
1303 if(responseInfo->info.type == CA_MSG_CONFIRM)
1305 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1306 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1309 OCPayloadDestroy(response.payload);
1316 OC_LOG(INFO, TAG, "There is an observer associated with the response token");
1317 if(responseInfo->result == CA_EMPTY)
1319 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1320 if(responseInfo->info.type == CA_MSG_RESET)
1322 OC_LOG(INFO, TAG, "This is a RESET");
1323 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1324 OC_OBSERVER_NOT_INTERESTED);
1326 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1328 OC_LOG(INFO, TAG, "This is a pure ACK");
1329 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1330 OC_OBSERVER_STILL_INTERESTED);
1333 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1335 OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1336 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1337 OC_OBSERVER_FAILED_COMM);
1342 if(!cbNode && !observer)
1344 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1345 || myStackMode == OC_GATEWAY)
1347 OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1348 if(responseInfo->result == CA_EMPTY)
1350 OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1354 OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1355 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1356 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1360 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1361 || myStackMode == OC_GATEWAY)
1363 OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1364 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1366 OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1367 responseInfo->info.messageId);
1369 if (responseInfo->info.type == CA_MSG_RESET)
1371 OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1372 responseInfo->info.messageId);
1379 OC_LOG(INFO, TAG, "Exit HandleCAResponses");
1383 * This function handles error response from CA
1384 * code shall be added to handle the errors
1386 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1388 OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1390 if(NULL == endPoint)
1392 OC_LOG(ERROR, TAG, "endPoint is NULL");
1396 if(NULL == errrorInfo)
1398 OC_LOG(ERROR, TAG, "errrorInfo is NULL");
1401 OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1405 * This function sends out Direct Stack Responses. These are responses that are not coming
1406 * from the application entity handler. These responses have no payload and are usually ACKs,
1407 * RESETs or some error conditions that were caught by the stack.
1409 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1410 const CAResponseResult_t responseResult, const CAMessageType_t type,
1411 const uint8_t numOptions, const CAHeaderOption_t *options,
1412 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1414 CAResponseInfo_t respInfo = {
1415 .result = responseResult
1417 respInfo.info.messageId = coapID;
1418 respInfo.info.numOptions = numOptions;
1420 if (respInfo.info.numOptions)
1422 respInfo.info.options =
1423 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1424 memcpy (respInfo.info.options, options,
1425 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1429 respInfo.info.payload = NULL;
1430 respInfo.info.token = token;
1431 respInfo.info.tokenLength = tokenLength;
1432 respInfo.info.type = type;
1433 respInfo.info.resourceUri = OICStrdup (resourceUri);
1434 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1436 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1437 // Add the destination to route option from the endpoint->routeData.
1438 OCStackResult result = RMAddInfo(endPoint->routeData,
1439 &(respInfo.info.options),
1440 &(respInfo.info.numOptions));
1441 if(OC_STACK_OK != result)
1443 OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1448 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1450 // resourceUri in the info field is cloned in the CA layer and
1451 // thus ownership is still here.
1452 OICFree (respInfo.info.resourceUri);
1453 OICFree (respInfo.info.options);
1454 if(CA_STATUS_OK != caResult)
1456 OC_LOG(ERROR, TAG, "CASendResponse error");
1457 return CAResultToOCResult(caResult);
1462 //This function will be called back by CA layer when a request is received
1463 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1465 OC_LOG(INFO, TAG, "Enter HandleCARequests");
1468 OC_LOG(ERROR, TAG, "endPoint is NULL");
1474 OC_LOG(ERROR, TAG, "requestInfo is NULL");
1478 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1479 #ifdef ROUTING_GATEWAY
1480 bool needRIHandling = false;
1482 * Routing manager is going to update either of endpoint or request or both.
1483 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1484 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1485 * destination. It can also remove "RM" coap header option before passing request / response to
1486 * RI as this option will make no sense to either RI or application.
1488 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1490 if(OC_STACK_OK != ret || !needRIHandling)
1492 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1498 * Put source in sender endpoint so that the next packet from application can be routed to
1499 * proper destination and remove RM header option.
1501 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1502 (uint8_t *) &(requestInfo->info.numOptions),
1503 (CAEndpoint_t *) endPoint);
1506 OCStackResult requestResult = OC_STACK_ERROR;
1508 if(myStackMode == OC_CLIENT)
1510 //TODO: should the client be responding to requests?
1514 OCServerProtocolRequest serverRequest = {0};
1516 OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1518 char * uriWithoutQuery = NULL;
1519 char * query = NULL;
1521 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1523 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1525 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1528 OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1529 OC_LOG_V(INFO, TAG, "Query : %s", query);
1531 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1533 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1534 OICFree(uriWithoutQuery);
1538 OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1539 OICFree(uriWithoutQuery);
1546 if(strlen(query) < MAX_QUERY_LENGTH)
1548 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1553 OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1559 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1561 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1562 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1563 memcpy (serverRequest.payload, requestInfo->info.payload,
1564 requestInfo->info.payloadSize);
1568 serverRequest.reqTotalSize = 0;
1571 switch (requestInfo->method)
1574 serverRequest.method = OC_REST_GET;
1577 serverRequest.method = OC_REST_PUT;
1580 serverRequest.method = OC_REST_POST;
1583 serverRequest.method = OC_REST_DELETE;
1586 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1587 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1588 requestInfo->info.type, requestInfo->info.numOptions,
1589 requestInfo->info.options, requestInfo->info.token,
1590 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1591 OICFree(serverRequest.payload);
1595 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1596 requestInfo->info.tokenLength);
1597 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1598 serverRequest.tokenLength = requestInfo->info.tokenLength;
1600 if (!serverRequest.requestToken)
1602 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1603 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1604 requestInfo->info.type, requestInfo->info.numOptions,
1605 requestInfo->info.options, requestInfo->info.token,
1606 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1607 OICFree(serverRequest.payload);
1610 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1612 switch (requestInfo->info.acceptFormat)
1614 case CA_FORMAT_APPLICATION_CBOR:
1615 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1617 case CA_FORMAT_UNDEFINED:
1618 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1621 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1624 if (requestInfo->info.type == CA_MSG_CONFIRM)
1626 serverRequest.qos = OC_HIGH_QOS;
1630 serverRequest.qos = OC_LOW_QOS;
1632 // CA does not need the following field
1633 // Are we sure CA does not need them? how is it responding to multicast
1634 serverRequest.delayedResNeeded = 0;
1636 serverRequest.coapID = requestInfo->info.messageId;
1638 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1640 // copy vendor specific header options
1641 uint8_t tempNum = (requestInfo->info.numOptions);
1643 // Assume no observation requested and it is a pure GET.
1644 // If obs registration/de-registration requested it'll be fetched from the
1645 // options in GetObserveHeaderOption()
1646 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1648 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1649 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1652 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1653 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1654 requestInfo->info.type, requestInfo->info.numOptions,
1655 requestInfo->info.options, requestInfo->info.token,
1656 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1657 OICFree(serverRequest.payload);
1658 OICFree(serverRequest.requestToken);
1661 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1662 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1664 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1665 sizeof(CAHeaderOption_t)*tempNum);
1668 requestResult = HandleStackRequests (&serverRequest);
1670 // Send ACK to client as precursor to slow response
1671 if(requestResult == OC_STACK_SLOW_RESOURCE)
1673 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1674 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1676 else if(requestResult != OC_STACK_OK)
1678 OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1680 CAResponseResult_t stackResponse =
1681 OCToCAStackResult(requestResult, serverRequest.method);
1683 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1684 requestInfo->info.type, requestInfo->info.numOptions,
1685 requestInfo->info.options, requestInfo->info.token,
1686 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1688 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1689 // The token is copied in there, and is thus still owned by this function.
1690 OICFree(serverRequest.payload);
1691 OICFree(serverRequest.requestToken);
1692 OC_LOG(INFO, TAG, "Exit HandleCARequests");
1695 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1697 OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1698 OCStackResult result = OC_STACK_ERROR;
1699 ResourceHandling resHandling;
1700 OCResource *resource;
1701 if(!protocolRequest)
1703 OC_LOG(ERROR, TAG, "protocolRequest is NULL");
1704 return OC_STACK_INVALID_PARAM;
1707 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1708 protocolRequest->tokenLength);
1711 OC_LOG(INFO, TAG, "This is a new Server Request");
1712 result = AddServerRequest(&request, protocolRequest->coapID,
1713 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1714 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1715 protocolRequest->observationOption, protocolRequest->qos,
1716 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1717 protocolRequest->payload, protocolRequest->requestToken,
1718 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1719 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1720 &protocolRequest->devAddr);
1721 if (OC_STACK_OK != result)
1723 OC_LOG(ERROR, TAG, "Error adding server request");
1729 OC_LOG(ERROR, TAG, "Out of Memory");
1730 return OC_STACK_NO_MEMORY;
1733 if(!protocolRequest->reqMorePacket)
1735 request->requestComplete = 1;
1740 OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1743 if(request->requestComplete)
1745 OC_LOG(INFO, TAG, "This Server Request is complete");
1746 result = DetermineResourceHandling (request, &resHandling, &resource);
1747 if (result == OC_STACK_OK)
1749 result = ProcessRequest(resHandling, resource, request);
1754 OC_LOG(INFO, TAG, "This Server Request is incomplete");
1755 result = OC_STACK_CONTINUE;
1760 bool validatePlatformInfo(OCPlatformInfo info)
1763 if (!info.platformID)
1765 OC_LOG(ERROR, TAG, "No platform ID found.");
1769 if (info.manufacturerName)
1771 size_t lenManufacturerName = strlen(info.manufacturerName);
1773 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1775 OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1781 OC_LOG(ERROR, TAG, "No manufacturer name present");
1785 if (info.manufacturerUrl)
1787 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1789 OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1796 //-----------------------------------------------------------------------------
1798 //-----------------------------------------------------------------------------
1800 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1803 !raInfo->username ||
1804 !raInfo->hostname ||
1805 !raInfo->xmpp_domain)
1808 return OC_STACK_INVALID_PARAM;
1810 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1811 gRASetInfo = (result == OC_STACK_OK)? true : false;
1817 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1821 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1824 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1826 if(stackState == OC_STACK_INITIALIZED)
1828 OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1829 OCStop() between them are ignored.");
1833 #ifndef ROUTING_GATEWAY
1834 if (OC_GATEWAY == mode)
1836 OC_LOG(ERROR, TAG, "Routing Manager not supported");
1837 return OC_STACK_INVALID_PARAM;
1844 OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1845 return OC_STACK_ERROR;
1849 OCStackResult result = OC_STACK_ERROR;
1850 OC_LOG(INFO, TAG, "Entering OCInit");
1853 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1854 || (mode == OC_GATEWAY)))
1856 OC_LOG(ERROR, TAG, "Invalid mode");
1857 return OC_STACK_ERROR;
1861 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1863 caglobals.client = true;
1865 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1867 caglobals.server = true;
1870 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1871 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1873 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1875 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1876 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1878 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1881 defaultDeviceHandler = NULL;
1882 defaultDeviceHandlerCallbackParameter = NULL;
1884 result = CAResultToOCResult(CAInitialize());
1885 VERIFY_SUCCESS(result, OC_STACK_OK);
1887 result = CAResultToOCResult(OCSelectNetwork());
1888 VERIFY_SUCCESS(result, OC_STACK_OK);
1890 switch (myStackMode)
1893 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1894 result = CAResultToOCResult(CAStartDiscoveryServer());
1895 OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1898 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1899 result = CAResultToOCResult(CAStartListeningServer());
1900 OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1902 case OC_CLIENT_SERVER:
1904 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1905 result = CAResultToOCResult(CAStartListeningServer());
1906 if(result == OC_STACK_OK)
1908 result = CAResultToOCResult(CAStartDiscoveryServer());
1912 VERIFY_SUCCESS(result, OC_STACK_OK);
1914 #ifdef WITH_PRESENCE
1915 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1916 #endif // WITH_PRESENCE
1918 //Update Stack state to initialized
1919 stackState = OC_STACK_INITIALIZED;
1921 // Initialize resource
1922 if(myStackMode != OC_CLIENT)
1924 result = initResources();
1927 // Initialize the SRM Policy Engine
1928 if(result == OC_STACK_OK)
1930 result = SRMInitPolicyEngine();
1931 // TODO after BeachHead delivery: consolidate into single SRMInit()
1934 #ifdef ROUTING_GATEWAY
1935 if (OC_GATEWAY == myStackMode)
1937 result = RMInitialize();
1942 if(result != OC_STACK_OK)
1944 OC_LOG(ERROR, TAG, "Stack initialization error");
1945 deleteAllResources();
1947 stackState = OC_STACK_UNINITIALIZED;
1952 OCStackResult OCStop()
1954 OC_LOG(INFO, TAG, "Entering OCStop");
1956 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1958 OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1961 else if (stackState != OC_STACK_INITIALIZED)
1963 OC_LOG(ERROR, TAG, "Stack not initialized");
1964 return OC_STACK_ERROR;
1967 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1969 #ifdef WITH_PRESENCE
1970 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1971 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1972 presenceResource.presenceTTL = 0;
1973 #endif // WITH_PRESENCE
1975 #ifdef ROUTING_GATEWAY
1976 if (OC_GATEWAY == myStackMode)
1982 // Free memory dynamically allocated for resources
1983 deleteAllResources();
1985 DeletePlatformInfo();
1987 // Remove all observers
1988 DeleteObserverList();
1989 // Remove all the client callbacks
1990 DeleteClientCBList();
1992 // De-init the SRM Policy Engine
1993 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1994 SRMDeInitPolicyEngine();
1997 stackState = OC_STACK_UNINITIALIZED;
2001 OCStackResult OCStartMulticastServer()
2003 if(stackState != OC_STACK_INITIALIZED)
2005 OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2006 return OC_STACK_ERROR;
2008 CAResult_t ret = CAStartListeningServer();
2009 if (CA_STATUS_OK != ret)
2011 OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2012 return OC_STACK_ERROR;
2017 OCStackResult OCStopMulticastServer()
2019 CAResult_t ret = CAStopListeningServer();
2020 if (CA_STATUS_OK != ret)
2022 OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2023 return OC_STACK_ERROR;
2028 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2033 return CA_MSG_CONFIRM;
2038 return CA_MSG_NONCONFIRM;
2042 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2046 query = strchr (inputUri, '?');
2050 if((query - inputUri) > MAX_URI_LENGTH)
2052 return OC_STACK_INVALID_URI;
2055 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2057 return OC_STACK_INVALID_QUERY;
2060 else if(uriLen > MAX_URI_LENGTH)
2062 return OC_STACK_INVALID_URI;
2068 * A request uri consists of the following components in order:
2071 * CoAP over UDP prefix "coap://"
2072 * CoAP over TCP prefix "coap+tcp://"
2074 * IPv6 address "[1234::5678]"
2075 * IPv4 address "192.168.1.1"
2076 * optional port ":5683"
2077 * resource uri "/oc/core..."
2079 * for PRESENCE requests, extract resource type.
2081 static OCStackResult ParseRequestUri(const char *fullUri,
2082 OCTransportAdapter adapter,
2083 OCTransportFlags flags,
2084 OCDevAddr **devAddr,
2086 char **resourceType)
2088 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2090 OCStackResult result = OC_STACK_OK;
2091 OCDevAddr *da = NULL;
2095 // provide defaults for all returned values
2102 *resourceUri = NULL;
2106 *resourceType = NULL;
2109 // delimit url prefix, if any
2110 const char *start = fullUri;
2111 char *slash2 = strstr(start, "//");
2116 char *slash = strchr(start, '/');
2119 return OC_STACK_INVALID_URI;
2122 // process url scheme
2123 size_t prefixLen = slash2 - fullUri;
2127 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2133 // TODO: this logic should come in with unit tests exercising the various strings
2134 // processs url prefix, if any
2135 size_t urlLen = slash - start;
2139 if (urlLen && devAddr)
2140 { // construct OCDevAddr
2141 if (start[0] == '[')
2143 char *close = strchr(++start, ']');
2144 if (!close || close > slash)
2146 return OC_STACK_INVALID_URI;
2149 if (close[1] == ':')
2153 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2154 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2158 char *dot = strchr(start, '.');
2159 if (dot && dot < slash)
2161 colon = strchr(start, ':');
2162 end = (colon && colon < slash) ? colon : slash;
2166 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2170 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2171 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2180 if (len >= sizeof(da->addr))
2182 return OC_STACK_INVALID_URI;
2184 // collect port, if any
2185 if (colon && colon < slash)
2187 for (colon++; colon < slash; colon++)
2190 if (c < '0' || c > '9')
2192 return OC_STACK_INVALID_URI;
2194 port = 10 * port + c - '0';
2199 if (len >= sizeof(da->addr))
2201 return OC_STACK_INVALID_URI;
2204 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2207 return OC_STACK_NO_MEMORY;
2209 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2211 da->adapter = adapter;
2213 if (!strncmp(fullUri, "coaps:", 6))
2215 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2220 // process resource uri, if any
2222 { // request uri and query
2223 size_t ulen = strlen(slash); // resource uri length
2224 size_t tlen = 0; // resource type length
2227 static const char strPresence[] = "/oic/ad?rt=";
2228 static const size_t lenPresence = sizeof(strPresence) - 1;
2229 if (!strncmp(slash, strPresence, lenPresence))
2231 type = slash + lenPresence;
2232 tlen = ulen - lenPresence;
2237 *resourceUri = (char *)OICMalloc(ulen + 1);
2240 result = OC_STACK_NO_MEMORY;
2243 strcpy(*resourceUri, slash);
2246 if (type && resourceType)
2248 *resourceType = (char *)OICMalloc(tlen + 1);
2251 result = OC_STACK_NO_MEMORY;
2255 OICStrcpy(*resourceType, (tlen+1), type);
2262 // free all returned values
2269 OICFree(*resourceUri);
2273 OICFree(*resourceType);
2278 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2279 char *resourceUri, char **requestUri)
2281 char uri[CA_MAX_URI_LENGTH];
2283 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2285 *requestUri = OICStrdup(uri);
2288 return OC_STACK_NO_MEMORY;
2295 * Discover or Perform requests on a specified resource
2297 OCStackResult OCDoResource(OCDoHandle *handle,
2299 const char *requestUri,
2300 const OCDevAddr *destination,
2302 OCConnectivityType connectivityType,
2303 OCQualityOfService qos,
2304 OCCallbackData *cbData,
2305 OCHeaderOption *options,
2308 OC_LOG(INFO, TAG, "Entering OCDoResource");
2310 // Validate input parameters
2311 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2312 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2313 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2315 OCStackResult result = OC_STACK_ERROR;
2316 CAResult_t caResult;
2317 CAToken_t token = NULL;
2318 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2319 ClientCB *clientCB = NULL;
2320 OCDoHandle resHandle = NULL;
2321 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2322 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2324 OCTransportAdapter adapter;
2325 OCTransportFlags flags;
2326 // the request contents are put here
2327 CARequestInfo_t requestInfo = {.method = CA_GET};
2328 // requestUri will be parsed into the following three variables
2329 OCDevAddr *devAddr = NULL;
2330 char *resourceUri = NULL;
2331 char *resourceType = NULL;
2333 // This validation is broken, but doesn't cause harm
2334 size_t uriLen = strlen(requestUri );
2335 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2341 * Support original behavior with address on resourceUri argument.
2343 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2344 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2346 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2348 if (result != OC_STACK_OK)
2350 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2357 case OC_REST_OBSERVE:
2358 case OC_REST_OBSERVE_ALL:
2359 case OC_REST_CANCEL_OBSERVE:
2360 requestInfo.method = CA_GET;
2363 requestInfo.method = CA_PUT;
2366 requestInfo.method = CA_POST;
2368 case OC_REST_DELETE:
2369 requestInfo.method = CA_DELETE;
2371 case OC_REST_DISCOVER:
2373 if (destination || devAddr)
2375 requestInfo.isMulticast = false;
2379 tmpDevAddr.adapter = adapter;
2380 tmpDevAddr.flags = flags;
2381 destination = &tmpDevAddr;
2382 requestInfo.isMulticast = true;
2384 // CA_DISCOVER will become GET and isMulticast
2385 requestInfo.method = CA_GET;
2387 #ifdef WITH_PRESENCE
2388 case OC_REST_PRESENCE:
2389 // Replacing method type with GET because "presence"
2390 // is a stack layer only implementation.
2391 requestInfo.method = CA_GET;
2395 result = OC_STACK_INVALID_METHOD;
2399 if (!devAddr && !destination)
2401 OC_LOG(DEBUG, TAG, "no devAddr and no destination");
2402 result = OC_STACK_INVALID_PARAM;
2406 /* If not original behavior, use destination argument */
2407 if (destination && !devAddr)
2409 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2412 result = OC_STACK_NO_MEMORY;
2415 *devAddr = *destination;
2418 resHandle = GenerateInvocationHandle();
2421 result = OC_STACK_NO_MEMORY;
2425 caResult = CAGenerateToken(&token, tokenLength);
2426 if (caResult != CA_STATUS_OK)
2428 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2429 result= OC_STACK_ERROR;
2433 // fill in request data
2434 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2435 requestInfo.info.token = token;
2436 requestInfo.info.tokenLength = tokenLength;
2437 requestInfo.info.resourceUri = resourceUri;
2439 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2441 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2442 options, numOptions, OC_OBSERVE_REGISTER);
2443 if (result != OC_STACK_OK)
2447 requestInfo.info.numOptions = numOptions + 1;
2451 requestInfo.info.numOptions = numOptions;
2452 requestInfo.info.options =
2453 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2454 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2455 numOptions * sizeof(CAHeaderOption_t));
2458 CopyDevAddrToEndpoint(devAddr, &endpoint);
2463 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2466 OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2469 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2473 requestInfo.info.payload = NULL;
2474 requestInfo.info.payloadSize = 0;
2475 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2478 if (result != OC_STACK_OK)
2480 OC_LOG(ERROR, TAG, "CACreateEndpoint error");
2484 // prepare for response
2485 #ifdef WITH_PRESENCE
2486 if (method == OC_REST_PRESENCE)
2488 char *presenceUri = NULL;
2489 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2490 if (OC_STACK_OK != result)
2495 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2496 // Presence notification will form a canonical uri to
2497 // look for callbacks into the application.
2498 resourceUri = presenceUri;
2502 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2503 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2504 method, devAddr, resourceUri, resourceType, ttl);
2505 if (OC_STACK_OK != result)
2510 devAddr = NULL; // Client CB list entry now owns it
2511 resourceUri = NULL; // Client CB list entry now owns it
2512 resourceType = NULL; // Client CB list entry now owns it
2515 result = OCSendRequest(&endpoint, &requestInfo);
2516 if (OC_STACK_OK != result)
2523 *handle = resHandle;
2527 if (result != OC_STACK_OK)
2529 OC_LOG(ERROR, TAG, "OCDoResource error");
2530 FindAndDeleteClientCB(clientCB);
2531 CADestroyToken(token);
2539 // This is the owner of the payload object, so we free it
2540 OCPayloadDestroy(payload);
2541 OICFree(requestInfo.info.payload);
2543 OICFree(resourceUri);
2544 OICFree(resourceType);
2545 OICFree(requestInfo.info.options);
2549 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2553 * This ftn is implemented one of two ways in the case of observation:
2555 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2556 * Remove the callback associated on client side.
2557 * When the next notification comes in from server,
2558 * reply with RESET message to server.
2559 * Keep in mind that the server will react to RESET only
2560 * if the last notification was sent as CON
2562 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2563 * and it is associated with an observe request
2564 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2565 * Send CON Observe request to server with
2566 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2567 * Remove the callback associated on client side.
2569 OCStackResult ret = OC_STACK_OK;
2570 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2571 CARequestInfo_t requestInfo = {.method = CA_GET};
2575 return OC_STACK_INVALID_PARAM;
2578 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2581 OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2582 return OC_STACK_ERROR;
2585 switch (clientCB->method)
2587 case OC_REST_OBSERVE:
2588 case OC_REST_OBSERVE_ALL:
2590 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2591 clientCB->requestUri);
2592 if (qos != OC_HIGH_QOS)
2594 FindAndDeleteClientCB(clientCB);
2598 OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2600 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2601 requestInfo.info.token = clientCB->token;
2602 requestInfo.info.tokenLength = clientCB->tokenLength;
2604 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2605 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2607 return OC_STACK_ERROR;
2609 requestInfo.info.numOptions = numOptions + 1;
2610 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2612 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2614 ret = OCSendRequest(&endpoint, &requestInfo);
2616 if (requestInfo.info.options)
2618 OICFree (requestInfo.info.options);
2620 if (requestInfo.info.resourceUri)
2622 OICFree (requestInfo.info.resourceUri);
2627 case OC_REST_DISCOVER:
2628 OC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2629 clientCB->requestUri);
2630 FindAndDeleteClientCB(clientCB);
2633 #ifdef WITH_PRESENCE
2634 case OC_REST_PRESENCE:
2635 FindAndDeleteClientCB(clientCB);
2640 ret = OC_STACK_INVALID_METHOD;
2648 * @brief Register Persistent storage callback.
2649 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2651 * OC_STACK_OK - No errors; Success
2652 * OC_STACK_INVALID_PARAM - Invalid parameter
2654 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2656 OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2657 if(!persistentStorageHandler)
2659 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2660 return OC_STACK_INVALID_PARAM;
2664 if( !persistentStorageHandler->open ||
2665 !persistentStorageHandler->close ||
2666 !persistentStorageHandler->read ||
2667 !persistentStorageHandler->unlink ||
2668 !persistentStorageHandler->write)
2670 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2671 return OC_STACK_INVALID_PARAM;
2674 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2677 #ifdef WITH_PRESENCE
2679 OCStackResult OCProcessPresence()
2681 OCStackResult result = OC_STACK_OK;
2683 // the following line floods the log with messages that are irrelevant
2684 // to most purposes. Uncomment as needed.
2685 //OC_LOG(INFO, TAG, "Entering RequestPresence");
2686 ClientCB* cbNode = NULL;
2687 OCClientResponse clientResponse;
2688 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2690 LL_FOREACH(cbList, cbNode)
2692 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2697 uint32_t now = GetTicks(0);
2698 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2699 cbNode->presence->TTLlevel);
2700 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2702 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2707 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2709 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2710 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2712 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2714 OC_LOG(DEBUG, TAG, "No more timeout ticks");
2716 clientResponse.sequenceNumber = 0;
2717 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2718 clientResponse.devAddr = *cbNode->devAddr;
2719 FixUpClientResponse(&clientResponse);
2720 clientResponse.payload = NULL;
2722 // Increment the TTLLevel (going to a next state), so we don't keep
2723 // sending presence notification to client.
2724 cbNode->presence->TTLlevel++;
2725 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2726 cbNode->presence->TTLlevel);
2728 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2729 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2731 FindAndDeleteClientCB(cbNode);
2735 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2740 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2741 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2742 CARequestInfo_t requestInfo = {.method = CA_GET};
2744 OC_LOG(DEBUG, TAG, "time to test server presence");
2746 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2748 requestData.type = CA_MSG_NONCONFIRM;
2749 requestData.token = cbNode->token;
2750 requestData.tokenLength = cbNode->tokenLength;
2751 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2752 requestInfo.method = CA_GET;
2753 requestInfo.info = requestData;
2755 result = OCSendRequest(&endpoint, &requestInfo);
2756 if (OC_STACK_OK != result)
2761 cbNode->presence->TTLlevel++;
2762 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2765 if (result != OC_STACK_OK)
2767 OC_LOG(ERROR, TAG, "OCProcessPresence error");
2772 #endif // WITH_PRESENCE
2774 OCStackResult OCProcess()
2776 #ifdef WITH_PRESENCE
2777 OCProcessPresence();
2779 CAHandleRequestResponse();
2781 #ifdef ROUTING_GATEWAY
2787 #ifdef WITH_PRESENCE
2788 OCStackResult OCStartPresence(const uint32_t ttl)
2790 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2791 OCChangeResourceProperty(
2792 &(((OCResource *)presenceResource.handle)->resourceProperties),
2795 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2797 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2798 OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2802 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2803 OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2807 presenceResource.presenceTTL = ttl;
2809 OC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2811 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2813 presenceState = OC_PRESENCE_INITIALIZED;
2815 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2817 CAToken_t caToken = NULL;
2818 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2819 if (caResult != CA_STATUS_OK)
2821 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2822 CADestroyToken(caToken);
2823 return OC_STACK_ERROR;
2826 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2827 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2828 CADestroyToken(caToken);
2831 // Each time OCStartPresence is called
2832 // a different random 32-bit integer number is used
2833 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2835 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2836 OC_PRESENCE_TRIGGER_CREATE);
2839 OCStackResult OCStopPresence()
2841 OCStackResult result = OC_STACK_ERROR;
2843 if(presenceResource.handle)
2845 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2847 // make resource inactive
2848 result = OCChangeResourceProperty(
2849 &(((OCResource *) presenceResource.handle)->resourceProperties),
2853 if(result != OC_STACK_OK)
2856 "Changing the presence resource properties to ACTIVE not successful");
2860 return SendStopNotification();
2864 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2865 void* callbackParameter)
2867 defaultDeviceHandler = entityHandler;
2868 defaultDeviceHandlerCallbackParameter = callbackParameter;
2873 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2875 OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2877 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2879 if (validatePlatformInfo(platformInfo))
2881 return SavePlatformInfo(platformInfo);
2885 return OC_STACK_INVALID_PARAM;
2890 return OC_STACK_ERROR;
2894 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2896 OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2898 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2900 OC_LOG(ERROR, TAG, "Null or empty device name.");
2901 return OC_STACK_INVALID_PARAM;
2904 return SaveDeviceInfo(deviceInfo);
2907 OCStackResult OCCreateResource(OCResourceHandle *handle,
2908 const char *resourceTypeName,
2909 const char *resourceInterfaceName,
2910 const char *uri, OCEntityHandler entityHandler,
2911 void* callbackParam,
2912 uint8_t resourceProperties)
2915 OCResource *pointer = NULL;
2916 OCStackResult result = OC_STACK_ERROR;
2918 OC_LOG(INFO, TAG, "Entering OCCreateResource");
2920 if(myStackMode == OC_CLIENT)
2922 return OC_STACK_INVALID_PARAM;
2924 // Validate parameters
2925 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2927 OC_LOG(ERROR, TAG, "URI is empty or too long");
2928 return OC_STACK_INVALID_URI;
2930 // Is it presented during resource discovery?
2931 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2933 OC_LOG(ERROR, TAG, "Input parameter is NULL");
2934 return OC_STACK_INVALID_PARAM;
2937 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2939 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2942 // Make sure resourceProperties bitmask has allowed properties specified
2943 if (resourceProperties
2944 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2945 OC_EXPLICIT_DISCOVERABLE))
2947 OC_LOG(ERROR, TAG, "Invalid property");
2948 return OC_STACK_INVALID_PARAM;
2951 // If the headResource is NULL, then no resources have been created...
2952 pointer = headResource;
2955 // At least one resources is in the resource list, so we need to search for
2956 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2959 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2961 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2962 return OC_STACK_INVALID_PARAM;
2964 pointer = pointer->next;
2967 // Create the pointer and insert it into the resource list
2968 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2971 result = OC_STACK_NO_MEMORY;
2974 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2976 insertResource(pointer);
2979 pointer->uri = OICStrdup(uri);
2982 result = OC_STACK_NO_MEMORY;
2986 // Set properties. Set OC_ACTIVE
2987 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2990 // Add the resourcetype to the resource
2991 result = BindResourceTypeToResource(pointer, resourceTypeName);
2992 if (result != OC_STACK_OK)
2994 OC_LOG(ERROR, TAG, "Error adding resourcetype");
2998 // Add the resourceinterface to the resource
2999 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3000 if (result != OC_STACK_OK)
3002 OC_LOG(ERROR, TAG, "Error adding resourceinterface");
3006 // If an entity handler has been passed, attach it to the newly created
3007 // resource. Otherwise, set the default entity handler.
3010 pointer->entityHandler = entityHandler;
3011 pointer->entityHandlerCallbackParam = callbackParam;
3015 pointer->entityHandler = defaultResourceEHandler;
3016 pointer->entityHandlerCallbackParam = NULL;
3020 result = OC_STACK_OK;
3022 #ifdef WITH_PRESENCE
3023 if (presenceResource.handle)
3025 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3026 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3030 if (result != OC_STACK_OK)
3032 // Deep delete of resource and other dynamic elements that it contains
3033 deleteResource(pointer);
3039 OCStackResult OCBindResource(
3040 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3042 OCResource *resource = NULL;
3045 OC_LOG(INFO, TAG, "Entering OCBindResource");
3047 // Validate parameters
3048 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3049 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3050 // Container cannot contain itself
3051 if (collectionHandle == resourceHandle)
3053 OC_LOG(ERROR, TAG, "Added handle equals collection handle");
3054 return OC_STACK_INVALID_PARAM;
3057 // Use the handle to find the resource in the resource linked list
3058 resource = findResource((OCResource *) collectionHandle);
3061 OC_LOG(ERROR, TAG, "Collection handle not found");
3062 return OC_STACK_INVALID_PARAM;
3065 // Look for an open slot to add add the child resource.
3066 // If found, add it and return success
3067 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3069 if (!resource->rsrcResources[i])
3071 resource->rsrcResources[i] = (OCResource *) resourceHandle;
3072 OC_LOG(INFO, TAG, "resource bound");
3074 #ifdef WITH_PRESENCE
3075 if (presenceResource.handle)
3077 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3078 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3079 OC_PRESENCE_TRIGGER_CHANGE);
3087 // Unable to add resourceHandle, so return error
3088 return OC_STACK_ERROR;
3091 OCStackResult OCUnBindResource(
3092 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3094 OCResource *resource = NULL;
3097 OC_LOG(INFO, TAG, "Entering OCUnBindResource");
3099 // Validate parameters
3100 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3101 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3102 // Container cannot contain itself
3103 if (collectionHandle == resourceHandle)
3105 OC_LOG(ERROR, TAG, "removing handle equals collection handle");
3106 return OC_STACK_INVALID_PARAM;
3109 // Use the handle to find the resource in the resource linked list
3110 resource = findResource((OCResource *) collectionHandle);
3113 OC_LOG(ERROR, TAG, "Collection handle not found");
3114 return OC_STACK_INVALID_PARAM;
3117 // Look for an open slot to add add the child resource.
3118 // If found, add it and return success
3119 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3121 if (resourceHandle == resource->rsrcResources[i])
3123 resource->rsrcResources[i] = (OCResource *) NULL;
3124 OC_LOG(INFO, TAG, "resource unbound");
3126 // Send notification when resource is unbounded successfully.
3127 #ifdef WITH_PRESENCE
3128 if (presenceResource.handle)
3130 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3131 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3132 OC_PRESENCE_TRIGGER_CHANGE);
3139 OC_LOG(INFO, TAG, "resource not found in collection");
3141 // Unable to add resourceHandle, so return error
3142 return OC_STACK_ERROR;
3145 // Precondition is that the parameter has been checked to not equal NULL.
3146 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3148 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3154 while (resourceItemName[index] != '\0')
3156 if (resourceItemName[index] != '.' &&
3157 resourceItemName[index] != '-' &&
3158 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3159 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3168 OCStackResult BindResourceTypeToResource(OCResource* resource,
3169 const char *resourceTypeName)
3171 OCResourceType *pointer = NULL;
3173 OCStackResult result = OC_STACK_ERROR;
3175 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3177 if (!ValidateResourceTypeInterface(resourceTypeName))
3179 OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3180 return OC_STACK_INVALID_PARAM;
3183 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3186 result = OC_STACK_NO_MEMORY;
3190 str = OICStrdup(resourceTypeName);
3193 result = OC_STACK_NO_MEMORY;
3196 pointer->resourcetypename = str;
3198 insertResourceType(resource, pointer);
3199 result = OC_STACK_OK;
3202 if (result != OC_STACK_OK)
3211 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3212 const char *resourceInterfaceName)
3214 OCResourceInterface *pointer = NULL;
3216 OCStackResult result = OC_STACK_ERROR;
3218 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3220 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3222 OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3223 return OC_STACK_INVALID_PARAM;
3226 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3228 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3231 result = OC_STACK_NO_MEMORY;
3235 str = OICStrdup(resourceInterfaceName);
3238 result = OC_STACK_NO_MEMORY;
3241 pointer->name = str;
3243 // Bind the resourceinterface to the resource
3244 insertResourceInterface(resource, pointer);
3246 result = OC_STACK_OK;
3249 if (result != OC_STACK_OK)
3258 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3259 const char *resourceTypeName)
3262 OCStackResult result = OC_STACK_ERROR;
3263 OCResource *resource = NULL;
3265 resource = findResource((OCResource *) handle);
3268 OC_LOG(ERROR, TAG, "Resource not found");
3269 return OC_STACK_ERROR;
3272 result = BindResourceTypeToResource(resource, resourceTypeName);
3274 #ifdef WITH_PRESENCE
3275 if(presenceResource.handle)
3277 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3278 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3285 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3286 const char *resourceInterfaceName)
3289 OCStackResult result = OC_STACK_ERROR;
3290 OCResource *resource = NULL;
3292 resource = findResource((OCResource *) handle);
3295 OC_LOG(ERROR, TAG, "Resource not found");
3296 return OC_STACK_ERROR;
3299 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3301 #ifdef WITH_PRESENCE
3302 if (presenceResource.handle)
3304 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3305 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3312 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3314 OCResource *pointer = headResource;
3316 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3320 *numResources = *numResources + 1;
3321 pointer = pointer->next;
3326 OCResourceHandle OCGetResourceHandle(uint8_t index)
3328 OCResource *pointer = headResource;
3330 for( uint8_t i = 0; i < index && pointer; ++i)
3332 pointer = pointer->next;
3334 return (OCResourceHandle) pointer;
3337 OCStackResult OCDeleteResource(OCResourceHandle handle)
3341 OC_LOG(ERROR, TAG, "Invalid handle for deletion");
3342 return OC_STACK_INVALID_PARAM;
3345 OCResource *resource = findResource((OCResource *) handle);
3346 if (resource == NULL)
3348 OC_LOG(ERROR, TAG, "Resource not found");
3349 return OC_STACK_NO_RESOURCE;
3352 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3354 OC_LOG(ERROR, TAG, "Error deleting resource");
3355 return OC_STACK_ERROR;
3361 const char *OCGetResourceUri(OCResourceHandle handle)
3363 OCResource *resource = NULL;
3365 resource = findResource((OCResource *) handle);
3368 return resource->uri;
3370 return (const char *) NULL;
3373 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3375 OCResource *resource = NULL;
3377 resource = findResource((OCResource *) handle);
3380 return resource->resourceProperties;
3382 return (OCResourceProperty)-1;
3385 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3386 uint8_t *numResourceTypes)
3388 OCResource *resource = NULL;
3389 OCResourceType *pointer = NULL;
3391 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3392 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3394 *numResourceTypes = 0;
3396 resource = findResource((OCResource *) handle);
3399 pointer = resource->rsrcType;
3402 *numResourceTypes = *numResourceTypes + 1;
3403 pointer = pointer->next;
3409 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3411 OCResourceType *resourceType = NULL;
3413 resourceType = findResourceTypeAtIndex(handle, index);
3416 return resourceType->resourcetypename;
3418 return (const char *) NULL;
3421 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3422 uint8_t *numResourceInterfaces)
3424 OCResourceInterface *pointer = NULL;
3425 OCResource *resource = NULL;
3427 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3428 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3430 *numResourceInterfaces = 0;
3431 resource = findResource((OCResource *) handle);
3434 pointer = resource->rsrcInterface;
3437 *numResourceInterfaces = *numResourceInterfaces + 1;
3438 pointer = pointer->next;
3444 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3446 OCResourceInterface *resourceInterface = NULL;
3448 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3449 if (resourceInterface)
3451 return resourceInterface->name;
3453 return (const char *) NULL;
3456 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3459 OCResource *resource = NULL;
3461 if (index >= MAX_CONTAINED_RESOURCES)
3466 resource = findResource((OCResource *) collectionHandle);
3472 return resource->rsrcResources[index];
3475 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3476 OCEntityHandler entityHandler,
3477 void* callbackParam)
3479 OCResource *resource = NULL;
3481 // Validate parameters
3482 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3484 // Use the handle to find the resource in the resource linked list
3485 resource = findResource((OCResource *)handle);
3488 OC_LOG(ERROR, TAG, "Resource not found");
3489 return OC_STACK_ERROR;
3493 resource->entityHandler = entityHandler;
3494 resource->entityHandlerCallbackParam = callbackParam;
3496 #ifdef WITH_PRESENCE
3497 if (presenceResource.handle)
3499 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3500 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3507 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3509 OCResource *resource = NULL;
3511 resource = findResource((OCResource *)handle);
3514 OC_LOG(ERROR, TAG, "Resource not found");
3519 return resource->entityHandler;
3522 void incrementSequenceNumber(OCResource * resPtr)
3524 // Increment the sequence number
3525 resPtr->sequenceNum += 1;
3526 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3528 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3533 #ifdef WITH_PRESENCE
3534 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3535 OCPresenceTrigger trigger)
3537 OCResource *resPtr = NULL;
3538 OCStackResult result = OC_STACK_ERROR;
3539 OCMethod method = OC_REST_PRESENCE;
3540 uint32_t maxAge = 0;
3541 resPtr = findResource((OCResource *) presenceResource.handle);
3544 return OC_STACK_NO_RESOURCE;
3547 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3549 maxAge = presenceResource.presenceTTL;
3551 result = SendAllObserverNotification(method, resPtr, maxAge,
3552 trigger, resourceType, OC_LOW_QOS);
3558 OCStackResult SendStopNotification()
3560 OCResource *resPtr = NULL;
3561 OCStackResult result = OC_STACK_ERROR;
3562 OCMethod method = OC_REST_PRESENCE;
3563 resPtr = findResource((OCResource *) presenceResource.handle);
3566 return OC_STACK_NO_RESOURCE;
3569 // maxAge is 0. ResourceType is NULL.
3570 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3576 #endif // WITH_PRESENCE
3577 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3579 OCResource *resPtr = NULL;
3580 OCStackResult result = OC_STACK_ERROR;
3581 OCMethod method = OC_REST_NOMETHOD;
3582 uint32_t maxAge = 0;
3584 OC_LOG(INFO, TAG, "Notifying all observers");
3585 #ifdef WITH_PRESENCE
3586 if(handle == presenceResource.handle)
3590 #endif // WITH_PRESENCE
3591 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3593 // Verify that the resource exists
3594 resPtr = findResource ((OCResource *) handle);
3597 return OC_STACK_NO_RESOURCE;
3601 //only increment in the case of regular observing (not presence)
3602 incrementSequenceNumber(resPtr);
3603 method = OC_REST_OBSERVE;
3604 maxAge = MAX_OBSERVE_AGE;
3605 #ifdef WITH_PRESENCE
3606 result = SendAllObserverNotification (method, resPtr, maxAge,
3607 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3609 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3616 OCNotifyListOfObservers (OCResourceHandle handle,
3617 OCObservationId *obsIdList,
3618 uint8_t numberOfIds,
3619 const OCRepPayload *payload,
3620 OCQualityOfService qos)
3622 OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3624 OCResource *resPtr = NULL;
3625 //TODO: we should allow the server to define this
3626 uint32_t maxAge = MAX_OBSERVE_AGE;
3628 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3629 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3630 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3632 resPtr = findResource ((OCResource *) handle);
3633 if (NULL == resPtr || myStackMode == OC_CLIENT)
3635 return OC_STACK_NO_RESOURCE;
3639 incrementSequenceNumber(resPtr);
3641 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3642 payload, maxAge, qos));
3645 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3647 OCStackResult result = OC_STACK_ERROR;
3648 OCServerRequest *serverRequest = NULL;
3650 OC_LOG(INFO, TAG, "Entering OCDoResponse");
3652 // Validate input parameters
3653 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3654 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3657 // Get pointer to request info
3658 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3661 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3662 result = serverRequest->ehResponseHandler(ehResponse);
3668 //-----------------------------------------------------------------------------
3669 // Private internal function definitions
3670 //-----------------------------------------------------------------------------
3671 static OCDoHandle GenerateInvocationHandle()
3673 OCDoHandle handle = NULL;
3674 // Generate token here, it will be deleted when the transaction is deleted
3675 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3678 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3684 #ifdef WITH_PRESENCE
3685 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3686 OCResourceProperty resourceProperties, uint8_t enable)
3690 return OC_STACK_INVALID_PARAM;
3692 if (resourceProperties
3693 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3695 OC_LOG(ERROR, TAG, "Invalid property");
3696 return OC_STACK_INVALID_PARAM;
3700 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3704 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3710 OCStackResult initResources()
3712 OCStackResult result = OC_STACK_OK;
3714 headResource = NULL;
3715 tailResource = NULL;
3716 // Init Virtual Resources
3717 #ifdef WITH_PRESENCE
3718 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3720 result = OCCreateResource(&presenceResource.handle,
3721 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3723 OC_RSRVD_PRESENCE_URI,
3727 //make resource inactive
3728 result = OCChangeResourceProperty(
3729 &(((OCResource *) presenceResource.handle)->resourceProperties),
3733 if (result == OC_STACK_OK)
3735 result = SRMInitSecureResources();
3741 void insertResource(OCResource *resource)
3745 headResource = resource;
3746 tailResource = resource;
3750 tailResource->next = resource;
3751 tailResource = resource;
3753 resource->next = NULL;
3756 OCResource *findResource(OCResource *resource)
3758 OCResource *pointer = headResource;
3762 if (pointer == resource)
3766 pointer = pointer->next;
3771 void deleteAllResources()
3773 OCResource *pointer = headResource;
3774 OCResource *temp = NULL;
3778 temp = pointer->next;
3779 #ifdef WITH_PRESENCE
3780 if (pointer != (OCResource *) presenceResource.handle)
3782 #endif // WITH_PRESENCE
3783 deleteResource(pointer);
3784 #ifdef WITH_PRESENCE
3786 #endif // WITH_PRESENCE
3790 SRMDeInitSecureResources();
3792 #ifdef WITH_PRESENCE
3793 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3794 // presence notification attributed to their deletion to be processed.
3795 deleteResource((OCResource *) presenceResource.handle);
3796 #endif // WITH_PRESENCE
3799 OCStackResult deleteResource(OCResource *resource)
3801 OCResource *prev = NULL;
3802 OCResource *temp = NULL;
3805 OC_LOG(DEBUG,TAG,"resource is NULL");
3806 return OC_STACK_INVALID_PARAM;
3809 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3811 temp = headResource;
3814 if (temp == resource)
3816 // Invalidate all Resource Properties.
3817 resource->resourceProperties = (OCResourceProperty) 0;
3818 #ifdef WITH_PRESENCE
3819 if(resource != (OCResource *) presenceResource.handle)
3821 #endif // WITH_PRESENCE
3822 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3823 #ifdef WITH_PRESENCE
3826 if(presenceResource.handle)
3828 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3829 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3832 // Only resource in list.
3833 if (temp == headResource && temp == tailResource)
3835 headResource = NULL;
3836 tailResource = NULL;
3839 else if (temp == headResource)
3841 headResource = temp->next;
3844 else if (temp == tailResource)
3846 tailResource = prev;
3847 tailResource->next = NULL;
3851 prev->next = temp->next;
3854 deleteResourceElements(temp);
3865 return OC_STACK_ERROR;
3868 void deleteResourceElements(OCResource *resource)
3875 OICFree(resource->uri);
3876 deleteResourceType(resource->rsrcType);
3877 deleteResourceInterface(resource->rsrcInterface);
3880 void deleteResourceType(OCResourceType *resourceType)
3882 OCResourceType *pointer = resourceType;
3883 OCResourceType *next = NULL;
3887 next = pointer->next;
3888 OICFree(pointer->resourcetypename);
3894 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3896 OCResourceInterface *pointer = resourceInterface;
3897 OCResourceInterface *next = NULL;
3901 next = pointer->next;
3902 OICFree(pointer->name);
3908 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3910 OCResourceType *pointer = NULL;
3911 OCResourceType *previous = NULL;
3912 if (!resource || !resourceType)
3916 // resource type list is empty.
3917 else if (!resource->rsrcType)
3919 resource->rsrcType = resourceType;
3923 pointer = resource->rsrcType;
3927 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3929 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3930 OICFree(resourceType->resourcetypename);
3931 OICFree(resourceType);
3935 pointer = pointer->next;
3937 previous->next = resourceType;
3939 resourceType->next = NULL;
3941 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3944 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3946 OCResource *resource = NULL;
3947 OCResourceType *pointer = NULL;
3949 // Find the specified resource
3950 resource = findResource((OCResource *) handle);
3956 // Make sure a resource has a resourcetype
3957 if (!resource->rsrcType)
3962 // Iterate through the list
3963 pointer = resource->rsrcType;
3964 for(uint8_t i = 0; i< index && pointer; ++i)
3966 pointer = pointer->next;
3971 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3973 if(resourceTypeList && resourceTypeName)
3975 OCResourceType * rtPointer = resourceTypeList;
3976 while(resourceTypeName && rtPointer)
3978 if(rtPointer->resourcetypename &&
3979 strcmp(resourceTypeName, (const char *)
3980 (rtPointer->resourcetypename)) == 0)
3984 rtPointer = rtPointer->next;
3992 * Insert a new interface into interface linked list only if not already present.
3993 * If alredy present, 2nd arg is free'd.
3994 * Default interface will always be first if present.
3996 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
3998 OCResourceInterface *pointer = NULL;
3999 OCResourceInterface *previous = NULL;
4001 newInterface->next = NULL;
4003 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4005 if (!*firstInterface)
4007 *firstInterface = newInterface;
4009 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4011 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4013 OICFree(newInterface->name);
4014 OICFree(newInterface);
4019 newInterface->next = *firstInterface;
4020 *firstInterface = newInterface;
4025 pointer = *firstInterface;
4028 if (strcmp(newInterface->name, pointer->name) == 0)
4030 OICFree(newInterface->name);
4031 OICFree(newInterface);
4035 pointer = pointer->next;
4037 previous->next = newInterface;
4041 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4044 OCResource *resource = NULL;
4045 OCResourceInterface *pointer = NULL;
4047 // Find the specified resource
4048 resource = findResource((OCResource *) handle);
4054 // Make sure a resource has a resourceinterface
4055 if (!resource->rsrcInterface)
4060 // Iterate through the list
4061 pointer = resource->rsrcInterface;
4063 for (uint8_t i = 0; i < index && pointer; ++i)
4065 pointer = pointer->next;
4071 * This function splits the uri using the '?' delimiter.
4072 * "uriWithoutQuery" is the block of characters between the beginning
4073 * till the delimiter or '\0' which ever comes first.
4074 * "query" is whatever is to the right of the delimiter if present.
4075 * No delimiter sets the query to NULL.
4076 * If either are present, they will be malloc'ed into the params 2, 3.
4077 * The first param, *uri is left untouched.
4079 * NOTE: This function does not account for whitespace at the end of the uri NOR
4080 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4081 * part of the query.
4083 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4087 return OC_STACK_INVALID_URI;
4089 if(!query || !uriWithoutQuery)
4091 return OC_STACK_INVALID_PARAM;
4095 *uriWithoutQuery = NULL;
4097 size_t uriWithoutQueryLen = 0;
4098 size_t queryLen = 0;
4099 size_t uriLen = strlen(uri);
4101 char *pointerToDelimiter = strstr(uri, "?");
4103 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4104 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4106 if (uriWithoutQueryLen)
4108 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4109 if (!*uriWithoutQuery)
4113 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4117 *query = (char *) OICCalloc(queryLen + 1, 1);
4120 OICFree(*uriWithoutQuery);
4121 *uriWithoutQuery = NULL;
4124 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4130 return OC_STACK_NO_MEMORY;
4133 const OicUuid_t* OCGetServerInstanceID(void)
4135 static bool generated = false;
4136 static OicUuid_t sid;
4142 if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4144 OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4151 const char* OCGetServerInstanceIDString(void)
4153 static bool generated = false;
4154 static char sidStr[UUID_STRING_SIZE];
4161 const OicUuid_t* sid = OCGetServerInstanceID();
4163 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4165 OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4173 CAResult_t OCSelectNetwork()
4175 CAResult_t retResult = CA_STATUS_FAILED;
4176 CAResult_t caResult = CA_STATUS_OK;
4178 CATransportAdapter_t connTypes[] = {
4180 CA_ADAPTER_RFCOMM_BTEDR,
4181 CA_ADAPTER_GATT_BTLE
4184 ,CA_ADAPTER_REMOTE_ACCESS
4191 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4193 for(int i = 0; i<numConnTypes; i++)
4195 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4196 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4198 caResult = CASelectNetwork(connTypes[i]);
4199 if(caResult == CA_STATUS_OK)
4201 retResult = CA_STATUS_OK;
4206 if(retResult != CA_STATUS_OK)
4208 return caResult; // Returns error of appropriate transport that failed fatally.
4214 OCStackResult CAResultToOCResult(CAResult_t caResult)
4220 case CA_STATUS_INVALID_PARAM:
4221 return OC_STACK_INVALID_PARAM;
4222 case CA_ADAPTER_NOT_ENABLED:
4223 return OC_STACK_ADAPTER_NOT_ENABLED;
4224 case CA_SERVER_STARTED_ALREADY:
4226 case CA_SERVER_NOT_STARTED:
4227 return OC_STACK_ERROR;
4228 case CA_DESTINATION_NOT_REACHABLE:
4229 return OC_STACK_COMM_ERROR;
4230 case CA_SOCKET_OPERATION_FAILED:
4231 return OC_STACK_COMM_ERROR;
4232 case CA_SEND_FAILED:
4233 return OC_STACK_COMM_ERROR;
4234 case CA_RECEIVE_FAILED:
4235 return OC_STACK_COMM_ERROR;
4236 case CA_MEMORY_ALLOC_FAILED:
4237 return OC_STACK_NO_MEMORY;
4238 case CA_REQUEST_TIMEOUT:
4239 return OC_STACK_TIMEOUT;
4240 case CA_DESTINATION_DISCONNECTED:
4241 return OC_STACK_COMM_ERROR;
4242 case CA_STATUS_FAILED:
4243 return OC_STACK_ERROR;
4244 case CA_NOT_SUPPORTED:
4245 return OC_STACK_NOTIMPL;
4247 return OC_STACK_ERROR;