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
37 #include "ocstackinternal.h"
38 #include "ocresourcehandler.h"
39 #include "occlientcb.h"
40 #include "ocobserve.h"
42 #include "oic_malloc.h"
43 #include "oic_string.h"
45 #include "ocserverrequest.h"
46 #include "secureresourcemanager.h"
47 #include "doxmresource.h"
49 #include "cainterface.h"
50 #include "ocpayload.h"
51 #include "ocpayloadcbor.h"
53 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
54 #include "routingutility.h"
55 #ifdef ROUTING_GATEWAY
56 #include "routingmanager.h"
65 #include "coap_time.h"
70 #include <arpa/inet.h>
74 #define UINT32_MAX (0xFFFFFFFFUL)
77 //-----------------------------------------------------------------------------
79 //-----------------------------------------------------------------------------
82 OC_STACK_UNINITIALIZED = 0,
84 OC_STACK_UNINIT_IN_PROGRESS
90 OC_PRESENCE_UNINITIALIZED = 0,
91 OC_PRESENCE_INITIALIZED
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
98 static OCStackState stackState = OC_STACK_UNINITIALIZED;
100 OCResource *headResource = NULL;
101 static OCResource *tailResource = NULL;
103 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
104 static PresenceResource presenceResource;
105 static uint8_t PresenceTimeOutSize = 0;
106 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
109 static OCMode myStackMode;
111 //TODO: revisit this design
112 static bool gRASetInfo = false;
114 OCDeviceEntityHandler defaultDeviceHandler;
115 void* defaultDeviceHandlerCallbackParameter = NULL;
118 static const char COAP_TCP[] = "coap+tcp:";
121 //-----------------------------------------------------------------------------
123 //-----------------------------------------------------------------------------
124 #define TAG "OCStack"
125 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
126 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
127 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
128 TAG, #arg " is NULL"); return (retVal); } }
129 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
130 TAG, #arg " is NULL"); return; } }
131 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
134 //TODO: we should allow the server to define this
135 #define MAX_OBSERVE_AGE (0x2FFFFUL)
137 #define MILLISECONDS_PER_SECOND (1000)
139 //-----------------------------------------------------------------------------
140 // Private internal function prototypes
141 //-----------------------------------------------------------------------------
144 * Generate handle of OCDoResource invocation for callback management.
146 * @return Generated OCDoResource handle.
148 static OCDoHandle GenerateInvocationHandle();
151 * Initialize resource data structures, variables, etc.
153 * @return ::OC_STACK_OK on success, some other value upon failure.
155 static OCStackResult initResources();
158 * Add a resource to the end of the linked list of resources.
160 * @param resource Resource to be added
162 static void insertResource(OCResource *resource);
165 * Find a resource in the linked list of resources.
167 * @param resource Resource to be found.
168 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
171 static OCResource *findResource(OCResource *resource);
174 * Insert a resource type into a resource's resource type linked list.
175 * If resource type already exists, it will not be inserted and the
176 * resourceType will be free'd.
177 * resourceType->next should be null to avoid memory leaks.
178 * Function returns silently for null args.
180 * @param resource Resource where resource type is to be inserted.
181 * @param resourceType Resource type to be inserted.
183 static void insertResourceType(OCResource *resource,
184 OCResourceType *resourceType);
187 * Get a resource type at the specified index within a resource.
189 * @param handle Handle of resource.
190 * @param index Index of resource type.
192 * @return Pointer to resource type if found, NULL otherwise.
194 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
198 * Insert a resource interface into a resource's resource interface linked list.
199 * If resource interface already exists, it will not be inserted and the
200 * resourceInterface will be free'd.
201 * resourceInterface->next should be null to avoid memory leaks.
203 * @param resource Resource where resource interface is to be inserted.
204 * @param resourceInterface Resource interface to be inserted.
206 static void insertResourceInterface(OCResource *resource,
207 OCResourceInterface *resourceInterface);
210 * Get a resource interface at the specified index within a resource.
212 * @param handle Handle of resource.
213 * @param index Index of resource interface.
215 * @return Pointer to resource interface if found, NULL otherwise.
217 static OCResourceInterface *findResourceInterfaceAtIndex(
218 OCResourceHandle handle, uint8_t index);
221 * Delete all of the dynamically allocated elements that were created for the resource type.
223 * @param resourceType Specified resource type.
225 static void deleteResourceType(OCResourceType *resourceType);
228 * Delete all of the dynamically allocated elements that were created for the resource interface.
230 * @param resourceInterface Specified resource interface.
232 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
235 * Delete all of the dynamically allocated elements that were created for the resource.
237 * @param resource Specified resource.
239 static void deleteResourceElements(OCResource *resource);
242 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
245 * @param handle Handle of resource to be deleted.
247 * @return ::OC_STACK_OK on success, some other value upon failure.
249 static OCStackResult deleteResource(OCResource *resource);
252 * Delete all of the resources in the resource list.
254 static void deleteAllResources();
257 * Increment resource sequence number. Handles rollover.
259 * @param resPtr Pointer to resource.
261 static void incrementSequenceNumber(OCResource * resPtr);
264 * Verify the lengths of the URI and the query separately.
266 * @param inputUri Input URI and query.
267 * @param uriLen The length of the initial URI with query.
268 * @return ::OC_STACK_OK on success, some other value upon failure.
270 static OCStackResult verifyUriQueryLength(const char * inputUri,
274 * Attempts to initialize every network interface that the CA Layer might have compiled in.
276 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
277 * return something other than @ref CA_STATUS_OK, then this function fails.
279 * @return ::CA_STATUS_OK on success, some other value upon failure.
281 static CAResult_t OCSelectNetwork();
284 * Get the CoAP ticks after the specified number of milli-seconds.
286 * @param afterMilliSeconds Milli-seconds.
290 static uint32_t GetTicks(uint32_t afterMilliSeconds);
293 * Convert CAResponseResult_t to OCStackResult.
295 * @param caCode CAResponseResult_t code.
296 * @return ::OC_STACK_OK on success, some other value upon failure.
298 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
301 * Convert OCStackResult to CAResponseResult_t.
303 * @param caCode OCStackResult code.
304 * @param method OCMethod method the return code replies to.
305 * @return ::CA_CONTENT on OK, some other value upon failure.
307 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
310 * Convert OCTransportFlags_t to CATransportModifiers_t.
312 * @param ocConType OCTransportFlags_t input.
313 * @return CATransportFlags
315 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
318 * Convert CATransportFlags_t to OCTransportModifiers_t.
320 * @param caConType CATransportFlags_t input.
321 * @return OCTransportFlags
323 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
326 * Handle response from presence request.
328 * @param endPoint CA remote endpoint.
329 * @param responseInfo CA response info.
330 * @return ::OC_STACK_OK on success, some other value upon failure.
332 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
333 const CAResponseInfo_t *responseInfo);
336 * This function will be called back by CA layer when a response is received.
338 * @param endPoint CA remote endpoint.
339 * @param responseInfo CA response info.
341 static void HandleCAResponses(const CAEndpoint_t* endPoint,
342 const CAResponseInfo_t* responseInfo);
345 * This function will be called back by CA layer when a request is received.
347 * @param endPoint CA remote endpoint.
348 * @param requestInfo CA request info.
350 static void HandleCARequests(const CAEndpoint_t* endPoint,
351 const CARequestInfo_t* requestInfo);
354 * Extract query from a URI.
356 * @param uri Full URI with query.
357 * @param query Pointer to string that will contain query.
358 * @param newURI Pointer to string that will contain URI.
359 * @return ::OC_STACK_OK on success, some other value upon failure.
361 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
364 * Finds a resource type in an OCResourceType link-list.
366 * @param resourceTypeList The link-list to be searched through.
367 * @param resourceTypeName The key to search for.
369 * @return Resource type that matches the key (ie. resourceTypeName) or
370 * NULL if there is either an invalid parameter or this function was unable to find the key.
372 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
373 const char * resourceTypeName);
376 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
377 * TTL will be set to maxAge.
379 * @param cbNode Callback Node for which presence ttl is to be reset.
380 * @param maxAge New value of ttl in seconds.
382 * @return ::OC_STACK_OK on success, some other value upon failure.
384 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
387 * Ensure the accept header option is set appropriatly before sending the requests and routing
388 * header option is updated with destination.
390 * @param object CA remote endpoint.
391 * @param requestInfo CA request info.
393 * @return ::OC_STACK_OK on success, some other value upon failure.
395 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
397 //-----------------------------------------------------------------------------
398 // Internal functions
399 //-----------------------------------------------------------------------------
401 uint32_t GetTicks(uint32_t afterMilliSeconds)
406 // Guard against overflow of uint32_t
407 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
408 COAP_TICKS_PER_SECOND)
410 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
418 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
420 VERIFY_NON_NULL_NR(in, FATAL);
421 VERIFY_NON_NULL_NR(out, FATAL);
423 out->adapter = (OCTransportAdapter)in->adapter;
424 out->flags = CAToOCTransportFlags(in->flags);
425 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
426 out->port = in->port;
427 out->interface = in->interface;
428 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
429 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
433 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
435 VERIFY_NON_NULL_NR(in, FATAL);
436 VERIFY_NON_NULL_NR(out, FATAL);
438 out->adapter = (CATransportAdapter_t)in->adapter;
439 out->flags = OCToCATransportFlags(in->flags);
440 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
441 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
442 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
444 out->port = in->port;
445 out->interface = in->interface;
448 void FixUpClientResponse(OCClientResponse *cr)
450 VERIFY_NON_NULL_NR(cr, FATAL);
452 cr->addr = &cr->devAddr;
453 cr->connType = (OCConnectivityType)
454 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
457 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
459 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
460 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
462 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
463 OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
464 &(requestInfo->info.numOptions));
465 if (OC_STACK_OK != rmResult)
467 OC_LOG(ERROR, TAG, "Add destination option failed");
472 // OC stack prefer CBOR encoded payloads.
473 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
474 CAResult_t result = CASendRequest(object, requestInfo);
475 if(CA_STATUS_OK != result)
477 OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
478 return CAResultToOCResult(result);
482 //-----------------------------------------------------------------------------
483 // Internal API function
484 //-----------------------------------------------------------------------------
486 // This internal function is called to update the stack with the status of
487 // observers and communication failures
488 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
490 OCStackResult result = OC_STACK_ERROR;
491 ResourceObserver * observer = NULL;
492 OCEntityHandlerRequest ehRequest = {0};
496 case OC_OBSERVER_NOT_INTERESTED:
497 OC_LOG(DEBUG, TAG, "observer not interested in our notifications");
498 observer = GetObserverUsingToken (token, tokenLength);
501 result = FormOCEntityHandlerRequest(&ehRequest,
502 (OCRequestHandle)NULL,
505 (OCResourceHandle)NULL,
506 NULL, PAYLOAD_TYPE_REPRESENTATION,
508 OC_OBSERVE_DEREGISTER,
509 observer->observeId);
510 if(result != OC_STACK_OK)
514 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
515 observer->resource->entityHandlerCallbackParam);
518 result = DeleteObserverUsingToken (token, tokenLength);
519 if(result == OC_STACK_OK)
521 OC_LOG(DEBUG, TAG, "Removed observer successfully");
525 result = OC_STACK_OK;
526 OC_LOG(DEBUG, TAG, "Observer Removal failed");
530 case OC_OBSERVER_STILL_INTERESTED:
531 OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
532 observer = GetObserverUsingToken (token, tokenLength);
535 observer->forceHighQos = 0;
536 observer->failedCommCount = 0;
537 result = OC_STACK_OK;
541 result = OC_STACK_OBSERVER_NOT_FOUND;
545 case OC_OBSERVER_FAILED_COMM:
546 OC_LOG(DEBUG, TAG, "observer is unreachable");
547 observer = GetObserverUsingToken (token, tokenLength);
550 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
552 result = FormOCEntityHandlerRequest(&ehRequest,
553 (OCRequestHandle)NULL,
556 (OCResourceHandle)NULL,
557 NULL, PAYLOAD_TYPE_REPRESENTATION,
559 OC_OBSERVE_DEREGISTER,
560 observer->observeId);
561 if(result != OC_STACK_OK)
563 return OC_STACK_ERROR;
565 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
566 observer->resource->entityHandlerCallbackParam);
568 result = DeleteObserverUsingToken (token, tokenLength);
569 if(result == OC_STACK_OK)
571 OC_LOG(DEBUG, TAG, "Removed observer successfully");
575 result = OC_STACK_OK;
576 OC_LOG(DEBUG, TAG, "Observer Removal failed");
581 observer->failedCommCount++;
582 result = OC_STACK_CONTINUE;
584 observer->forceHighQos = 1;
585 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
589 OC_LOG(ERROR, TAG, "Unknown status");
590 result = OC_STACK_ERROR;
595 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
597 OCStackResult ret = OC_STACK_ERROR;
602 ret = OC_STACK_RESOURCE_CREATED;
605 ret = OC_STACK_RESOURCE_DELETED;
612 ret = OC_STACK_INVALID_QUERY;
614 case CA_UNAUTHORIZED_REQ:
615 ret = OC_STACK_UNAUTHORIZED_REQ;
618 ret = OC_STACK_INVALID_OPTION;
621 ret = OC_STACK_NO_RESOURCE;
623 case CA_RETRANSMIT_TIMEOUT:
624 ret = OC_STACK_COMM_ERROR;
632 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
634 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
643 // This Response Code is like HTTP 204 "No Content" but only used in
644 // response to POST and PUT requests.
648 // This Response Code is like HTTP 200 "OK" but only used in response to
653 // This should not happen but,
654 // give it a value just in case but output an error
656 OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
659 case OC_STACK_RESOURCE_CREATED:
662 case OC_STACK_RESOURCE_DELETED:
665 case OC_STACK_INVALID_QUERY:
668 case OC_STACK_INVALID_OPTION:
671 case OC_STACK_NO_RESOURCE:
674 case OC_STACK_COMM_ERROR:
675 ret = CA_RETRANSMIT_TIMEOUT;
677 case OC_STACK_UNAUTHORIZED_REQ:
678 ret = CA_UNAUTHORIZED_REQ;
686 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
688 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
690 // supply default behavior.
691 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
693 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
695 if ((caFlags & OC_MASK_SCOPE) == 0)
697 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
702 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
704 return (OCTransportFlags)caFlags;
707 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
709 uint32_t lowerBound = 0;
710 uint32_t higherBound = 0;
712 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
714 return OC_STACK_INVALID_PARAM;
717 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
719 cbNode->presence->TTL = maxAgeSeconds;
721 for (int index = 0; index < PresenceTimeOutSize; index++)
723 // Guard against overflow
724 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
727 lowerBound = GetTicks((PresenceTimeOut[index] *
728 cbNode->presence->TTL *
729 MILLISECONDS_PER_SECOND)/100);
733 lowerBound = GetTicks(UINT32_MAX);
736 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
739 higherBound = GetTicks((PresenceTimeOut[index + 1] *
740 cbNode->presence->TTL *
741 MILLISECONDS_PER_SECOND)/100);
745 higherBound = GetTicks(UINT32_MAX);
748 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
750 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
751 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
752 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
755 cbNode->presence->TTLlevel = 0;
757 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
761 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
763 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
765 return OC_RSRVD_TRIGGER_CREATE;
767 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
769 return OC_RSRVD_TRIGGER_CHANGE;
773 return OC_RSRVD_TRIGGER_DELETE;
777 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
781 return OC_PRESENCE_TRIGGER_CREATE;
783 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
785 return OC_PRESENCE_TRIGGER_CREATE;
787 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
789 return OC_PRESENCE_TRIGGER_CHANGE;
793 return OC_PRESENCE_TRIGGER_DELETE;
798 * The cononical presence allows constructed URIs to be string compared.
800 * requestUri must be a char array of size CA_MAX_URI_LENGTH
802 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
805 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
806 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
807 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
809 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
811 if (ep->adapter == CA_ADAPTER_IP)
813 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
815 if ('\0' == ep->addr[0]) // multicast
817 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
821 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
822 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
827 if ('\0' == ep->addr[0]) // multicast
829 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
830 ep->port = OC_MULTICAST_PORT;
832 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
833 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
837 // might work for other adapters (untested, but better than nothing)
838 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
839 OC_RSRVD_PRESENCE_URI);
843 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
844 const CAResponseInfo_t *responseInfo)
846 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
847 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
849 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
850 ClientCB * cbNode = NULL;
851 char *resourceTypeName = NULL;
852 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
853 OCStackResult result = OC_STACK_ERROR;
856 char presenceUri[CA_MAX_URI_LENGTH];
858 int presenceSubscribe = 0;
859 int multicastPresenceSubscribe = 0;
861 if (responseInfo->result != CA_CONTENT)
863 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
864 return OC_STACK_ERROR;
867 // check for unicast presence
868 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
869 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
871 return OC_STACK_INVALID_URI;
874 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
877 presenceSubscribe = 1;
881 // check for multiicast presence
882 CAEndpoint_t ep = { .adapter = endpoint->adapter,
883 .flags = endpoint->flags };
885 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
887 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
890 multicastPresenceSubscribe = 1;
894 if (!presenceSubscribe && !multicastPresenceSubscribe)
896 OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
900 response.payload = NULL;
901 response.result = OC_STACK_OK;
903 CopyEndpointToDevAddr(endpoint, &response.devAddr);
904 FixUpClientResponse(&response);
906 if (responseInfo->info.payload)
908 result = OCParsePayload(&response.payload,
909 PAYLOAD_TYPE_PRESENCE,
910 responseInfo->info.payload,
911 responseInfo->info.payloadSize);
913 if(result != OC_STACK_OK)
915 OC_LOG(ERROR, TAG, "Presence parse failed");
918 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
920 OC_LOG(ERROR, TAG, "Presence payload was wrong type");
921 result = OC_STACK_ERROR;
924 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
925 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
926 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
929 if (presenceSubscribe)
931 if(cbNode->sequenceNumber == response.sequenceNumber)
933 OC_LOG(INFO, TAG, "No presence change");
934 ResetPresenceTTL(cbNode, maxAge);
935 OC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
941 OC_LOG(INFO, TAG, "Stopping presence");
942 response.result = OC_STACK_PRESENCE_STOPPED;
945 OICFree(cbNode->presence->timeOut);
946 OICFree(cbNode->presence);
947 cbNode->presence = NULL;
952 if(!cbNode->presence)
954 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
956 if(!(cbNode->presence))
958 OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
959 result = OC_STACK_NO_MEMORY;
963 VERIFY_NON_NULL_V(cbNode->presence);
964 cbNode->presence->timeOut = NULL;
965 cbNode->presence->timeOut = (uint32_t *)
966 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
967 if(!(cbNode->presence->timeOut)){
969 "Could not allocate memory for cbNode->presence->timeOut");
970 OICFree(cbNode->presence);
971 result = OC_STACK_NO_MEMORY;
976 ResetPresenceTTL(cbNode, maxAge);
978 cbNode->sequenceNumber = response.sequenceNumber;
980 // Ensure that a filter is actually applied.
981 if( resourceTypeName && cbNode->filterResourceType)
983 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
992 // This is the multicast case
993 OCMulticastNode* mcNode = NULL;
994 mcNode = GetMCPresenceNode(presenceUri);
998 if(mcNode->nonce == response.sequenceNumber)
1000 OC_LOG(INFO, TAG, "No presence change (Multicast)");
1003 mcNode->nonce = response.sequenceNumber;
1007 OC_LOG(INFO, TAG, "Stopping presence");
1008 response.result = OC_STACK_PRESENCE_STOPPED;
1013 char* uri = OICStrdup(presenceUri);
1017 "No Memory for URI to store in the presence node");
1018 result = OC_STACK_NO_MEMORY;
1022 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1023 if(result == OC_STACK_NO_MEMORY)
1026 "No Memory for Multicast Presence Node");
1030 // presence node now owns uri
1033 // Ensure that a filter is actually applied.
1034 if(resourceTypeName && cbNode->filterResourceType)
1036 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1043 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1045 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1047 FindAndDeleteClientCB(cbNode);
1051 OCPayloadDestroy(response.payload);
1055 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1057 VERIFY_NON_NULL_NR(endPoint, FATAL);
1058 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1060 OC_LOG(INFO, TAG, "Enter HandleCAResponses");
1062 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1063 #ifdef ROUTING_GATEWAY
1064 bool needRIHandling = false;
1066 * Routing manager is going to update either of endpoint or response or both.
1067 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1068 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1071 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1073 if(ret != OC_STACK_OK || !needRIHandling)
1075 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1081 * Put source in sender endpoint so that the next packet from application can be routed to
1082 * proper destination and remove "RM" coap header option before passing request / response to
1083 * RI as this option will make no sense to either RI or application.
1085 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1086 (uint8_t *) &(responseInfo->info.numOptions),
1087 (CAEndpoint_t *) endPoint);
1090 if(responseInfo->info.resourceUri &&
1091 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1093 HandlePresenceResponse(endPoint, responseInfo);
1097 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1098 responseInfo->info.tokenLength, NULL, NULL);
1100 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1101 responseInfo->info.tokenLength);
1105 OC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1106 if(responseInfo->result == CA_EMPTY)
1108 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1109 // We do not have a case for the client to receive a RESET
1110 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1112 //This is the case of receiving an ACK on a request to a slow resource!
1113 OC_LOG(INFO, TAG, "This is a pure ACK");
1114 //TODO: should we inform the client
1115 // app that at least the request was received at the server?
1118 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1120 OC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1121 OC_LOG(INFO, TAG, "Calling into application address space");
1123 OCClientResponse response =
1124 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1125 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1126 FixUpClientResponse(&response);
1127 response.resourceUri = responseInfo->info.resourceUri;
1128 memcpy(response.identity.id, responseInfo->info.identity.id,
1129 sizeof (response.identity.id));
1130 response.identity.id_length = responseInfo->info.identity.id_length;
1132 response.result = CAToOCStackResult(responseInfo->result);
1133 cbNode->callBack(cbNode->context,
1134 cbNode->handle, &response);
1135 FindAndDeleteClientCB(cbNode);
1139 OC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1140 OC_LOG(INFO, TAG, "Calling into application address space");
1142 OCClientResponse response =
1143 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1144 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1145 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1146 FixUpClientResponse(&response);
1147 response.resourceUri = responseInfo->info.resourceUri;
1148 memcpy(response.identity.id, responseInfo->info.identity.id,
1149 sizeof (response.identity.id));
1150 response.identity.id_length = responseInfo->info.identity.id_length;
1152 response.result = CAToOCStackResult(responseInfo->result);
1154 if(responseInfo->info.payload &&
1155 responseInfo->info.payloadSize)
1157 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1158 // check the security resource
1159 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1161 type = PAYLOAD_TYPE_SECURITY;
1163 else if (cbNode->method == OC_REST_DISCOVER)
1165 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1166 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1168 type = PAYLOAD_TYPE_DISCOVERY;
1170 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1172 type = PAYLOAD_TYPE_DEVICE;
1174 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1176 type = PAYLOAD_TYPE_PLATFORM;
1178 #ifdef ROUTING_GATEWAY
1179 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1181 type = PAYLOAD_TYPE_REPRESENTATION;
1184 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1186 type = PAYLOAD_TYPE_RD;
1190 OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1191 cbNode->method, cbNode->requestUri);
1195 else if (cbNode->method == OC_REST_GET ||
1196 cbNode->method == OC_REST_PUT ||
1197 cbNode->method == OC_REST_POST ||
1198 cbNode->method == OC_REST_OBSERVE ||
1199 cbNode->method == OC_REST_OBSERVE_ALL ||
1200 cbNode->method == OC_REST_DELETE)
1202 char targetUri[MAX_URI_LENGTH];
1203 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
1204 OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1205 if (strcmp(targetUri, cbNode->requestUri) == 0)
1207 type = PAYLOAD_TYPE_RD;
1209 if (type == PAYLOAD_TYPE_INVALID)
1211 OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1212 cbNode->method, cbNode->requestUri);
1213 type = PAYLOAD_TYPE_REPRESENTATION;
1218 OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1219 cbNode->method, cbNode->requestUri);
1223 if(OC_STACK_OK != OCParsePayload(&response.payload,
1225 responseInfo->info.payload,
1226 responseInfo->info.payloadSize))
1228 OC_LOG(ERROR, TAG, "Error converting payload");
1229 OCPayloadDestroy(response.payload);
1234 response.numRcvdVendorSpecificHeaderOptions = 0;
1235 if(responseInfo->info.numOptions > 0)
1238 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1239 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1242 uint32_t observationOption;
1243 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1244 for (observationOption=0, i=0;
1245 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1249 (observationOption << 8) | optionData[i];
1251 response.sequenceNumber = observationOption;
1253 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1258 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1261 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1263 OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1264 OCPayloadDestroy(response.payload);
1268 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1270 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1271 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1275 if (cbNode->method == OC_REST_OBSERVE &&
1276 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1277 response.sequenceNumber <= cbNode->sequenceNumber)
1279 OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1280 response.sequenceNumber);
1284 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1287 cbNode->sequenceNumber = response.sequenceNumber;
1289 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1291 FindAndDeleteClientCB(cbNode);
1295 // To keep discovery callbacks active.
1296 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1297 MILLISECONDS_PER_SECOND);
1301 //Need to send ACK when the response is CON
1302 if(responseInfo->info.type == CA_MSG_CONFIRM)
1304 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1305 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1308 OCPayloadDestroy(response.payload);
1315 OC_LOG(INFO, TAG, "There is an observer associated with the response token");
1316 if(responseInfo->result == CA_EMPTY)
1318 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1319 if(responseInfo->info.type == CA_MSG_RESET)
1321 OC_LOG(INFO, TAG, "This is a RESET");
1322 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1323 OC_OBSERVER_NOT_INTERESTED);
1325 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1327 OC_LOG(INFO, TAG, "This is a pure ACK");
1328 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1329 OC_OBSERVER_STILL_INTERESTED);
1332 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1334 OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1335 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1336 OC_OBSERVER_FAILED_COMM);
1341 if(!cbNode && !observer)
1343 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1344 || myStackMode == OC_GATEWAY)
1346 OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1347 if(responseInfo->result == CA_EMPTY)
1349 OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1353 OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1354 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1355 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1359 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1360 || myStackMode == OC_GATEWAY)
1362 OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1363 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1365 OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1366 responseInfo->info.messageId);
1368 if (responseInfo->info.type == CA_MSG_RESET)
1370 OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1371 responseInfo->info.messageId);
1378 OC_LOG(INFO, TAG, "Exit HandleCAResponses");
1382 * This function handles error response from CA
1383 * code shall be added to handle the errors
1385 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1387 OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1389 if(NULL == endPoint)
1391 OC_LOG(ERROR, TAG, "endPoint is NULL");
1395 if(NULL == errrorInfo)
1397 OC_LOG(ERROR, TAG, "errrorInfo is NULL");
1400 OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1404 * This function sends out Direct Stack Responses. These are responses that are not coming
1405 * from the application entity handler. These responses have no payload and are usually ACKs,
1406 * RESETs or some error conditions that were caught by the stack.
1408 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1409 const CAResponseResult_t responseResult, const CAMessageType_t type,
1410 const uint8_t numOptions, const CAHeaderOption_t *options,
1411 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1413 CAResponseInfo_t respInfo = {
1414 .result = responseResult
1416 respInfo.info.messageId = coapID;
1417 respInfo.info.numOptions = numOptions;
1419 if (respInfo.info.numOptions)
1421 respInfo.info.options =
1422 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1423 memcpy (respInfo.info.options, options,
1424 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1428 respInfo.info.payload = NULL;
1429 respInfo.info.token = token;
1430 respInfo.info.tokenLength = tokenLength;
1431 respInfo.info.type = type;
1432 respInfo.info.resourceUri = OICStrdup (resourceUri);
1433 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1435 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1436 // Add the destination to route option from the endpoint->routeData.
1437 OCStackResult result = RMAddInfo(endPoint->routeData,
1438 &(respInfo.info.options),
1439 &(respInfo.info.numOptions));
1440 if(OC_STACK_OK != result)
1442 OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1447 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1449 // resourceUri in the info field is cloned in the CA layer and
1450 // thus ownership is still here.
1451 OICFree (respInfo.info.resourceUri);
1452 OICFree (respInfo.info.options);
1453 if(CA_STATUS_OK != caResult)
1455 OC_LOG(ERROR, TAG, "CASendResponse error");
1456 return CAResultToOCResult(caResult);
1461 //This function will be called back by CA layer when a request is received
1462 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1464 OC_LOG(INFO, TAG, "Enter HandleCARequests");
1467 OC_LOG(ERROR, TAG, "endPoint is NULL");
1473 OC_LOG(ERROR, TAG, "requestInfo is NULL");
1477 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1478 #ifdef ROUTING_GATEWAY
1479 bool needRIHandling = false;
1481 * Routing manager is going to update either of endpoint or request or both.
1482 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1483 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1484 * destination. It can also remove "RM" coap header option before passing request / response to
1485 * RI as this option will make no sense to either RI or application.
1487 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1489 if(OC_STACK_OK != ret || !needRIHandling)
1491 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1497 * Put source in sender endpoint so that the next packet from application can be routed to
1498 * proper destination and remove RM header option.
1500 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1501 (uint8_t *) &(requestInfo->info.numOptions),
1502 (CAEndpoint_t *) endPoint);
1505 OCStackResult requestResult = OC_STACK_ERROR;
1507 if(myStackMode == OC_CLIENT)
1509 //TODO: should the client be responding to requests?
1513 OCServerProtocolRequest serverRequest = {0};
1515 OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1517 char * uriWithoutQuery = NULL;
1518 char * query = NULL;
1520 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1522 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1524 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1527 OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1528 OC_LOG_V(INFO, TAG, "Query : %s", query);
1530 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1532 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1533 OICFree(uriWithoutQuery);
1537 OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1538 OICFree(uriWithoutQuery);
1545 if(strlen(query) < MAX_QUERY_LENGTH)
1547 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1552 OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1558 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1560 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1561 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1562 memcpy (serverRequest.payload, requestInfo->info.payload,
1563 requestInfo->info.payloadSize);
1567 serverRequest.reqTotalSize = 0;
1570 switch (requestInfo->method)
1573 serverRequest.method = OC_REST_GET;
1576 serverRequest.method = OC_REST_PUT;
1579 serverRequest.method = OC_REST_POST;
1582 serverRequest.method = OC_REST_DELETE;
1585 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1586 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1587 requestInfo->info.type, requestInfo->info.numOptions,
1588 requestInfo->info.options, requestInfo->info.token,
1589 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1590 OICFree(serverRequest.payload);
1594 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1595 requestInfo->info.tokenLength);
1596 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1597 serverRequest.tokenLength = requestInfo->info.tokenLength;
1599 if (!serverRequest.requestToken)
1601 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1602 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1603 requestInfo->info.type, requestInfo->info.numOptions,
1604 requestInfo->info.options, requestInfo->info.token,
1605 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1606 OICFree(serverRequest.payload);
1609 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1611 switch (requestInfo->info.acceptFormat)
1613 case CA_FORMAT_APPLICATION_CBOR:
1614 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1616 case CA_FORMAT_UNDEFINED:
1617 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1620 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1623 if (requestInfo->info.type == CA_MSG_CONFIRM)
1625 serverRequest.qos = OC_HIGH_QOS;
1629 serverRequest.qos = OC_LOW_QOS;
1631 // CA does not need the following field
1632 // Are we sure CA does not need them? how is it responding to multicast
1633 serverRequest.delayedResNeeded = 0;
1635 serverRequest.coapID = requestInfo->info.messageId;
1637 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1639 // copy vendor specific header options
1640 uint8_t tempNum = (requestInfo->info.numOptions);
1642 // Assume no observation requested and it is a pure GET.
1643 // If obs registration/de-registration requested it'll be fetched from the
1644 // options in GetObserveHeaderOption()
1645 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1647 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1648 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1651 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1652 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1653 requestInfo->info.type, requestInfo->info.numOptions,
1654 requestInfo->info.options, requestInfo->info.token,
1655 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1656 OICFree(serverRequest.payload);
1657 OICFree(serverRequest.requestToken);
1660 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1661 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1663 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1664 sizeof(CAHeaderOption_t)*tempNum);
1667 requestResult = HandleStackRequests (&serverRequest);
1669 // Send ACK to client as precursor to slow response
1670 if(requestResult == OC_STACK_SLOW_RESOURCE)
1672 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1673 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1675 else if(requestResult != OC_STACK_OK)
1677 OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1679 CAResponseResult_t stackResponse =
1680 OCToCAStackResult(requestResult, serverRequest.method);
1682 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1683 requestInfo->info.type, requestInfo->info.numOptions,
1684 requestInfo->info.options, requestInfo->info.token,
1685 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1687 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1688 // The token is copied in there, and is thus still owned by this function.
1689 OICFree(serverRequest.payload);
1690 OICFree(serverRequest.requestToken);
1691 OC_LOG(INFO, TAG, "Exit HandleCARequests");
1694 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1696 OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1697 OCStackResult result = OC_STACK_ERROR;
1698 ResourceHandling resHandling;
1699 OCResource *resource;
1700 if(!protocolRequest)
1702 OC_LOG(ERROR, TAG, "protocolRequest is NULL");
1703 return OC_STACK_INVALID_PARAM;
1706 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1707 protocolRequest->tokenLength);
1710 OC_LOG(INFO, TAG, "This is a new Server Request");
1711 result = AddServerRequest(&request, protocolRequest->coapID,
1712 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1713 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1714 protocolRequest->observationOption, protocolRequest->qos,
1715 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1716 protocolRequest->payload, protocolRequest->requestToken,
1717 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1718 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1719 &protocolRequest->devAddr);
1720 if (OC_STACK_OK != result)
1722 OC_LOG(ERROR, TAG, "Error adding server request");
1728 OC_LOG(ERROR, TAG, "Out of Memory");
1729 return OC_STACK_NO_MEMORY;
1732 if(!protocolRequest->reqMorePacket)
1734 request->requestComplete = 1;
1739 OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1742 if(request->requestComplete)
1744 OC_LOG(INFO, TAG, "This Server Request is complete");
1745 result = DetermineResourceHandling (request, &resHandling, &resource);
1746 if (result == OC_STACK_OK)
1748 result = ProcessRequest(resHandling, resource, request);
1753 OC_LOG(INFO, TAG, "This Server Request is incomplete");
1754 result = OC_STACK_CONTINUE;
1759 bool validatePlatformInfo(OCPlatformInfo info)
1762 if (!info.platformID)
1764 OC_LOG(ERROR, TAG, "No platform ID found.");
1768 if (info.manufacturerName)
1770 size_t lenManufacturerName = strlen(info.manufacturerName);
1772 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1774 OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1780 OC_LOG(ERROR, TAG, "No manufacturer name present");
1784 if (info.manufacturerUrl)
1786 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1788 OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1795 //-----------------------------------------------------------------------------
1797 //-----------------------------------------------------------------------------
1799 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1802 !raInfo->username ||
1803 !raInfo->hostname ||
1804 !raInfo->xmpp_domain)
1807 return OC_STACK_INVALID_PARAM;
1809 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1810 gRASetInfo = (result == OC_STACK_OK)? true : false;
1816 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1820 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1823 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1825 if(stackState == OC_STACK_INITIALIZED)
1827 OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1828 OCStop() between them are ignored.");
1832 #ifndef ROUTING_GATEWAY
1833 if (OC_GATEWAY == mode)
1835 OC_LOG(ERROR, TAG, "Routing Manager not supported");
1836 return OC_STACK_INVALID_PARAM;
1843 OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1844 return OC_STACK_ERROR;
1848 OCStackResult result = OC_STACK_ERROR;
1849 OC_LOG(INFO, TAG, "Entering OCInit");
1852 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1853 || (mode == OC_GATEWAY)))
1855 OC_LOG(ERROR, TAG, "Invalid mode");
1856 return OC_STACK_ERROR;
1860 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1862 caglobals.client = true;
1864 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1866 caglobals.server = true;
1869 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1870 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1872 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1874 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1875 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1877 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1881 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1883 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
1885 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1887 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
1891 defaultDeviceHandler = NULL;
1892 defaultDeviceHandlerCallbackParameter = NULL;
1895 result = CAResultToOCResult(CAInitialize());
1896 VERIFY_SUCCESS(result, OC_STACK_OK);
1898 result = CAResultToOCResult(OCSelectNetwork());
1899 VERIFY_SUCCESS(result, OC_STACK_OK);
1901 switch (myStackMode)
1904 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1905 result = CAResultToOCResult(CAStartDiscoveryServer());
1906 OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1909 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1910 result = CAResultToOCResult(CAStartListeningServer());
1911 OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1913 case OC_CLIENT_SERVER:
1915 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1916 result = CAResultToOCResult(CAStartListeningServer());
1917 if(result == OC_STACK_OK)
1919 result = CAResultToOCResult(CAStartDiscoveryServer());
1923 VERIFY_SUCCESS(result, OC_STACK_OK);
1925 #ifdef WITH_PRESENCE
1926 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1927 #endif // WITH_PRESENCE
1929 //Update Stack state to initialized
1930 stackState = OC_STACK_INITIALIZED;
1932 // Initialize resource
1933 if(myStackMode != OC_CLIENT)
1935 result = initResources();
1938 // Initialize the SRM Policy Engine
1939 if(result == OC_STACK_OK)
1941 result = SRMInitPolicyEngine();
1942 // TODO after BeachHead delivery: consolidate into single SRMInit()
1945 #ifdef ROUTING_GATEWAY
1946 if (OC_GATEWAY == myStackMode)
1948 result = RMInitialize();
1953 if(result != OC_STACK_OK)
1955 OC_LOG(ERROR, TAG, "Stack initialization error");
1956 deleteAllResources();
1958 stackState = OC_STACK_UNINITIALIZED;
1963 OCStackResult OCStop()
1965 OC_LOG(INFO, TAG, "Entering OCStop");
1967 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1969 OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1972 else if (stackState != OC_STACK_INITIALIZED)
1974 OC_LOG(ERROR, TAG, "Stack not initialized");
1975 return OC_STACK_ERROR;
1978 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1980 #ifdef WITH_PRESENCE
1981 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1982 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1983 presenceResource.presenceTTL = 0;
1984 #endif // WITH_PRESENCE
1986 #ifdef ROUTING_GATEWAY
1987 if (OC_GATEWAY == myStackMode)
1993 // Free memory dynamically allocated for resources
1994 deleteAllResources();
1996 DeletePlatformInfo();
1998 // Remove all observers
1999 DeleteObserverList();
2000 // Remove all the client callbacks
2001 DeleteClientCBList();
2003 // De-init the SRM Policy Engine
2004 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2005 SRMDeInitPolicyEngine();
2008 stackState = OC_STACK_UNINITIALIZED;
2012 OCStackResult OCStartMulticastServer()
2014 if(stackState != OC_STACK_INITIALIZED)
2016 OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2017 return OC_STACK_ERROR;
2019 CAResult_t ret = CAStartListeningServer();
2020 if (CA_STATUS_OK != ret)
2022 OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2023 return OC_STACK_ERROR;
2028 OCStackResult OCStopMulticastServer()
2030 CAResult_t ret = CAStopListeningServer();
2031 if (CA_STATUS_OK != ret)
2033 OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2034 return OC_STACK_ERROR;
2039 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2044 return CA_MSG_CONFIRM;
2049 return CA_MSG_NONCONFIRM;
2053 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2057 query = strchr (inputUri, '?');
2061 if((query - inputUri) > MAX_URI_LENGTH)
2063 return OC_STACK_INVALID_URI;
2066 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2068 return OC_STACK_INVALID_QUERY;
2071 else if(uriLen > MAX_URI_LENGTH)
2073 return OC_STACK_INVALID_URI;
2079 * A request uri consists of the following components in order:
2082 * CoAP over UDP prefix "coap://"
2083 * CoAP over TCP prefix "coap+tcp://"
2085 * IPv6 address "[1234::5678]"
2086 * IPv4 address "192.168.1.1"
2087 * optional port ":5683"
2088 * resource uri "/oc/core..."
2090 * for PRESENCE requests, extract resource type.
2092 static OCStackResult ParseRequestUri(const char *fullUri,
2093 OCTransportAdapter adapter,
2094 OCTransportFlags flags,
2095 OCDevAddr **devAddr,
2097 char **resourceType)
2099 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2101 OCStackResult result = OC_STACK_OK;
2102 OCDevAddr *da = NULL;
2106 // provide defaults for all returned values
2113 *resourceUri = NULL;
2117 *resourceType = NULL;
2120 // delimit url prefix, if any
2121 const char *start = fullUri;
2122 char *slash2 = strstr(start, "//");
2127 char *slash = strchr(start, '/');
2130 return OC_STACK_INVALID_URI;
2134 // process url scheme
2135 size_t prefixLen = slash2 - fullUri;
2139 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2146 // TODO: this logic should come in with unit tests exercising the various strings
2147 // processs url prefix, if any
2148 size_t urlLen = slash - start;
2152 if (urlLen && devAddr)
2153 { // construct OCDevAddr
2154 if (start[0] == '[')
2156 char *close = strchr(++start, ']');
2157 if (!close || close > slash)
2159 return OC_STACK_INVALID_URI;
2162 if (close[1] == ':')
2166 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2167 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2171 char *dot = strchr(start, '.');
2172 if (dot && dot < slash)
2174 colon = strchr(start, ':');
2175 end = (colon && colon < slash) ? colon : slash;
2179 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2184 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2185 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2194 if (len >= sizeof(da->addr))
2196 return OC_STACK_INVALID_URI;
2198 // collect port, if any
2199 if (colon && colon < slash)
2201 for (colon++; colon < slash; colon++)
2204 if (c < '0' || c > '9')
2206 return OC_STACK_INVALID_URI;
2208 port = 10 * port + c - '0';
2213 if (len >= sizeof(da->addr))
2215 return OC_STACK_INVALID_URI;
2218 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2221 return OC_STACK_NO_MEMORY;
2223 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2225 da->adapter = adapter;
2227 if (!strncmp(fullUri, "coaps:", 6))
2229 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2234 // process resource uri, if any
2236 { // request uri and query
2237 size_t ulen = strlen(slash); // resource uri length
2238 size_t tlen = 0; // resource type length
2241 static const char strPresence[] = "/oic/ad?rt=";
2242 static const size_t lenPresence = sizeof(strPresence) - 1;
2243 if (!strncmp(slash, strPresence, lenPresence))
2245 type = slash + lenPresence;
2246 tlen = ulen - lenPresence;
2251 *resourceUri = (char *)OICMalloc(ulen + 1);
2254 result = OC_STACK_NO_MEMORY;
2257 strcpy(*resourceUri, slash);
2260 if (type && resourceType)
2262 *resourceType = (char *)OICMalloc(tlen + 1);
2265 result = OC_STACK_NO_MEMORY;
2269 OICStrcpy(*resourceType, (tlen+1), type);
2276 // free all returned values
2283 OICFree(*resourceUri);
2287 OICFree(*resourceType);
2292 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2293 char *resourceUri, char **requestUri)
2295 char uri[CA_MAX_URI_LENGTH];
2297 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2299 *requestUri = OICStrdup(uri);
2302 return OC_STACK_NO_MEMORY;
2309 * Discover or Perform requests on a specified resource
2311 OCStackResult OCDoResource(OCDoHandle *handle,
2313 const char *requestUri,
2314 const OCDevAddr *destination,
2316 OCConnectivityType connectivityType,
2317 OCQualityOfService qos,
2318 OCCallbackData *cbData,
2319 OCHeaderOption *options,
2322 OC_LOG(INFO, TAG, "Entering OCDoResource");
2324 // Validate input parameters
2325 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2326 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2327 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2329 OCStackResult result = OC_STACK_ERROR;
2330 CAResult_t caResult;
2331 CAToken_t token = NULL;
2332 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2333 ClientCB *clientCB = NULL;
2334 OCDoHandle resHandle = NULL;
2335 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2336 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2338 OCTransportAdapter adapter;
2339 OCTransportFlags flags;
2340 // the request contents are put here
2341 CARequestInfo_t requestInfo = {.method = CA_GET};
2342 // requestUri will be parsed into the following three variables
2343 OCDevAddr *devAddr = NULL;
2344 char *resourceUri = NULL;
2345 char *resourceType = NULL;
2347 // This validation is broken, but doesn't cause harm
2348 size_t uriLen = strlen(requestUri );
2349 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2355 * Support original behavior with address on resourceUri argument.
2357 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2358 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2360 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2362 if (result != OC_STACK_OK)
2364 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2371 case OC_REST_OBSERVE:
2372 case OC_REST_OBSERVE_ALL:
2373 case OC_REST_CANCEL_OBSERVE:
2374 requestInfo.method = CA_GET;
2377 requestInfo.method = CA_PUT;
2380 requestInfo.method = CA_POST;
2382 case OC_REST_DELETE:
2383 requestInfo.method = CA_DELETE;
2385 case OC_REST_DISCOVER:
2387 if (destination || devAddr)
2389 requestInfo.isMulticast = false;
2393 tmpDevAddr.adapter = adapter;
2394 tmpDevAddr.flags = flags;
2395 destination = &tmpDevAddr;
2396 requestInfo.isMulticast = true;
2398 // CA_DISCOVER will become GET and isMulticast
2399 requestInfo.method = CA_GET;
2401 #ifdef WITH_PRESENCE
2402 case OC_REST_PRESENCE:
2403 // Replacing method type with GET because "presence"
2404 // is a stack layer only implementation.
2405 requestInfo.method = CA_GET;
2409 result = OC_STACK_INVALID_METHOD;
2413 if (!devAddr && !destination)
2415 OC_LOG(DEBUG, TAG, "no devAddr and no destination");
2416 result = OC_STACK_INVALID_PARAM;
2420 /* If not original behavior, use destination argument */
2421 if (destination && !devAddr)
2423 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2426 result = OC_STACK_NO_MEMORY;
2429 *devAddr = *destination;
2432 resHandle = GenerateInvocationHandle();
2435 result = OC_STACK_NO_MEMORY;
2439 caResult = CAGenerateToken(&token, tokenLength);
2440 if (caResult != CA_STATUS_OK)
2442 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2443 result= OC_STACK_ERROR;
2447 // fill in request data
2448 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2449 requestInfo.info.token = token;
2450 requestInfo.info.tokenLength = tokenLength;
2451 requestInfo.info.resourceUri = resourceUri;
2453 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2455 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2456 options, numOptions, OC_OBSERVE_REGISTER);
2457 if (result != OC_STACK_OK)
2461 requestInfo.info.numOptions = numOptions + 1;
2465 requestInfo.info.numOptions = numOptions;
2466 requestInfo.info.options =
2467 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2468 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2469 numOptions * sizeof(CAHeaderOption_t));
2472 CopyDevAddrToEndpoint(devAddr, &endpoint);
2477 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2480 OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2483 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2487 requestInfo.info.payload = NULL;
2488 requestInfo.info.payloadSize = 0;
2489 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2492 if (result != OC_STACK_OK)
2494 OC_LOG(ERROR, TAG, "CACreateEndpoint error");
2498 // prepare for response
2499 #ifdef WITH_PRESENCE
2500 if (method == OC_REST_PRESENCE)
2502 char *presenceUri = NULL;
2503 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2504 if (OC_STACK_OK != result)
2509 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2510 // Presence notification will form a canonical uri to
2511 // look for callbacks into the application.
2512 resourceUri = presenceUri;
2516 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2517 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2518 method, devAddr, resourceUri, resourceType, ttl);
2519 if (OC_STACK_OK != result)
2524 devAddr = NULL; // Client CB list entry now owns it
2525 resourceUri = NULL; // Client CB list entry now owns it
2526 resourceType = NULL; // Client CB list entry now owns it
2529 result = OCSendRequest(&endpoint, &requestInfo);
2530 if (OC_STACK_OK != result)
2537 *handle = resHandle;
2541 if (result != OC_STACK_OK)
2543 OC_LOG(ERROR, TAG, "OCDoResource error");
2544 FindAndDeleteClientCB(clientCB);
2545 CADestroyToken(token);
2553 // This is the owner of the payload object, so we free it
2554 OCPayloadDestroy(payload);
2555 OICFree(requestInfo.info.payload);
2557 OICFree(resourceUri);
2558 OICFree(resourceType);
2559 OICFree(requestInfo.info.options);
2563 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2567 * This ftn is implemented one of two ways in the case of observation:
2569 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2570 * Remove the callback associated on client side.
2571 * When the next notification comes in from server,
2572 * reply with RESET message to server.
2573 * Keep in mind that the server will react to RESET only
2574 * if the last notification was sent as CON
2576 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2577 * and it is associated with an observe request
2578 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2579 * Send CON Observe request to server with
2580 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2581 * Remove the callback associated on client side.
2583 OCStackResult ret = OC_STACK_OK;
2584 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2585 CARequestInfo_t requestInfo = {.method = CA_GET};
2589 return OC_STACK_INVALID_PARAM;
2592 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2595 OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2596 return OC_STACK_ERROR;
2599 switch (clientCB->method)
2601 case OC_REST_OBSERVE:
2602 case OC_REST_OBSERVE_ALL:
2604 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2605 clientCB->requestUri);
2606 if (qos != OC_HIGH_QOS)
2608 FindAndDeleteClientCB(clientCB);
2612 OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2614 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2615 requestInfo.info.token = clientCB->token;
2616 requestInfo.info.tokenLength = clientCB->tokenLength;
2618 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2619 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2621 return OC_STACK_ERROR;
2623 requestInfo.info.numOptions = numOptions + 1;
2624 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2626 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2628 ret = OCSendRequest(&endpoint, &requestInfo);
2630 if (requestInfo.info.options)
2632 OICFree (requestInfo.info.options);
2634 if (requestInfo.info.resourceUri)
2636 OICFree (requestInfo.info.resourceUri);
2641 case OC_REST_DISCOVER:
2642 OC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2643 clientCB->requestUri);
2644 FindAndDeleteClientCB(clientCB);
2647 #ifdef WITH_PRESENCE
2648 case OC_REST_PRESENCE:
2649 FindAndDeleteClientCB(clientCB);
2654 ret = OC_STACK_INVALID_METHOD;
2662 * @brief Register Persistent storage callback.
2663 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2665 * OC_STACK_OK - No errors; Success
2666 * OC_STACK_INVALID_PARAM - Invalid parameter
2668 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2670 OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2671 if(!persistentStorageHandler)
2673 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2674 return OC_STACK_INVALID_PARAM;
2678 if( !persistentStorageHandler->open ||
2679 !persistentStorageHandler->close ||
2680 !persistentStorageHandler->read ||
2681 !persistentStorageHandler->unlink ||
2682 !persistentStorageHandler->write)
2684 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2685 return OC_STACK_INVALID_PARAM;
2688 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2691 #ifdef WITH_PRESENCE
2693 OCStackResult OCProcessPresence()
2695 OCStackResult result = OC_STACK_OK;
2697 // the following line floods the log with messages that are irrelevant
2698 // to most purposes. Uncomment as needed.
2699 //OC_LOG(INFO, TAG, "Entering RequestPresence");
2700 ClientCB* cbNode = NULL;
2701 OCClientResponse clientResponse;
2702 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2704 LL_FOREACH(cbList, cbNode)
2706 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2711 uint32_t now = GetTicks(0);
2712 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2713 cbNode->presence->TTLlevel);
2714 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2716 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2721 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2723 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2724 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2726 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2728 OC_LOG(DEBUG, TAG, "No more timeout ticks");
2730 clientResponse.sequenceNumber = 0;
2731 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2732 clientResponse.devAddr = *cbNode->devAddr;
2733 FixUpClientResponse(&clientResponse);
2734 clientResponse.payload = NULL;
2736 // Increment the TTLLevel (going to a next state), so we don't keep
2737 // sending presence notification to client.
2738 cbNode->presence->TTLlevel++;
2739 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2740 cbNode->presence->TTLlevel);
2742 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2743 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2745 FindAndDeleteClientCB(cbNode);
2749 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2754 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2755 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2756 CARequestInfo_t requestInfo = {.method = CA_GET};
2758 OC_LOG(DEBUG, TAG, "time to test server presence");
2760 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2762 requestData.type = CA_MSG_NONCONFIRM;
2763 requestData.token = cbNode->token;
2764 requestData.tokenLength = cbNode->tokenLength;
2765 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2766 requestInfo.method = CA_GET;
2767 requestInfo.info = requestData;
2769 result = OCSendRequest(&endpoint, &requestInfo);
2770 if (OC_STACK_OK != result)
2775 cbNode->presence->TTLlevel++;
2776 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2779 if (result != OC_STACK_OK)
2781 OC_LOG(ERROR, TAG, "OCProcessPresence error");
2786 #endif // WITH_PRESENCE
2788 OCStackResult OCProcess()
2790 #ifdef WITH_PRESENCE
2791 OCProcessPresence();
2793 CAHandleRequestResponse();
2795 #ifdef ROUTING_GATEWAY
2801 #ifdef WITH_PRESENCE
2802 OCStackResult OCStartPresence(const uint32_t ttl)
2804 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2805 OCChangeResourceProperty(
2806 &(((OCResource *)presenceResource.handle)->resourceProperties),
2809 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2811 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2812 OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2816 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2817 OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2821 presenceResource.presenceTTL = ttl;
2823 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2825 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2827 presenceState = OC_PRESENCE_INITIALIZED;
2829 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2831 CAToken_t caToken = NULL;
2832 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2833 if (caResult != CA_STATUS_OK)
2835 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2836 CADestroyToken(caToken);
2837 return OC_STACK_ERROR;
2840 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2841 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2842 CADestroyToken(caToken);
2845 // Each time OCStartPresence is called
2846 // a different random 32-bit integer number is used
2847 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2849 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2850 OC_PRESENCE_TRIGGER_CREATE);
2853 OCStackResult OCStopPresence()
2855 OCStackResult result = OC_STACK_ERROR;
2857 if(presenceResource.handle)
2859 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2861 // make resource inactive
2862 result = OCChangeResourceProperty(
2863 &(((OCResource *) presenceResource.handle)->resourceProperties),
2867 if(result != OC_STACK_OK)
2870 "Changing the presence resource properties to ACTIVE not successful");
2874 return SendStopNotification();
2878 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2879 void* callbackParameter)
2881 defaultDeviceHandler = entityHandler;
2882 defaultDeviceHandlerCallbackParameter = callbackParameter;
2887 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2889 OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2891 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2893 if (validatePlatformInfo(platformInfo))
2895 return SavePlatformInfo(platformInfo);
2899 return OC_STACK_INVALID_PARAM;
2904 return OC_STACK_ERROR;
2908 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2910 OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2912 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2914 OC_LOG(ERROR, TAG, "Null or empty device name.");
2915 return OC_STACK_INVALID_PARAM;
2918 return SaveDeviceInfo(deviceInfo);
2921 OCStackResult OCCreateResource(OCResourceHandle *handle,
2922 const char *resourceTypeName,
2923 const char *resourceInterfaceName,
2924 const char *uri, OCEntityHandler entityHandler,
2925 void* callbackParam,
2926 uint8_t resourceProperties)
2929 OCResource *pointer = NULL;
2930 OCStackResult result = OC_STACK_ERROR;
2932 OC_LOG(INFO, TAG, "Entering OCCreateResource");
2934 if(myStackMode == OC_CLIENT)
2936 return OC_STACK_INVALID_PARAM;
2938 // Validate parameters
2939 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2941 OC_LOG(ERROR, TAG, "URI is empty or too long");
2942 return OC_STACK_INVALID_URI;
2944 // Is it presented during resource discovery?
2945 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2947 OC_LOG(ERROR, TAG, "Input parameter is NULL");
2948 return OC_STACK_INVALID_PARAM;
2951 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2953 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2956 // Make sure resourceProperties bitmask has allowed properties specified
2957 if (resourceProperties
2958 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2959 OC_EXPLICIT_DISCOVERABLE))
2961 OC_LOG(ERROR, TAG, "Invalid property");
2962 return OC_STACK_INVALID_PARAM;
2965 // If the headResource is NULL, then no resources have been created...
2966 pointer = headResource;
2969 // At least one resources is in the resource list, so we need to search for
2970 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2973 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2975 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2976 return OC_STACK_INVALID_PARAM;
2978 pointer = pointer->next;
2981 // Create the pointer and insert it into the resource list
2982 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2985 result = OC_STACK_NO_MEMORY;
2988 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2990 insertResource(pointer);
2993 pointer->uri = OICStrdup(uri);
2996 result = OC_STACK_NO_MEMORY;
3000 // Set properties. Set OC_ACTIVE
3001 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3004 // Add the resourcetype to the resource
3005 result = BindResourceTypeToResource(pointer, resourceTypeName);
3006 if (result != OC_STACK_OK)
3008 OC_LOG(ERROR, TAG, "Error adding resourcetype");
3012 // Add the resourceinterface to the resource
3013 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3014 if (result != OC_STACK_OK)
3016 OC_LOG(ERROR, TAG, "Error adding resourceinterface");
3020 // If an entity handler has been passed, attach it to the newly created
3021 // resource. Otherwise, set the default entity handler.
3024 pointer->entityHandler = entityHandler;
3025 pointer->entityHandlerCallbackParam = callbackParam;
3029 pointer->entityHandler = defaultResourceEHandler;
3030 pointer->entityHandlerCallbackParam = NULL;
3034 result = OC_STACK_OK;
3036 #ifdef WITH_PRESENCE
3037 if (presenceResource.handle)
3039 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3040 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3044 if (result != OC_STACK_OK)
3046 // Deep delete of resource and other dynamic elements that it contains
3047 deleteResource(pointer);
3053 OCStackResult OCBindResource(
3054 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3056 OCResource *resource = NULL;
3059 OC_LOG(INFO, TAG, "Entering OCBindResource");
3061 // Validate parameters
3062 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3063 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3064 // Container cannot contain itself
3065 if (collectionHandle == resourceHandle)
3067 OC_LOG(ERROR, TAG, "Added handle equals collection handle");
3068 return OC_STACK_INVALID_PARAM;
3071 // Use the handle to find the resource in the resource linked list
3072 resource = findResource((OCResource *) collectionHandle);
3075 OC_LOG(ERROR, TAG, "Collection handle not found");
3076 return OC_STACK_INVALID_PARAM;
3079 // Look for an open slot to add add the child resource.
3080 // If found, add it and return success
3081 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3083 if (!resource->rsrcResources[i])
3085 resource->rsrcResources[i] = (OCResource *) resourceHandle;
3086 OC_LOG(INFO, TAG, "resource bound");
3088 #ifdef WITH_PRESENCE
3089 if (presenceResource.handle)
3091 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3092 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3093 OC_PRESENCE_TRIGGER_CHANGE);
3101 // Unable to add resourceHandle, so return error
3102 return OC_STACK_ERROR;
3105 OCStackResult OCUnBindResource(
3106 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3108 OCResource *resource = NULL;
3111 OC_LOG(INFO, TAG, "Entering OCUnBindResource");
3113 // Validate parameters
3114 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3115 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3116 // Container cannot contain itself
3117 if (collectionHandle == resourceHandle)
3119 OC_LOG(ERROR, TAG, "removing handle equals collection handle");
3120 return OC_STACK_INVALID_PARAM;
3123 // Use the handle to find the resource in the resource linked list
3124 resource = findResource((OCResource *) collectionHandle);
3127 OC_LOG(ERROR, TAG, "Collection handle not found");
3128 return OC_STACK_INVALID_PARAM;
3131 // Look for an open slot to add add the child resource.
3132 // If found, add it and return success
3133 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3135 if (resourceHandle == resource->rsrcResources[i])
3137 resource->rsrcResources[i] = (OCResource *) NULL;
3138 OC_LOG(INFO, TAG, "resource unbound");
3140 // Send notification when resource is unbounded successfully.
3141 #ifdef WITH_PRESENCE
3142 if (presenceResource.handle)
3144 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3145 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3146 OC_PRESENCE_TRIGGER_CHANGE);
3153 OC_LOG(INFO, TAG, "resource not found in collection");
3155 // Unable to add resourceHandle, so return error
3156 return OC_STACK_ERROR;
3159 // Precondition is that the parameter has been checked to not equal NULL.
3160 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3162 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3168 while (resourceItemName[index] != '\0')
3170 if (resourceItemName[index] != '.' &&
3171 resourceItemName[index] != '-' &&
3172 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3173 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3182 OCStackResult BindResourceTypeToResource(OCResource* resource,
3183 const char *resourceTypeName)
3185 OCResourceType *pointer = NULL;
3187 OCStackResult result = OC_STACK_ERROR;
3189 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3191 if (!ValidateResourceTypeInterface(resourceTypeName))
3193 OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3194 return OC_STACK_INVALID_PARAM;
3197 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3200 result = OC_STACK_NO_MEMORY;
3204 str = OICStrdup(resourceTypeName);
3207 result = OC_STACK_NO_MEMORY;
3210 pointer->resourcetypename = str;
3212 insertResourceType(resource, pointer);
3213 result = OC_STACK_OK;
3216 if (result != OC_STACK_OK)
3225 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3226 const char *resourceInterfaceName)
3228 OCResourceInterface *pointer = NULL;
3230 OCStackResult result = OC_STACK_ERROR;
3232 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3234 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3236 OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3237 return OC_STACK_INVALID_PARAM;
3240 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3242 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3245 result = OC_STACK_NO_MEMORY;
3249 str = OICStrdup(resourceInterfaceName);
3252 result = OC_STACK_NO_MEMORY;
3255 pointer->name = str;
3257 // Bind the resourceinterface to the resource
3258 insertResourceInterface(resource, pointer);
3260 result = OC_STACK_OK;
3263 if (result != OC_STACK_OK)
3272 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3273 const char *resourceTypeName)
3276 OCStackResult result = OC_STACK_ERROR;
3277 OCResource *resource = NULL;
3279 resource = findResource((OCResource *) handle);
3282 OC_LOG(ERROR, TAG, "Resource not found");
3283 return OC_STACK_ERROR;
3286 result = BindResourceTypeToResource(resource, resourceTypeName);
3288 #ifdef WITH_PRESENCE
3289 if(presenceResource.handle)
3291 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3292 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3299 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3300 const char *resourceInterfaceName)
3303 OCStackResult result = OC_STACK_ERROR;
3304 OCResource *resource = NULL;
3306 resource = findResource((OCResource *) handle);
3309 OC_LOG(ERROR, TAG, "Resource not found");
3310 return OC_STACK_ERROR;
3313 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3315 #ifdef WITH_PRESENCE
3316 if (presenceResource.handle)
3318 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3319 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3326 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3328 OCResource *pointer = headResource;
3330 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3334 *numResources = *numResources + 1;
3335 pointer = pointer->next;
3340 OCResourceHandle OCGetResourceHandle(uint8_t index)
3342 OCResource *pointer = headResource;
3344 for( uint8_t i = 0; i < index && pointer; ++i)
3346 pointer = pointer->next;
3348 return (OCResourceHandle) pointer;
3351 OCStackResult OCDeleteResource(OCResourceHandle handle)
3355 OC_LOG(ERROR, TAG, "Invalid handle for deletion");
3356 return OC_STACK_INVALID_PARAM;
3359 OCResource *resource = findResource((OCResource *) handle);
3360 if (resource == NULL)
3362 OC_LOG(ERROR, TAG, "Resource not found");
3363 return OC_STACK_NO_RESOURCE;
3366 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3368 OC_LOG(ERROR, TAG, "Error deleting resource");
3369 return OC_STACK_ERROR;
3375 const char *OCGetResourceUri(OCResourceHandle handle)
3377 OCResource *resource = NULL;
3379 resource = findResource((OCResource *) handle);
3382 return resource->uri;
3384 return (const char *) NULL;
3387 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3389 OCResource *resource = NULL;
3391 resource = findResource((OCResource *) handle);
3394 return resource->resourceProperties;
3396 return (OCResourceProperty)-1;
3399 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3400 uint8_t *numResourceTypes)
3402 OCResource *resource = NULL;
3403 OCResourceType *pointer = NULL;
3405 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3406 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3408 *numResourceTypes = 0;
3410 resource = findResource((OCResource *) handle);
3413 pointer = resource->rsrcType;
3416 *numResourceTypes = *numResourceTypes + 1;
3417 pointer = pointer->next;
3423 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3425 OCResourceType *resourceType = NULL;
3427 resourceType = findResourceTypeAtIndex(handle, index);
3430 return resourceType->resourcetypename;
3432 return (const char *) NULL;
3435 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3436 uint8_t *numResourceInterfaces)
3438 OCResourceInterface *pointer = NULL;
3439 OCResource *resource = NULL;
3441 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3442 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3444 *numResourceInterfaces = 0;
3445 resource = findResource((OCResource *) handle);
3448 pointer = resource->rsrcInterface;
3451 *numResourceInterfaces = *numResourceInterfaces + 1;
3452 pointer = pointer->next;
3458 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3460 OCResourceInterface *resourceInterface = NULL;
3462 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3463 if (resourceInterface)
3465 return resourceInterface->name;
3467 return (const char *) NULL;
3470 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3473 OCResource *resource = NULL;
3475 if (index >= MAX_CONTAINED_RESOURCES)
3480 resource = findResource((OCResource *) collectionHandle);
3486 return resource->rsrcResources[index];
3489 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3490 OCEntityHandler entityHandler,
3491 void* callbackParam)
3493 OCResource *resource = NULL;
3495 // Validate parameters
3496 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3498 // Use the handle to find the resource in the resource linked list
3499 resource = findResource((OCResource *)handle);
3502 OC_LOG(ERROR, TAG, "Resource not found");
3503 return OC_STACK_ERROR;
3507 resource->entityHandler = entityHandler;
3508 resource->entityHandlerCallbackParam = callbackParam;
3510 #ifdef WITH_PRESENCE
3511 if (presenceResource.handle)
3513 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3514 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3521 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3523 OCResource *resource = NULL;
3525 resource = findResource((OCResource *)handle);
3528 OC_LOG(ERROR, TAG, "Resource not found");
3533 return resource->entityHandler;
3536 void incrementSequenceNumber(OCResource * resPtr)
3538 // Increment the sequence number
3539 resPtr->sequenceNum += 1;
3540 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3542 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3547 #ifdef WITH_PRESENCE
3548 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3549 OCPresenceTrigger trigger)
3551 OCResource *resPtr = NULL;
3552 OCStackResult result = OC_STACK_ERROR;
3553 OCMethod method = OC_REST_PRESENCE;
3554 uint32_t maxAge = 0;
3555 resPtr = findResource((OCResource *) presenceResource.handle);
3558 return OC_STACK_NO_RESOURCE;
3561 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3563 maxAge = presenceResource.presenceTTL;
3565 result = SendAllObserverNotification(method, resPtr, maxAge,
3566 trigger, resourceType, OC_LOW_QOS);
3572 OCStackResult SendStopNotification()
3574 OCResource *resPtr = NULL;
3575 OCStackResult result = OC_STACK_ERROR;
3576 OCMethod method = OC_REST_PRESENCE;
3577 resPtr = findResource((OCResource *) presenceResource.handle);
3580 return OC_STACK_NO_RESOURCE;
3583 // maxAge is 0. ResourceType is NULL.
3584 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3590 #endif // WITH_PRESENCE
3591 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3593 OCResource *resPtr = NULL;
3594 OCStackResult result = OC_STACK_ERROR;
3595 OCMethod method = OC_REST_NOMETHOD;
3596 uint32_t maxAge = 0;
3598 OC_LOG(INFO, TAG, "Notifying all observers");
3599 #ifdef WITH_PRESENCE
3600 if(handle == presenceResource.handle)
3604 #endif // WITH_PRESENCE
3605 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3607 // Verify that the resource exists
3608 resPtr = findResource ((OCResource *) handle);
3611 return OC_STACK_NO_RESOURCE;
3615 //only increment in the case of regular observing (not presence)
3616 incrementSequenceNumber(resPtr);
3617 method = OC_REST_OBSERVE;
3618 maxAge = MAX_OBSERVE_AGE;
3619 #ifdef WITH_PRESENCE
3620 result = SendAllObserverNotification (method, resPtr, maxAge,
3621 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3623 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3630 OCNotifyListOfObservers (OCResourceHandle handle,
3631 OCObservationId *obsIdList,
3632 uint8_t numberOfIds,
3633 const OCRepPayload *payload,
3634 OCQualityOfService qos)
3636 OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3638 OCResource *resPtr = NULL;
3639 //TODO: we should allow the server to define this
3640 uint32_t maxAge = MAX_OBSERVE_AGE;
3642 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3643 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3644 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3646 resPtr = findResource ((OCResource *) handle);
3647 if (NULL == resPtr || myStackMode == OC_CLIENT)
3649 return OC_STACK_NO_RESOURCE;
3653 incrementSequenceNumber(resPtr);
3655 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3656 payload, maxAge, qos));
3659 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3661 OCStackResult result = OC_STACK_ERROR;
3662 OCServerRequest *serverRequest = NULL;
3664 OC_LOG(INFO, TAG, "Entering OCDoResponse");
3666 // Validate input parameters
3667 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3668 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3671 // Get pointer to request info
3672 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3675 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3676 result = serverRequest->ehResponseHandler(ehResponse);
3682 //-----------------------------------------------------------------------------
3683 // Private internal function definitions
3684 //-----------------------------------------------------------------------------
3685 static OCDoHandle GenerateInvocationHandle()
3687 OCDoHandle handle = NULL;
3688 // Generate token here, it will be deleted when the transaction is deleted
3689 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3692 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3698 #ifdef WITH_PRESENCE
3699 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3700 OCResourceProperty resourceProperties, uint8_t enable)
3704 return OC_STACK_INVALID_PARAM;
3706 if (resourceProperties
3707 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3709 OC_LOG(ERROR, TAG, "Invalid property");
3710 return OC_STACK_INVALID_PARAM;
3714 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3718 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3724 OCStackResult initResources()
3726 OCStackResult result = OC_STACK_OK;
3728 headResource = NULL;
3729 tailResource = NULL;
3730 // Init Virtual Resources
3731 #ifdef WITH_PRESENCE
3732 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3734 result = OCCreateResource(&presenceResource.handle,
3735 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3737 OC_RSRVD_PRESENCE_URI,
3741 //make resource inactive
3742 result = OCChangeResourceProperty(
3743 &(((OCResource *) presenceResource.handle)->resourceProperties),
3747 if (result == OC_STACK_OK)
3749 result = SRMInitSecureResources();
3755 void insertResource(OCResource *resource)
3759 headResource = resource;
3760 tailResource = resource;
3764 tailResource->next = resource;
3765 tailResource = resource;
3767 resource->next = NULL;
3770 OCResource *findResource(OCResource *resource)
3772 OCResource *pointer = headResource;
3776 if (pointer == resource)
3780 pointer = pointer->next;
3785 void deleteAllResources()
3787 OCResource *pointer = headResource;
3788 OCResource *temp = NULL;
3792 temp = pointer->next;
3793 #ifdef WITH_PRESENCE
3794 if (pointer != (OCResource *) presenceResource.handle)
3796 #endif // WITH_PRESENCE
3797 deleteResource(pointer);
3798 #ifdef WITH_PRESENCE
3800 #endif // WITH_PRESENCE
3804 SRMDeInitSecureResources();
3806 #ifdef WITH_PRESENCE
3807 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3808 // presence notification attributed to their deletion to be processed.
3809 deleteResource((OCResource *) presenceResource.handle);
3810 #endif // WITH_PRESENCE
3813 OCStackResult deleteResource(OCResource *resource)
3815 OCResource *prev = NULL;
3816 OCResource *temp = NULL;
3819 OC_LOG(DEBUG,TAG,"resource is NULL");
3820 return OC_STACK_INVALID_PARAM;
3823 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3825 temp = headResource;
3828 if (temp == resource)
3830 // Invalidate all Resource Properties.
3831 resource->resourceProperties = (OCResourceProperty) 0;
3832 #ifdef WITH_PRESENCE
3833 if(resource != (OCResource *) presenceResource.handle)
3835 #endif // WITH_PRESENCE
3836 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3837 #ifdef WITH_PRESENCE
3840 if(presenceResource.handle)
3842 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3843 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3846 // Only resource in list.
3847 if (temp == headResource && temp == tailResource)
3849 headResource = NULL;
3850 tailResource = NULL;
3853 else if (temp == headResource)
3855 headResource = temp->next;
3858 else if (temp == tailResource)
3860 tailResource = prev;
3861 tailResource->next = NULL;
3865 prev->next = temp->next;
3868 deleteResourceElements(temp);
3879 return OC_STACK_ERROR;
3882 void deleteResourceElements(OCResource *resource)
3889 OICFree(resource->uri);
3890 deleteResourceType(resource->rsrcType);
3891 deleteResourceInterface(resource->rsrcInterface);
3894 void deleteResourceType(OCResourceType *resourceType)
3896 OCResourceType *pointer = resourceType;
3897 OCResourceType *next = NULL;
3901 next = pointer->next;
3902 OICFree(pointer->resourcetypename);
3908 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3910 OCResourceInterface *pointer = resourceInterface;
3911 OCResourceInterface *next = NULL;
3915 next = pointer->next;
3916 OICFree(pointer->name);
3922 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3924 OCResourceType *pointer = NULL;
3925 OCResourceType *previous = NULL;
3926 if (!resource || !resourceType)
3930 // resource type list is empty.
3931 else if (!resource->rsrcType)
3933 resource->rsrcType = resourceType;
3937 pointer = resource->rsrcType;
3941 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3943 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3944 OICFree(resourceType->resourcetypename);
3945 OICFree(resourceType);
3949 pointer = pointer->next;
3951 previous->next = resourceType;
3953 resourceType->next = NULL;
3955 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3958 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3960 OCResource *resource = NULL;
3961 OCResourceType *pointer = NULL;
3963 // Find the specified resource
3964 resource = findResource((OCResource *) handle);
3970 // Make sure a resource has a resourcetype
3971 if (!resource->rsrcType)
3976 // Iterate through the list
3977 pointer = resource->rsrcType;
3978 for(uint8_t i = 0; i< index && pointer; ++i)
3980 pointer = pointer->next;
3985 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
3987 if(resourceTypeList && resourceTypeName)
3989 OCResourceType * rtPointer = resourceTypeList;
3990 while(resourceTypeName && rtPointer)
3992 if(rtPointer->resourcetypename &&
3993 strcmp(resourceTypeName, (const char *)
3994 (rtPointer->resourcetypename)) == 0)
3998 rtPointer = rtPointer->next;
4006 * Insert a new interface into interface linked list only if not already present.
4007 * If alredy present, 2nd arg is free'd.
4008 * Default interface will always be first if present.
4010 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4012 OCResourceInterface *pointer = NULL;
4013 OCResourceInterface *previous = NULL;
4015 newInterface->next = NULL;
4017 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4019 if (!*firstInterface)
4021 *firstInterface = newInterface;
4023 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4025 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4027 OICFree(newInterface->name);
4028 OICFree(newInterface);
4033 newInterface->next = *firstInterface;
4034 *firstInterface = newInterface;
4039 pointer = *firstInterface;
4042 if (strcmp(newInterface->name, pointer->name) == 0)
4044 OICFree(newInterface->name);
4045 OICFree(newInterface);
4049 pointer = pointer->next;
4051 previous->next = newInterface;
4055 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4058 OCResource *resource = NULL;
4059 OCResourceInterface *pointer = NULL;
4061 // Find the specified resource
4062 resource = findResource((OCResource *) handle);
4068 // Make sure a resource has a resourceinterface
4069 if (!resource->rsrcInterface)
4074 // Iterate through the list
4075 pointer = resource->rsrcInterface;
4077 for (uint8_t i = 0; i < index && pointer; ++i)
4079 pointer = pointer->next;
4085 * This function splits the uri using the '?' delimiter.
4086 * "uriWithoutQuery" is the block of characters between the beginning
4087 * till the delimiter or '\0' which ever comes first.
4088 * "query" is whatever is to the right of the delimiter if present.
4089 * No delimiter sets the query to NULL.
4090 * If either are present, they will be malloc'ed into the params 2, 3.
4091 * The first param, *uri is left untouched.
4093 * NOTE: This function does not account for whitespace at the end of the uri NOR
4094 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4095 * part of the query.
4097 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4101 return OC_STACK_INVALID_URI;
4103 if(!query || !uriWithoutQuery)
4105 return OC_STACK_INVALID_PARAM;
4109 *uriWithoutQuery = NULL;
4111 size_t uriWithoutQueryLen = 0;
4112 size_t queryLen = 0;
4113 size_t uriLen = strlen(uri);
4115 char *pointerToDelimiter = strstr(uri, "?");
4117 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4118 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4120 if (uriWithoutQueryLen)
4122 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4123 if (!*uriWithoutQuery)
4127 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4131 *query = (char *) OICCalloc(queryLen + 1, 1);
4134 OICFree(*uriWithoutQuery);
4135 *uriWithoutQuery = NULL;
4138 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4144 return OC_STACK_NO_MEMORY;
4147 const OicUuid_t* OCGetServerInstanceID(void)
4149 static bool generated = false;
4150 static OicUuid_t sid;
4156 if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4158 OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4165 const char* OCGetServerInstanceIDString(void)
4167 static bool generated = false;
4168 static char sidStr[UUID_STRING_SIZE];
4175 const OicUuid_t* sid = OCGetServerInstanceID();
4177 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4179 OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4187 CAResult_t OCSelectNetwork()
4189 CAResult_t retResult = CA_STATUS_FAILED;
4190 CAResult_t caResult = CA_STATUS_OK;
4192 CATransportAdapter_t connTypes[] = {
4194 CA_ADAPTER_RFCOMM_BTEDR,
4195 CA_ADAPTER_GATT_BTLE
4198 ,CA_ADAPTER_REMOTE_ACCESS
4201 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4203 for(int i = 0; i<numConnTypes; i++)
4205 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4206 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4208 caResult = CASelectNetwork(connTypes[i]);
4209 if(caResult == CA_STATUS_OK)
4211 retResult = CA_STATUS_OK;
4216 if(retResult != CA_STATUS_OK)
4218 return caResult; // Returns error of appropriate transport that failed fatally.
4224 OCStackResult CAResultToOCResult(CAResult_t caResult)
4230 case CA_STATUS_INVALID_PARAM:
4231 return OC_STACK_INVALID_PARAM;
4232 case CA_ADAPTER_NOT_ENABLED:
4233 return OC_STACK_ADAPTER_NOT_ENABLED;
4234 case CA_SERVER_STARTED_ALREADY:
4236 case CA_SERVER_NOT_STARTED:
4237 return OC_STACK_ERROR;
4238 case CA_DESTINATION_NOT_REACHABLE:
4239 return OC_STACK_COMM_ERROR;
4240 case CA_SOCKET_OPERATION_FAILED:
4241 return OC_STACK_COMM_ERROR;
4242 case CA_SEND_FAILED:
4243 return OC_STACK_COMM_ERROR;
4244 case CA_RECEIVE_FAILED:
4245 return OC_STACK_COMM_ERROR;
4246 case CA_MEMORY_ALLOC_FAILED:
4247 return OC_STACK_NO_MEMORY;
4248 case CA_REQUEST_TIMEOUT:
4249 return OC_STACK_TIMEOUT;
4250 case CA_DESTINATION_DISCONNECTED:
4251 return OC_STACK_COMM_ERROR;
4252 case CA_STATUS_FAILED:
4253 return OC_STACK_ERROR;
4254 case CA_NOT_SUPPORTED:
4255 return OC_STACK_NOTIMPL;
4257 return OC_STACK_ERROR;