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;
102 static OCResourceHandle platformResource = {0};
103 static OCResourceHandle deviceResource = {0};
105 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
106 static PresenceResource presenceResource;
107 static uint8_t PresenceTimeOutSize = 0;
108 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
111 static OCMode myStackMode;
113 //TODO: revisit this design
114 static bool gRASetInfo = false;
116 OCDeviceEntityHandler defaultDeviceHandler;
117 void* defaultDeviceHandlerCallbackParameter = NULL;
118 static const char COAP_TCP[] = "coap+tcp:";
120 //-----------------------------------------------------------------------------
122 //-----------------------------------------------------------------------------
123 #define TAG "OCStack"
124 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
125 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
126 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
127 TAG, #arg " is NULL"); return (retVal); } }
128 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
129 TAG, #arg " is NULL"); return; } }
130 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL");\
133 //TODO: we should allow the server to define this
134 #define MAX_OBSERVE_AGE (0x2FFFFUL)
136 #define MILLISECONDS_PER_SECOND (1000)
138 //-----------------------------------------------------------------------------
139 // Private internal function prototypes
140 //-----------------------------------------------------------------------------
143 * Generate handle of OCDoResource invocation for callback management.
145 * @return Generated OCDoResource handle.
147 static OCDoHandle GenerateInvocationHandle();
150 * Initialize resource data structures, variables, etc.
152 * @return ::OC_STACK_OK on success, some other value upon failure.
154 static OCStackResult initResources();
157 * Add a resource to the end of the linked list of resources.
159 * @param resource Resource to be added
161 static void insertResource(OCResource *resource);
164 * Find a resource in the linked list of resources.
166 * @param resource Resource to be found.
167 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
170 static OCResource *findResource(OCResource *resource);
173 * Insert a resource type into a resource's resource type linked list.
174 * If resource type already exists, it will not be inserted and the
175 * resourceType will be free'd.
176 * resourceType->next should be null to avoid memory leaks.
177 * Function returns silently for null args.
179 * @param resource Resource where resource type is to be inserted.
180 * @param resourceType Resource type to be inserted.
182 static void insertResourceType(OCResource *resource,
183 OCResourceType *resourceType);
186 * Get a resource type at the specified index within a resource.
188 * @param handle Handle of resource.
189 * @param index Index of resource type.
191 * @return Pointer to resource type if found, NULL otherwise.
193 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
197 * Insert a resource interface into a resource's resource interface linked list.
198 * If resource interface already exists, it will not be inserted and the
199 * resourceInterface will be free'd.
200 * resourceInterface->next should be null to avoid memory leaks.
202 * @param resource Resource where resource interface is to be inserted.
203 * @param resourceInterface Resource interface to be inserted.
205 static void insertResourceInterface(OCResource *resource,
206 OCResourceInterface *resourceInterface);
209 * Get a resource interface at the specified index within a resource.
211 * @param handle Handle of resource.
212 * @param index Index of resource interface.
214 * @return Pointer to resource interface if found, NULL otherwise.
216 static OCResourceInterface *findResourceInterfaceAtIndex(
217 OCResourceHandle handle, uint8_t index);
220 * Delete all of the dynamically allocated elements that were created for the resource type.
222 * @param resourceType Specified resource type.
224 static void deleteResourceType(OCResourceType *resourceType);
227 * Delete all of the dynamically allocated elements that were created for the resource interface.
229 * @param resourceInterface Specified resource interface.
231 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
234 * Delete all of the dynamically allocated elements that were created for the resource.
236 * @param resource Specified resource.
238 static void deleteResourceElements(OCResource *resource);
241 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
244 * @param handle Handle of resource to be deleted.
246 * @return ::OC_STACK_OK on success, some other value upon failure.
248 static OCStackResult deleteResource(OCResource *resource);
251 * Delete all of the resources in the resource list.
253 static void deleteAllResources();
256 * Increment resource sequence number. Handles rollover.
258 * @param resPtr Pointer to resource.
260 static void incrementSequenceNumber(OCResource * resPtr);
263 * Verify the lengths of the URI and the query separately.
265 * @param inputUri Input URI and query.
266 * @param uriLen The length of the initial URI with query.
267 * @return ::OC_STACK_OK on success, some other value upon failure.
269 static OCStackResult verifyUriQueryLength(const char * inputUri,
273 * Attempts to initialize every network interface that the CA Layer might have compiled in.
275 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
276 * return something other than @ref CA_STATUS_OK, then this function fails.
278 * @return ::CA_STATUS_OK on success, some other value upon failure.
280 static CAResult_t OCSelectNetwork();
283 * Get the CoAP ticks after the specified number of milli-seconds.
285 * @param afterMilliSeconds Milli-seconds.
289 static uint32_t GetTicks(uint32_t afterMilliSeconds);
292 * Convert CAResponseResult_t to OCStackResult.
294 * @param caCode CAResponseResult_t code.
295 * @return ::OC_STACK_OK on success, some other value upon failure.
297 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
300 * Convert OCStackResult to CAResponseResult_t.
302 * @param caCode OCStackResult code.
303 * @param method OCMethod method the return code replies to.
304 * @return ::CA_CONTENT on OK, some other value upon failure.
306 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
309 * Convert OCTransportFlags_t to CATransportModifiers_t.
311 * @param ocConType OCTransportFlags_t input.
312 * @return CATransportFlags
314 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
317 * Convert CATransportFlags_t to OCTransportModifiers_t.
319 * @param caConType CATransportFlags_t input.
320 * @return OCTransportFlags
322 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
325 * Handle response from presence request.
327 * @param endPoint CA remote endpoint.
328 * @param responseInfo CA response info.
329 * @return ::OC_STACK_OK on success, some other value upon failure.
331 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
332 const CAResponseInfo_t *responseInfo);
335 * This function will be called back by CA layer when a response is received.
337 * @param endPoint CA remote endpoint.
338 * @param responseInfo CA response info.
340 static void HandleCAResponses(const CAEndpoint_t* endPoint,
341 const CAResponseInfo_t* responseInfo);
344 * This function will be called back by CA layer when a request is received.
346 * @param endPoint CA remote endpoint.
347 * @param requestInfo CA request info.
349 static void HandleCARequests(const CAEndpoint_t* endPoint,
350 const CARequestInfo_t* requestInfo);
353 * Extract query from a URI.
355 * @param uri Full URI with query.
356 * @param query Pointer to string that will contain query.
357 * @param newURI Pointer to string that will contain URI.
358 * @return ::OC_STACK_OK on success, some other value upon failure.
360 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
363 * Finds a resource type in an OCResourceType link-list.
365 * @param resourceTypeList The link-list to be searched through.
366 * @param resourceTypeName The key to search for.
368 * @return Resource type that matches the key (ie. resourceTypeName) or
369 * NULL if there is either an invalid parameter or this function was unable to find the key.
371 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
372 const char * resourceTypeName);
375 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
376 * TTL will be set to maxAge.
378 * @param cbNode Callback Node for which presence ttl is to be reset.
379 * @param maxAge New value of ttl in seconds.
381 * @return ::OC_STACK_OK on success, some other value upon failure.
383 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
386 * Ensure the accept header option is set appropriatly before sending the requests and routing
387 * header option is updated with destination.
389 * @param object CA remote endpoint.
390 * @param requestInfo CA request info.
392 * @return ::OC_STACK_OK on success, some other value upon failure.
394 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
396 //-----------------------------------------------------------------------------
397 // Internal functions
398 //-----------------------------------------------------------------------------
400 uint32_t GetTicks(uint32_t afterMilliSeconds)
405 // Guard against overflow of uint32_t
406 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
407 COAP_TICKS_PER_SECOND)
409 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
417 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
419 VERIFY_NON_NULL_NR(in, FATAL);
420 VERIFY_NON_NULL_NR(out, FATAL);
422 out->adapter = (OCTransportAdapter)in->adapter;
423 out->flags = CAToOCTransportFlags(in->flags);
424 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
425 out->port = in->port;
426 out->interface = in->interface;
427 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
428 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
432 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
434 VERIFY_NON_NULL_NR(in, FATAL);
435 VERIFY_NON_NULL_NR(out, FATAL);
437 out->adapter = (CATransportAdapter_t)in->adapter;
438 out->flags = OCToCATransportFlags(in->flags);
439 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
440 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
441 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
443 out->port = in->port;
444 out->interface = in->interface;
447 void FixUpClientResponse(OCClientResponse *cr)
449 VERIFY_NON_NULL_NR(cr, FATAL);
451 cr->addr = &cr->devAddr;
452 cr->connType = (OCConnectivityType)
453 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
456 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
458 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
459 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
461 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
462 OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
463 &(requestInfo->info.numOptions));
464 if (OC_STACK_OK != rmResult)
466 OC_LOG(ERROR, TAG, "Add destination option failed");
471 // OC stack prefer CBOR encoded payloads.
472 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
473 CAResult_t result = CASendRequest(object, requestInfo);
474 if(CA_STATUS_OK != result)
476 OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
477 return CAResultToOCResult(result);
481 //-----------------------------------------------------------------------------
482 // Internal API function
483 //-----------------------------------------------------------------------------
485 // This internal function is called to update the stack with the status of
486 // observers and communication failures
487 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
489 OCStackResult result = OC_STACK_ERROR;
490 ResourceObserver * observer = NULL;
491 OCEntityHandlerRequest ehRequest = {0};
495 case OC_OBSERVER_NOT_INTERESTED:
496 OC_LOG(DEBUG, TAG, "observer not interested in our notifications");
497 observer = GetObserverUsingToken (token, tokenLength);
500 result = FormOCEntityHandlerRequest(&ehRequest,
501 (OCRequestHandle)NULL,
504 (OCResourceHandle)NULL,
505 NULL, PAYLOAD_TYPE_REPRESENTATION,
507 OC_OBSERVE_DEREGISTER,
508 observer->observeId);
509 if(result != OC_STACK_OK)
513 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
514 observer->resource->entityHandlerCallbackParam);
517 result = DeleteObserverUsingToken (token, tokenLength);
518 if(result == OC_STACK_OK)
520 OC_LOG(DEBUG, TAG, "Removed observer successfully");
524 result = OC_STACK_OK;
525 OC_LOG(DEBUG, TAG, "Observer Removal failed");
529 case OC_OBSERVER_STILL_INTERESTED:
530 OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
531 observer = GetObserverUsingToken (token, tokenLength);
534 observer->forceHighQos = 0;
535 observer->failedCommCount = 0;
536 result = OC_STACK_OK;
540 result = OC_STACK_OBSERVER_NOT_FOUND;
544 case OC_OBSERVER_FAILED_COMM:
545 OC_LOG(DEBUG, TAG, "observer is unreachable");
546 observer = GetObserverUsingToken (token, tokenLength);
549 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
551 result = FormOCEntityHandlerRequest(&ehRequest,
552 (OCRequestHandle)NULL,
555 (OCResourceHandle)NULL,
556 NULL, PAYLOAD_TYPE_REPRESENTATION,
558 OC_OBSERVE_DEREGISTER,
559 observer->observeId);
560 if(result != OC_STACK_OK)
562 return OC_STACK_ERROR;
564 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
565 observer->resource->entityHandlerCallbackParam);
567 result = DeleteObserverUsingToken (token, tokenLength);
568 if(result == OC_STACK_OK)
570 OC_LOG(DEBUG, TAG, "Removed observer successfully");
574 result = OC_STACK_OK;
575 OC_LOG(DEBUG, TAG, "Observer Removal failed");
580 observer->failedCommCount++;
581 result = OC_STACK_CONTINUE;
583 observer->forceHighQos = 1;
584 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
588 OC_LOG(ERROR, TAG, "Unknown status");
589 result = OC_STACK_ERROR;
594 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
596 OCStackResult ret = OC_STACK_ERROR;
601 ret = OC_STACK_RESOURCE_CREATED;
604 ret = OC_STACK_RESOURCE_DELETED;
611 ret = OC_STACK_INVALID_QUERY;
613 case CA_UNAUTHORIZED_REQ:
614 ret = OC_STACK_UNAUTHORIZED_REQ;
617 ret = OC_STACK_INVALID_OPTION;
620 ret = OC_STACK_NO_RESOURCE;
622 case CA_RETRANSMIT_TIMEOUT:
623 ret = OC_STACK_COMM_ERROR;
631 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
633 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
642 // This Response Code is like HTTP 204 "No Content" but only used in
643 // response to POST and PUT requests.
647 // This Response Code is like HTTP 200 "OK" but only used in response to
652 // This should not happen but,
653 // give it a value just in case but output an error
655 OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
658 case OC_STACK_RESOURCE_CREATED:
661 case OC_STACK_RESOURCE_DELETED:
664 case OC_STACK_INVALID_QUERY:
667 case OC_STACK_INVALID_OPTION:
670 case OC_STACK_NO_RESOURCE:
673 case OC_STACK_COMM_ERROR:
674 ret = CA_RETRANSMIT_TIMEOUT;
676 case OC_STACK_UNAUTHORIZED_REQ:
677 ret = CA_UNAUTHORIZED_REQ;
685 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
687 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
689 // supply default behavior.
690 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
692 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
694 if ((caFlags & OC_MASK_SCOPE) == 0)
696 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
701 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
703 return (OCTransportFlags)caFlags;
706 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
708 uint32_t lowerBound = 0;
709 uint32_t higherBound = 0;
711 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
713 return OC_STACK_INVALID_PARAM;
716 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
718 cbNode->presence->TTL = maxAgeSeconds;
720 for (int index = 0; index < PresenceTimeOutSize; index++)
722 // Guard against overflow
723 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
726 lowerBound = GetTicks((PresenceTimeOut[index] *
727 cbNode->presence->TTL *
728 MILLISECONDS_PER_SECOND)/100);
732 lowerBound = GetTicks(UINT32_MAX);
735 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
738 higherBound = GetTicks((PresenceTimeOut[index + 1] *
739 cbNode->presence->TTL *
740 MILLISECONDS_PER_SECOND)/100);
744 higherBound = GetTicks(UINT32_MAX);
747 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
749 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
750 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
751 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
754 cbNode->presence->TTLlevel = 0;
756 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
760 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
762 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
764 return OC_RSRVD_TRIGGER_CREATE;
766 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
768 return OC_RSRVD_TRIGGER_CHANGE;
772 return OC_RSRVD_TRIGGER_DELETE;
776 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
780 return OC_PRESENCE_TRIGGER_CREATE;
782 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
784 return OC_PRESENCE_TRIGGER_CREATE;
786 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
788 return OC_PRESENCE_TRIGGER_CHANGE;
792 return OC_PRESENCE_TRIGGER_DELETE;
797 * The cononical presence allows constructed URIs to be string compared.
799 * requestUri must be a char array of size CA_MAX_URI_LENGTH
801 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
804 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
805 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
806 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
808 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
810 if (ep->adapter == CA_ADAPTER_IP)
812 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
814 if ('\0' == ep->addr[0]) // multicast
816 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
820 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
821 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
826 if ('\0' == ep->addr[0]) // multicast
828 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
829 ep->port = OC_MULTICAST_PORT;
831 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
832 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
836 // might work for other adapters (untested, but better than nothing)
837 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
838 OC_RSRVD_PRESENCE_URI);
842 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
843 const CAResponseInfo_t *responseInfo)
845 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
846 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
848 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
849 ClientCB * cbNode = NULL;
850 char *resourceTypeName = NULL;
851 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
852 OCStackResult result = OC_STACK_ERROR;
855 char presenceUri[CA_MAX_URI_LENGTH];
857 int presenceSubscribe = 0;
858 int multicastPresenceSubscribe = 0;
860 if (responseInfo->result != CA_CONTENT)
862 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
863 return OC_STACK_ERROR;
866 // check for unicast presence
867 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
868 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
870 return OC_STACK_INVALID_URI;
873 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
876 presenceSubscribe = 1;
880 // check for multiicast presence
881 CAEndpoint_t ep = { .adapter = endpoint->adapter,
882 .flags = endpoint->flags };
884 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
886 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
889 multicastPresenceSubscribe = 1;
893 if (!presenceSubscribe && !multicastPresenceSubscribe)
895 OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
899 response.payload = NULL;
900 response.result = OC_STACK_OK;
902 CopyEndpointToDevAddr(endpoint, &response.devAddr);
903 FixUpClientResponse(&response);
905 if (responseInfo->info.payload)
907 result = OCParsePayload(&response.payload,
908 PAYLOAD_TYPE_PRESENCE,
909 responseInfo->info.payload,
910 responseInfo->info.payloadSize);
912 if(result != OC_STACK_OK)
914 OC_LOG(ERROR, TAG, "Presence parse failed");
917 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
919 OC_LOG(ERROR, TAG, "Presence payload was wrong type");
920 result = OC_STACK_ERROR;
923 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
924 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
925 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
928 if (presenceSubscribe)
930 if(cbNode->sequenceNumber == response.sequenceNumber)
932 OC_LOG(INFO, TAG, "No presence change");
933 ResetPresenceTTL(cbNode, maxAge);
934 OC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
940 OC_LOG(INFO, TAG, "Stopping presence");
941 response.result = OC_STACK_PRESENCE_STOPPED;
944 OICFree(cbNode->presence->timeOut);
945 OICFree(cbNode->presence);
946 cbNode->presence = NULL;
951 if(!cbNode->presence)
953 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
955 if(!(cbNode->presence))
957 OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
958 result = OC_STACK_NO_MEMORY;
962 VERIFY_NON_NULL_V(cbNode->presence);
963 cbNode->presence->timeOut = NULL;
964 cbNode->presence->timeOut = (uint32_t *)
965 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
966 if(!(cbNode->presence->timeOut)){
968 "Could not allocate memory for cbNode->presence->timeOut");
969 OICFree(cbNode->presence);
970 result = OC_STACK_NO_MEMORY;
975 ResetPresenceTTL(cbNode, maxAge);
977 cbNode->sequenceNumber = response.sequenceNumber;
979 // Ensure that a filter is actually applied.
980 if( resourceTypeName && cbNode->filterResourceType)
982 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
991 // This is the multicast case
992 OCMulticastNode* mcNode = NULL;
993 mcNode = GetMCPresenceNode(presenceUri);
997 if(mcNode->nonce == response.sequenceNumber)
999 OC_LOG(INFO, TAG, "No presence change (Multicast)");
1002 mcNode->nonce = response.sequenceNumber;
1006 OC_LOG(INFO, TAG, "Stopping presence");
1007 response.result = OC_STACK_PRESENCE_STOPPED;
1012 char* uri = OICStrdup(presenceUri);
1016 "No Memory for URI to store in the presence node");
1017 result = OC_STACK_NO_MEMORY;
1021 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1022 if(result == OC_STACK_NO_MEMORY)
1025 "No Memory for Multicast Presence Node");
1029 // presence node now owns uri
1032 // Ensure that a filter is actually applied.
1033 if(resourceTypeName && cbNode->filterResourceType)
1035 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1042 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1044 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1046 FindAndDeleteClientCB(cbNode);
1050 OCPayloadDestroy(response.payload);
1054 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1056 VERIFY_NON_NULL_NR(endPoint, FATAL);
1057 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1059 OC_LOG(INFO, TAG, "Enter HandleCAResponses");
1061 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1062 #ifdef ROUTING_GATEWAY
1063 bool needRIHandling = false;
1065 * Routing manager is going to update either of endpoint or response or both.
1066 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1067 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1070 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1072 if(ret != OC_STACK_OK || !needRIHandling)
1074 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1080 * Put source in sender endpoint so that the next packet from application can be routed to
1081 * proper destination and remove "RM" coap header option before passing request / response to
1082 * RI as this option will make no sense to either RI or application.
1084 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1085 (uint8_t *) &(responseInfo->info.numOptions),
1086 (CAEndpoint_t *) endPoint);
1089 if(responseInfo->info.resourceUri &&
1090 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1092 HandlePresenceResponse(endPoint, responseInfo);
1096 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1097 responseInfo->info.tokenLength, NULL, NULL);
1099 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1100 responseInfo->info.tokenLength);
1104 OC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1105 if(responseInfo->result == CA_EMPTY)
1107 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1108 // We do not have a case for the client to receive a RESET
1109 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1111 //This is the case of receiving an ACK on a request to a slow resource!
1112 OC_LOG(INFO, TAG, "This is a pure ACK");
1113 //TODO: should we inform the client
1114 // app that at least the request was received at the server?
1117 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1119 OC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1120 OC_LOG(INFO, TAG, "Calling into application address space");
1122 OCClientResponse response =
1123 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1124 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1125 FixUpClientResponse(&response);
1126 response.resourceUri = responseInfo->info.resourceUri;
1127 memcpy(response.identity.id, responseInfo->info.identity.id,
1128 sizeof (response.identity.id));
1129 response.identity.id_length = responseInfo->info.identity.id_length;
1131 response.result = CAToOCStackResult(responseInfo->result);
1132 cbNode->callBack(cbNode->context,
1133 cbNode->handle, &response);
1134 FindAndDeleteClientCB(cbNode);
1138 OC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1139 OC_LOG(INFO, TAG, "Calling into application address space");
1141 OCClientResponse response =
1142 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1143 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1144 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1145 FixUpClientResponse(&response);
1146 response.resourceUri = responseInfo->info.resourceUri;
1147 memcpy(response.identity.id, responseInfo->info.identity.id,
1148 sizeof (response.identity.id));
1149 response.identity.id_length = responseInfo->info.identity.id_length;
1151 response.result = CAToOCStackResult(responseInfo->result);
1153 if(responseInfo->info.payload &&
1154 responseInfo->info.payloadSize)
1156 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1157 // check the security resource
1158 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1160 type = PAYLOAD_TYPE_SECURITY;
1162 else if (cbNode->method == OC_REST_DISCOVER)
1164 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1165 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1167 type = PAYLOAD_TYPE_DISCOVERY;
1169 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1171 type = PAYLOAD_TYPE_DEVICE;
1173 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1175 type = PAYLOAD_TYPE_PLATFORM;
1177 #ifdef ROUTING_GATEWAY
1178 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1180 type = PAYLOAD_TYPE_REPRESENTATION;
1183 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1185 type = PAYLOAD_TYPE_RD;
1189 OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1190 cbNode->method, cbNode->requestUri);
1194 else if (cbNode->method == OC_REST_GET ||
1195 cbNode->method == OC_REST_PUT ||
1196 cbNode->method == OC_REST_POST ||
1197 cbNode->method == OC_REST_OBSERVE ||
1198 cbNode->method == OC_REST_OBSERVE_ALL ||
1199 cbNode->method == OC_REST_DELETE)
1201 char targetUri[MAX_URI_LENGTH];
1202 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
1203 OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1204 if (strcmp(targetUri, cbNode->requestUri) == 0)
1206 type = PAYLOAD_TYPE_RD;
1208 if (type == PAYLOAD_TYPE_INVALID)
1210 OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1211 cbNode->method, cbNode->requestUri);
1212 type = PAYLOAD_TYPE_REPRESENTATION;
1217 OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1218 cbNode->method, cbNode->requestUri);
1222 if(OC_STACK_OK != OCParsePayload(&response.payload,
1224 responseInfo->info.payload,
1225 responseInfo->info.payloadSize))
1227 OC_LOG(ERROR, TAG, "Error converting payload");
1228 OCPayloadDestroy(response.payload);
1233 response.numRcvdVendorSpecificHeaderOptions = 0;
1234 if(responseInfo->info.numOptions > 0)
1237 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1238 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1241 uint32_t observationOption;
1242 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1243 for (observationOption=0, i=0;
1244 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1248 (observationOption << 8) | optionData[i];
1250 response.sequenceNumber = observationOption;
1252 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1257 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1260 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1262 OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1263 OCPayloadDestroy(response.payload);
1267 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1269 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1270 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1274 if (cbNode->method == OC_REST_OBSERVE &&
1275 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1276 response.sequenceNumber <= cbNode->sequenceNumber)
1278 OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1279 response.sequenceNumber);
1283 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1286 cbNode->sequenceNumber = response.sequenceNumber;
1288 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1290 FindAndDeleteClientCB(cbNode);
1294 // To keep discovery callbacks active.
1295 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1296 MILLISECONDS_PER_SECOND);
1300 //Need to send ACK when the response is CON
1301 if(responseInfo->info.type == CA_MSG_CONFIRM)
1303 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1304 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1307 OCPayloadDestroy(response.payload);
1314 OC_LOG(INFO, TAG, "There is an observer associated with the response token");
1315 if(responseInfo->result == CA_EMPTY)
1317 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1318 if(responseInfo->info.type == CA_MSG_RESET)
1320 OC_LOG(INFO, TAG, "This is a RESET");
1321 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1322 OC_OBSERVER_NOT_INTERESTED);
1324 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1326 OC_LOG(INFO, TAG, "This is a pure ACK");
1327 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1328 OC_OBSERVER_STILL_INTERESTED);
1331 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1333 OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1334 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1335 OC_OBSERVER_FAILED_COMM);
1340 if(!cbNode && !observer)
1342 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1343 || myStackMode == OC_GATEWAY)
1345 OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1346 if(responseInfo->result == CA_EMPTY)
1348 OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1352 OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1353 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1354 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1358 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1359 || myStackMode == OC_GATEWAY)
1361 OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1362 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1364 OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1365 responseInfo->info.messageId);
1367 if (responseInfo->info.type == CA_MSG_RESET)
1369 OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1370 responseInfo->info.messageId);
1377 OC_LOG(INFO, TAG, "Exit HandleCAResponses");
1381 * This function handles error response from CA
1382 * code shall be added to handle the errors
1384 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1386 OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1388 if(NULL == endPoint)
1390 OC_LOG(ERROR, TAG, "endPoint is NULL");
1394 if(NULL == errrorInfo)
1396 OC_LOG(ERROR, TAG, "errrorInfo is NULL");
1399 OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1403 * This function sends out Direct Stack Responses. These are responses that are not coming
1404 * from the application entity handler. These responses have no payload and are usually ACKs,
1405 * RESETs or some error conditions that were caught by the stack.
1407 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1408 const CAResponseResult_t responseResult, const CAMessageType_t type,
1409 const uint8_t numOptions, const CAHeaderOption_t *options,
1410 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1412 CAResponseInfo_t respInfo = {
1413 .result = responseResult
1415 respInfo.info.messageId = coapID;
1416 respInfo.info.numOptions = numOptions;
1418 if (respInfo.info.numOptions)
1420 respInfo.info.options =
1421 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1422 memcpy (respInfo.info.options, options,
1423 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1427 respInfo.info.payload = NULL;
1428 respInfo.info.token = token;
1429 respInfo.info.tokenLength = tokenLength;
1430 respInfo.info.type = type;
1431 respInfo.info.resourceUri = OICStrdup (resourceUri);
1432 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1434 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1435 // Add the destination to route option from the endpoint->routeData.
1436 OCStackResult result = RMAddInfo(endPoint->routeData,
1437 &(respInfo.info.options),
1438 &(respInfo.info.numOptions));
1439 if(OC_STACK_OK != result)
1441 OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1446 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1448 // resourceUri in the info field is cloned in the CA layer and
1449 // thus ownership is still here.
1450 OICFree (respInfo.info.resourceUri);
1451 OICFree (respInfo.info.options);
1452 if(CA_STATUS_OK != caResult)
1454 OC_LOG(ERROR, TAG, "CASendResponse error");
1455 return CAResultToOCResult(caResult);
1460 //This function will be called back by CA layer when a request is received
1461 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1463 OC_LOG(INFO, TAG, "Enter HandleCARequests");
1466 OC_LOG(ERROR, TAG, "endPoint is NULL");
1472 OC_LOG(ERROR, TAG, "requestInfo is NULL");
1476 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1477 #ifdef ROUTING_GATEWAY
1478 bool needRIHandling = false;
1480 * Routing manager is going to update either of endpoint or request or both.
1481 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1482 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1483 * destination. It can also remove "RM" coap header option before passing request / response to
1484 * RI as this option will make no sense to either RI or application.
1486 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1488 if(OC_STACK_OK != ret || !needRIHandling)
1490 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1496 * Put source in sender endpoint so that the next packet from application can be routed to
1497 * proper destination and remove RM header option.
1499 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1500 (uint8_t *) &(requestInfo->info.numOptions),
1501 (CAEndpoint_t *) endPoint);
1504 OCStackResult requestResult = OC_STACK_ERROR;
1506 if(myStackMode == OC_CLIENT)
1508 //TODO: should the client be responding to requests?
1512 OCServerProtocolRequest serverRequest = {0};
1514 OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1516 char * uriWithoutQuery = NULL;
1517 char * query = NULL;
1519 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1521 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1523 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1526 OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1527 OC_LOG_V(INFO, TAG, "Query : %s", query);
1529 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1531 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1532 OICFree(uriWithoutQuery);
1536 OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1537 OICFree(uriWithoutQuery);
1544 if(strlen(query) < MAX_QUERY_LENGTH)
1546 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1551 OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1557 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1559 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1560 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1561 memcpy (serverRequest.payload, requestInfo->info.payload,
1562 requestInfo->info.payloadSize);
1566 serverRequest.reqTotalSize = 0;
1569 switch (requestInfo->method)
1572 serverRequest.method = OC_REST_GET;
1575 serverRequest.method = OC_REST_PUT;
1578 serverRequest.method = OC_REST_POST;
1581 serverRequest.method = OC_REST_DELETE;
1584 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1585 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1586 requestInfo->info.type, requestInfo->info.numOptions,
1587 requestInfo->info.options, requestInfo->info.token,
1588 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1589 OICFree(serverRequest.payload);
1593 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1594 requestInfo->info.tokenLength);
1595 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1596 serverRequest.tokenLength = requestInfo->info.tokenLength;
1598 if (!serverRequest.requestToken)
1600 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1601 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1602 requestInfo->info.type, requestInfo->info.numOptions,
1603 requestInfo->info.options, requestInfo->info.token,
1604 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1605 OICFree(serverRequest.payload);
1608 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1610 switch (requestInfo->info.acceptFormat)
1612 case CA_FORMAT_APPLICATION_CBOR:
1613 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1615 case CA_FORMAT_UNDEFINED:
1616 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1619 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1622 if (requestInfo->info.type == CA_MSG_CONFIRM)
1624 serverRequest.qos = OC_HIGH_QOS;
1628 serverRequest.qos = OC_LOW_QOS;
1630 // CA does not need the following field
1631 // Are we sure CA does not need them? how is it responding to multicast
1632 serverRequest.delayedResNeeded = 0;
1634 serverRequest.coapID = requestInfo->info.messageId;
1636 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1638 // copy vendor specific header options
1639 uint8_t tempNum = (requestInfo->info.numOptions);
1641 // Assume no observation requested and it is a pure GET.
1642 // If obs registration/de-registration requested it'll be fetched from the
1643 // options in GetObserveHeaderOption()
1644 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1646 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1647 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1650 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1651 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1652 requestInfo->info.type, requestInfo->info.numOptions,
1653 requestInfo->info.options, requestInfo->info.token,
1654 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1655 OICFree(serverRequest.payload);
1656 OICFree(serverRequest.requestToken);
1659 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1660 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1662 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1663 sizeof(CAHeaderOption_t)*tempNum);
1666 requestResult = HandleStackRequests (&serverRequest);
1668 // Send ACK to client as precursor to slow response
1669 if(requestResult == OC_STACK_SLOW_RESOURCE)
1671 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1672 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1674 else if(requestResult != OC_STACK_OK)
1676 OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1678 CAResponseResult_t stackResponse =
1679 OCToCAStackResult(requestResult, serverRequest.method);
1681 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1682 requestInfo->info.type, requestInfo->info.numOptions,
1683 requestInfo->info.options, requestInfo->info.token,
1684 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1686 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1687 // The token is copied in there, and is thus still owned by this function.
1688 OICFree(serverRequest.payload);
1689 OICFree(serverRequest.requestToken);
1690 OC_LOG(INFO, TAG, "Exit HandleCARequests");
1693 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1695 OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1696 OCStackResult result = OC_STACK_ERROR;
1697 ResourceHandling resHandling;
1698 OCResource *resource;
1699 if(!protocolRequest)
1701 OC_LOG(ERROR, TAG, "protocolRequest is NULL");
1702 return OC_STACK_INVALID_PARAM;
1705 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1706 protocolRequest->tokenLength);
1709 OC_LOG(INFO, TAG, "This is a new Server Request");
1710 result = AddServerRequest(&request, protocolRequest->coapID,
1711 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1712 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1713 protocolRequest->observationOption, protocolRequest->qos,
1714 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1715 protocolRequest->payload, protocolRequest->requestToken,
1716 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1717 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1718 &protocolRequest->devAddr);
1719 if (OC_STACK_OK != result)
1721 OC_LOG(ERROR, TAG, "Error adding server request");
1727 OC_LOG(ERROR, TAG, "Out of Memory");
1728 return OC_STACK_NO_MEMORY;
1731 if(!protocolRequest->reqMorePacket)
1733 request->requestComplete = 1;
1738 OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1741 if(request->requestComplete)
1743 OC_LOG(INFO, TAG, "This Server Request is complete");
1744 result = DetermineResourceHandling (request, &resHandling, &resource);
1745 if (result == OC_STACK_OK)
1747 result = ProcessRequest(resHandling, resource, request);
1752 OC_LOG(INFO, TAG, "This Server Request is incomplete");
1753 result = OC_STACK_CONTINUE;
1758 bool validatePlatformInfo(OCPlatformInfo info)
1761 if (!info.platformID)
1763 OC_LOG(ERROR, TAG, "No platform ID found.");
1767 if (info.manufacturerName)
1769 size_t lenManufacturerName = strlen(info.manufacturerName);
1771 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1773 OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1779 OC_LOG(ERROR, TAG, "No manufacturer name present");
1783 if (info.manufacturerUrl)
1785 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1787 OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1794 //-----------------------------------------------------------------------------
1796 //-----------------------------------------------------------------------------
1798 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1801 !raInfo->username ||
1802 !raInfo->hostname ||
1803 !raInfo->xmpp_domain)
1806 return OC_STACK_INVALID_PARAM;
1808 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1809 gRASetInfo = (result == OC_STACK_OK)? true : false;
1815 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1819 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1822 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1824 if(stackState == OC_STACK_INITIALIZED)
1826 OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1827 OCStop() between them are ignored.");
1831 #ifndef ROUTING_GATEWAY
1832 if (OC_GATEWAY == mode)
1834 OC_LOG(ERROR, TAG, "Routing Manager not supported");
1835 return OC_STACK_INVALID_PARAM;
1842 OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1843 return OC_STACK_ERROR;
1847 OCStackResult result = OC_STACK_ERROR;
1848 OC_LOG(INFO, TAG, "Entering OCInit");
1851 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1852 || (mode == OC_GATEWAY)))
1854 OC_LOG(ERROR, TAG, "Invalid mode");
1855 return OC_STACK_ERROR;
1859 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1861 caglobals.client = true;
1863 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1865 caglobals.server = true;
1868 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1869 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1871 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1873 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1874 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1876 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1879 defaultDeviceHandler = NULL;
1880 defaultDeviceHandlerCallbackParameter = NULL;
1882 result = CAResultToOCResult(CAInitialize());
1883 VERIFY_SUCCESS(result, OC_STACK_OK);
1885 result = CAResultToOCResult(OCSelectNetwork());
1886 VERIFY_SUCCESS(result, OC_STACK_OK);
1888 switch (myStackMode)
1891 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1892 result = CAResultToOCResult(CAStartDiscoveryServer());
1893 OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1896 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1897 result = CAResultToOCResult(CAStartListeningServer());
1898 OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1900 case OC_CLIENT_SERVER:
1902 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1903 result = CAResultToOCResult(CAStartListeningServer());
1904 if(result == OC_STACK_OK)
1906 result = CAResultToOCResult(CAStartDiscoveryServer());
1910 VERIFY_SUCCESS(result, OC_STACK_OK);
1912 #ifdef WITH_PRESENCE
1913 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1914 #endif // WITH_PRESENCE
1916 //Update Stack state to initialized
1917 stackState = OC_STACK_INITIALIZED;
1919 // Initialize resource
1920 if(myStackMode != OC_CLIENT)
1922 result = initResources();
1925 // Initialize the SRM Policy Engine
1926 if(result == OC_STACK_OK)
1928 result = SRMInitPolicyEngine();
1929 // TODO after BeachHead delivery: consolidate into single SRMInit()
1932 #ifdef ROUTING_GATEWAY
1933 if (OC_GATEWAY == myStackMode)
1935 result = RMInitialize();
1940 if(result != OC_STACK_OK)
1942 OC_LOG(ERROR, TAG, "Stack initialization error");
1943 deleteAllResources();
1945 stackState = OC_STACK_UNINITIALIZED;
1950 OCStackResult OCStop()
1952 OC_LOG(INFO, TAG, "Entering OCStop");
1954 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1956 OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1959 else if (stackState != OC_STACK_INITIALIZED)
1961 OC_LOG(ERROR, TAG, "Stack not initialized");
1962 return OC_STACK_ERROR;
1965 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1967 #ifdef WITH_PRESENCE
1968 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1969 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1970 presenceResource.presenceTTL = 0;
1971 #endif // WITH_PRESENCE
1973 #ifdef ROUTING_GATEWAY
1974 if (OC_GATEWAY == myStackMode)
1980 // Free memory dynamically allocated for resources
1981 deleteAllResources();
1983 DeletePlatformInfo();
1985 // Remove all observers
1986 DeleteObserverList();
1987 // Remove all the client callbacks
1988 DeleteClientCBList();
1990 // De-init the SRM Policy Engine
1991 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1992 SRMDeInitPolicyEngine();
1995 stackState = OC_STACK_UNINITIALIZED;
1999 OCStackResult OCStartMulticastServer()
2001 if(stackState != OC_STACK_INITIALIZED)
2003 OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2004 return OC_STACK_ERROR;
2006 CAResult_t ret = CAStartListeningServer();
2007 if (CA_STATUS_OK != ret)
2009 OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2010 return OC_STACK_ERROR;
2015 OCStackResult OCStopMulticastServer()
2017 CAResult_t ret = CAStopListeningServer();
2018 if (CA_STATUS_OK != ret)
2020 OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2021 return OC_STACK_ERROR;
2026 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2031 return CA_MSG_CONFIRM;
2036 return CA_MSG_NONCONFIRM;
2040 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2044 query = strchr (inputUri, '?');
2048 if((query - inputUri) > MAX_URI_LENGTH)
2050 return OC_STACK_INVALID_URI;
2053 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2055 return OC_STACK_INVALID_QUERY;
2058 else if(uriLen > MAX_URI_LENGTH)
2060 return OC_STACK_INVALID_URI;
2066 * A request uri consists of the following components in order:
2069 * CoAP over UDP prefix "coap://"
2070 * CoAP over TCP prefix "coap+tcp://"
2072 * IPv6 address "[1234::5678]"
2073 * IPv4 address "192.168.1.1"
2074 * optional port ":5683"
2075 * resource uri "/oc/core..."
2077 * for PRESENCE requests, extract resource type.
2079 static OCStackResult ParseRequestUri(const char *fullUri,
2080 OCTransportAdapter adapter,
2081 OCTransportFlags flags,
2082 OCDevAddr **devAddr,
2084 char **resourceType)
2086 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2088 OCStackResult result = OC_STACK_OK;
2089 OCDevAddr *da = NULL;
2093 // provide defaults for all returned values
2100 *resourceUri = NULL;
2104 *resourceType = NULL;
2107 // delimit url prefix, if any
2108 const char *start = fullUri;
2109 char *slash2 = strstr(start, "//");
2114 char *slash = strchr(start, '/');
2117 return OC_STACK_INVALID_URI;
2120 // process url scheme
2121 size_t prefixLen = slash2 - fullUri;
2125 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2131 // TODO: this logic should come in with unit tests exercising the various strings
2132 // processs url prefix, if any
2133 size_t urlLen = slash - start;
2137 if (urlLen && devAddr)
2138 { // construct OCDevAddr
2139 if (start[0] == '[')
2141 char *close = strchr(++start, ']');
2142 if (!close || close > slash)
2144 return OC_STACK_INVALID_URI;
2147 if (close[1] == ':')
2151 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2152 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2156 char *dot = strchr(start, '.');
2157 if (dot && dot < slash)
2159 colon = strchr(start, ':');
2160 end = (colon && colon < slash) ? colon : slash;
2164 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2168 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2169 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2178 if (len >= sizeof(da->addr))
2180 return OC_STACK_INVALID_URI;
2182 // collect port, if any
2183 if (colon && colon < slash)
2185 for (colon++; colon < slash; colon++)
2188 if (c < '0' || c > '9')
2190 return OC_STACK_INVALID_URI;
2192 port = 10 * port + c - '0';
2197 if (len >= sizeof(da->addr))
2199 return OC_STACK_INVALID_URI;
2202 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2205 return OC_STACK_NO_MEMORY;
2207 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2209 da->adapter = adapter;
2211 if (!strncmp(fullUri, "coaps:", 6))
2213 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2218 // process resource uri, if any
2220 { // request uri and query
2221 size_t ulen = strlen(slash); // resource uri length
2222 size_t tlen = 0; // resource type length
2225 static const char strPresence[] = "/oic/ad?rt=";
2226 static const size_t lenPresence = sizeof(strPresence) - 1;
2227 if (!strncmp(slash, strPresence, lenPresence))
2229 type = slash + lenPresence;
2230 tlen = ulen - lenPresence;
2235 *resourceUri = (char *)OICMalloc(ulen + 1);
2238 result = OC_STACK_NO_MEMORY;
2241 strcpy(*resourceUri, slash);
2244 if (type && resourceType)
2246 *resourceType = (char *)OICMalloc(tlen + 1);
2249 result = OC_STACK_NO_MEMORY;
2253 OICStrcpy(*resourceType, (tlen+1), type);
2260 // free all returned values
2267 OICFree(*resourceUri);
2271 OICFree(*resourceType);
2276 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2277 char *resourceUri, char **requestUri)
2279 char uri[CA_MAX_URI_LENGTH];
2281 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2283 *requestUri = OICStrdup(uri);
2286 return OC_STACK_NO_MEMORY;
2293 * Discover or Perform requests on a specified resource
2295 OCStackResult OCDoResource(OCDoHandle *handle,
2297 const char *requestUri,
2298 const OCDevAddr *destination,
2300 OCConnectivityType connectivityType,
2301 OCQualityOfService qos,
2302 OCCallbackData *cbData,
2303 OCHeaderOption *options,
2306 OC_LOG(INFO, TAG, "Entering OCDoResource");
2308 // Validate input parameters
2309 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2310 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2311 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2313 OCStackResult result = OC_STACK_ERROR;
2314 CAResult_t caResult;
2315 CAToken_t token = NULL;
2316 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2317 ClientCB *clientCB = NULL;
2318 OCDoHandle resHandle = NULL;
2319 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2320 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2322 OCTransportAdapter adapter;
2323 OCTransportFlags flags;
2324 // the request contents are put here
2325 CARequestInfo_t requestInfo = {.method = CA_GET};
2326 // requestUri will be parsed into the following three variables
2327 OCDevAddr *devAddr = NULL;
2328 char *resourceUri = NULL;
2329 char *resourceType = NULL;
2331 // This validation is broken, but doesn't cause harm
2332 size_t uriLen = strlen(requestUri );
2333 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2339 * Support original behavior with address on resourceUri argument.
2341 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2342 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2344 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2346 if (result != OC_STACK_OK)
2348 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2355 case OC_REST_OBSERVE:
2356 case OC_REST_OBSERVE_ALL:
2357 case OC_REST_CANCEL_OBSERVE:
2358 requestInfo.method = CA_GET;
2361 requestInfo.method = CA_PUT;
2364 requestInfo.method = CA_POST;
2366 case OC_REST_DELETE:
2367 requestInfo.method = CA_DELETE;
2369 case OC_REST_DISCOVER:
2371 if (destination || devAddr)
2373 requestInfo.isMulticast = false;
2377 tmpDevAddr.adapter = adapter;
2378 tmpDevAddr.flags = flags;
2379 destination = &tmpDevAddr;
2380 requestInfo.isMulticast = true;
2382 // CA_DISCOVER will become GET and isMulticast
2383 requestInfo.method = CA_GET;
2385 #ifdef WITH_PRESENCE
2386 case OC_REST_PRESENCE:
2387 // Replacing method type with GET because "presence"
2388 // is a stack layer only implementation.
2389 requestInfo.method = CA_GET;
2393 result = OC_STACK_INVALID_METHOD;
2397 if (!devAddr && !destination)
2399 OC_LOG(DEBUG, TAG, "no devAddr and no destination");
2400 result = OC_STACK_INVALID_PARAM;
2404 /* If not original behavior, use destination argument */
2405 if (destination && !devAddr)
2407 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2410 result = OC_STACK_NO_MEMORY;
2413 *devAddr = *destination;
2416 resHandle = GenerateInvocationHandle();
2419 result = OC_STACK_NO_MEMORY;
2423 caResult = CAGenerateToken(&token, tokenLength);
2424 if (caResult != CA_STATUS_OK)
2426 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2427 result= OC_STACK_ERROR;
2431 // fill in request data
2432 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2433 requestInfo.info.token = token;
2434 requestInfo.info.tokenLength = tokenLength;
2435 requestInfo.info.resourceUri = resourceUri;
2437 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2439 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2440 options, numOptions, OC_OBSERVE_REGISTER);
2441 if (result != OC_STACK_OK)
2445 requestInfo.info.numOptions = numOptions + 1;
2449 requestInfo.info.numOptions = numOptions;
2450 requestInfo.info.options =
2451 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2452 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2453 numOptions * sizeof(CAHeaderOption_t));
2456 CopyDevAddrToEndpoint(devAddr, &endpoint);
2461 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2464 OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2467 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2471 requestInfo.info.payload = NULL;
2472 requestInfo.info.payloadSize = 0;
2473 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2476 if (result != OC_STACK_OK)
2478 OC_LOG(ERROR, TAG, "CACreateEndpoint error");
2482 // prepare for response
2483 #ifdef WITH_PRESENCE
2484 if (method == OC_REST_PRESENCE)
2486 char *presenceUri = NULL;
2487 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2488 if (OC_STACK_OK != result)
2493 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2494 // Presence notification will form a canonical uri to
2495 // look for callbacks into the application.
2496 resourceUri = presenceUri;
2500 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2501 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2502 method, devAddr, resourceUri, resourceType, ttl);
2503 if (OC_STACK_OK != result)
2508 devAddr = NULL; // Client CB list entry now owns it
2509 resourceUri = NULL; // Client CB list entry now owns it
2510 resourceType = NULL; // Client CB list entry now owns it
2513 result = OCSendRequest(&endpoint, &requestInfo);
2514 if (OC_STACK_OK != result)
2521 *handle = resHandle;
2525 if (result != OC_STACK_OK)
2527 OC_LOG(ERROR, TAG, "OCDoResource error");
2528 FindAndDeleteClientCB(clientCB);
2529 CADestroyToken(token);
2537 // This is the owner of the payload object, so we free it
2538 OCPayloadDestroy(payload);
2539 OICFree(requestInfo.info.payload);
2541 OICFree(resourceUri);
2542 OICFree(resourceType);
2543 OICFree(requestInfo.info.options);
2547 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2551 * This ftn is implemented one of two ways in the case of observation:
2553 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2554 * Remove the callback associated on client side.
2555 * When the next notification comes in from server,
2556 * reply with RESET message to server.
2557 * Keep in mind that the server will react to RESET only
2558 * if the last notification was sent as CON
2560 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2561 * and it is associated with an observe request
2562 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2563 * Send CON Observe request to server with
2564 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2565 * Remove the callback associated on client side.
2567 OCStackResult ret = OC_STACK_OK;
2568 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2569 CARequestInfo_t requestInfo = {.method = CA_GET};
2573 return OC_STACK_INVALID_PARAM;
2576 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2579 OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2580 return OC_STACK_ERROR;
2583 switch (clientCB->method)
2585 case OC_REST_OBSERVE:
2586 case OC_REST_OBSERVE_ALL:
2588 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2589 clientCB->requestUri);
2590 if (qos != OC_HIGH_QOS)
2592 FindAndDeleteClientCB(clientCB);
2596 OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2598 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2599 requestInfo.info.token = clientCB->token;
2600 requestInfo.info.tokenLength = clientCB->tokenLength;
2602 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2603 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2605 return OC_STACK_ERROR;
2607 requestInfo.info.numOptions = numOptions + 1;
2608 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2610 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2612 ret = OCSendRequest(&endpoint, &requestInfo);
2614 if (requestInfo.info.options)
2616 OICFree (requestInfo.info.options);
2618 if (requestInfo.info.resourceUri)
2620 OICFree (requestInfo.info.resourceUri);
2625 case OC_REST_DISCOVER:
2626 OC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2627 clientCB->requestUri);
2628 FindAndDeleteClientCB(clientCB);
2631 #ifdef WITH_PRESENCE
2632 case OC_REST_PRESENCE:
2633 FindAndDeleteClientCB(clientCB);
2638 ret = OC_STACK_INVALID_METHOD;
2646 * @brief Register Persistent storage callback.
2647 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2649 * OC_STACK_OK - No errors; Success
2650 * OC_STACK_INVALID_PARAM - Invalid parameter
2652 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2654 OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2655 if(!persistentStorageHandler)
2657 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2658 return OC_STACK_INVALID_PARAM;
2662 if( !persistentStorageHandler->open ||
2663 !persistentStorageHandler->close ||
2664 !persistentStorageHandler->read ||
2665 !persistentStorageHandler->unlink ||
2666 !persistentStorageHandler->write)
2668 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2669 return OC_STACK_INVALID_PARAM;
2672 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2675 #ifdef WITH_PRESENCE
2677 OCStackResult OCProcessPresence()
2679 OCStackResult result = OC_STACK_OK;
2681 // the following line floods the log with messages that are irrelevant
2682 // to most purposes. Uncomment as needed.
2683 //OC_LOG(INFO, TAG, "Entering RequestPresence");
2684 ClientCB* cbNode = NULL;
2685 OCClientResponse clientResponse;
2686 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2688 LL_FOREACH(cbList, cbNode)
2690 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2695 uint32_t now = GetTicks(0);
2696 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2697 cbNode->presence->TTLlevel);
2698 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2700 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2705 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2707 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2708 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2710 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2712 OC_LOG(DEBUG, TAG, "No more timeout ticks");
2714 clientResponse.sequenceNumber = 0;
2715 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2716 clientResponse.devAddr = *cbNode->devAddr;
2717 FixUpClientResponse(&clientResponse);
2718 clientResponse.payload = NULL;
2720 // Increment the TTLLevel (going to a next state), so we don't keep
2721 // sending presence notification to client.
2722 cbNode->presence->TTLlevel++;
2723 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2724 cbNode->presence->TTLlevel);
2726 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2727 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2729 FindAndDeleteClientCB(cbNode);
2733 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2738 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2739 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2740 CARequestInfo_t requestInfo = {.method = CA_GET};
2742 OC_LOG(DEBUG, TAG, "time to test server presence");
2744 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2746 requestData.type = CA_MSG_NONCONFIRM;
2747 requestData.token = cbNode->token;
2748 requestData.tokenLength = cbNode->tokenLength;
2749 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2750 requestInfo.method = CA_GET;
2751 requestInfo.info = requestData;
2753 result = OCSendRequest(&endpoint, &requestInfo);
2754 if (OC_STACK_OK != result)
2759 cbNode->presence->TTLlevel++;
2760 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2763 if (result != OC_STACK_OK)
2765 OC_LOG(ERROR, TAG, "OCProcessPresence error");
2770 #endif // WITH_PRESENCE
2772 OCStackResult OCProcess()
2774 #ifdef WITH_PRESENCE
2775 OCProcessPresence();
2777 CAHandleRequestResponse();
2779 #ifdef ROUTING_GATEWAY
2785 #ifdef WITH_PRESENCE
2786 OCStackResult OCStartPresence(const uint32_t ttl)
2788 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2789 OCChangeResourceProperty(
2790 &(((OCResource *)presenceResource.handle)->resourceProperties),
2793 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2795 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2796 OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2800 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2801 OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2805 presenceResource.presenceTTL = ttl;
2807 OC_LOG_V(DEBUG, TAG, "Presence TTL is %lu seconds", presenceResource.presenceTTL);
2809 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2811 presenceState = OC_PRESENCE_INITIALIZED;
2813 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2815 CAToken_t caToken = NULL;
2816 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2817 if (caResult != CA_STATUS_OK)
2819 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2820 CADestroyToken(caToken);
2821 return OC_STACK_ERROR;
2824 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2825 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2826 CADestroyToken(caToken);
2829 // Each time OCStartPresence is called
2830 // a different random 32-bit integer number is used
2831 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2833 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2834 OC_PRESENCE_TRIGGER_CREATE);
2837 OCStackResult OCStopPresence()
2839 OCStackResult result = OC_STACK_ERROR;
2841 if(presenceResource.handle)
2843 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2845 // make resource inactive
2846 result = OCChangeResourceProperty(
2847 &(((OCResource *) presenceResource.handle)->resourceProperties),
2851 if(result != OC_STACK_OK)
2854 "Changing the presence resource properties to ACTIVE not successful");
2858 return SendStopNotification();
2862 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2863 void* callbackParameter)
2865 defaultDeviceHandler = entityHandler;
2866 defaultDeviceHandlerCallbackParameter = callbackParameter;
2871 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2873 OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2875 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2877 if (validatePlatformInfo(platformInfo))
2879 return SavePlatformInfo(platformInfo);
2883 return OC_STACK_INVALID_PARAM;
2888 return OC_STACK_ERROR;
2892 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2894 OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2896 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2898 OC_LOG(ERROR, TAG, "Null or empty device name.");
2899 return OC_STACK_INVALID_PARAM;
2902 return SaveDeviceInfo(deviceInfo);
2905 OCStackResult OCCreateResource(OCResourceHandle *handle,
2906 const char *resourceTypeName,
2907 const char *resourceInterfaceName,
2908 const char *uri, OCEntityHandler entityHandler,
2909 void* callbackParam,
2910 uint8_t resourceProperties)
2913 OCResource *pointer = NULL;
2914 OCStackResult result = OC_STACK_ERROR;
2916 OC_LOG(INFO, TAG, "Entering OCCreateResource");
2918 if(myStackMode == OC_CLIENT)
2920 return OC_STACK_INVALID_PARAM;
2922 // Validate parameters
2923 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2925 OC_LOG(ERROR, TAG, "URI is empty or too long");
2926 return OC_STACK_INVALID_URI;
2928 // Is it presented during resource discovery?
2929 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2931 OC_LOG(ERROR, TAG, "Input parameter is NULL");
2932 return OC_STACK_INVALID_PARAM;
2935 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2937 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2940 // Make sure resourceProperties bitmask has allowed properties specified
2941 if (resourceProperties
2942 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2943 OC_EXPLICIT_DISCOVERABLE))
2945 OC_LOG(ERROR, TAG, "Invalid property");
2946 return OC_STACK_INVALID_PARAM;
2949 // If the headResource is NULL, then no resources have been created...
2950 pointer = headResource;
2953 // At least one resources is in the resource list, so we need to search for
2954 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2957 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2959 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2960 return OC_STACK_INVALID_PARAM;
2962 pointer = pointer->next;
2965 // Create the pointer and insert it into the resource list
2966 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2969 result = OC_STACK_NO_MEMORY;
2972 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2974 insertResource(pointer);
2977 pointer->uri = OICStrdup(uri);
2980 result = OC_STACK_NO_MEMORY;
2984 // Set properties. Set OC_ACTIVE
2985 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2988 // Add the resourcetype to the resource
2989 result = BindResourceTypeToResource(pointer, resourceTypeName);
2990 if (result != OC_STACK_OK)
2992 OC_LOG(ERROR, TAG, "Error adding resourcetype");
2996 // Add the resourceinterface to the resource
2997 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
2998 if (result != OC_STACK_OK)
3000 OC_LOG(ERROR, TAG, "Error adding resourceinterface");
3004 // If an entity handler has been passed, attach it to the newly created
3005 // resource. Otherwise, set the default entity handler.
3008 pointer->entityHandler = entityHandler;
3009 pointer->entityHandlerCallbackParam = callbackParam;
3013 pointer->entityHandler = defaultResourceEHandler;
3014 pointer->entityHandlerCallbackParam = NULL;
3018 result = OC_STACK_OK;
3020 #ifdef WITH_PRESENCE
3021 if (presenceResource.handle)
3023 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3024 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3028 if (result != OC_STACK_OK)
3030 // Deep delete of resource and other dynamic elements that it contains
3031 deleteResource(pointer);
3037 OCStackResult OCBindResource(
3038 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3040 OCResource *resource = NULL;
3043 OC_LOG(INFO, TAG, "Entering OCBindResource");
3045 // Validate parameters
3046 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3047 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3048 // Container cannot contain itself
3049 if (collectionHandle == resourceHandle)
3051 OC_LOG(ERROR, TAG, "Added handle equals collection handle");
3052 return OC_STACK_INVALID_PARAM;
3055 // Use the handle to find the resource in the resource linked list
3056 resource = findResource((OCResource *) collectionHandle);
3059 OC_LOG(ERROR, TAG, "Collection handle not found");
3060 return OC_STACK_INVALID_PARAM;
3063 // Look for an open slot to add add the child resource.
3064 // If found, add it and return success
3065 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3067 if (!resource->rsrcResources[i])
3069 resource->rsrcResources[i] = (OCResource *) resourceHandle;
3070 OC_LOG(INFO, TAG, "resource bound");
3072 #ifdef WITH_PRESENCE
3073 if (presenceResource.handle)
3075 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3076 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3077 OC_PRESENCE_TRIGGER_CHANGE);
3085 // Unable to add resourceHandle, so return error
3086 return OC_STACK_ERROR;
3089 OCStackResult OCUnBindResource(
3090 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3092 OCResource *resource = NULL;
3095 OC_LOG(INFO, TAG, "Entering OCUnBindResource");
3097 // Validate parameters
3098 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3099 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3100 // Container cannot contain itself
3101 if (collectionHandle == resourceHandle)
3103 OC_LOG(ERROR, TAG, "removing handle equals collection handle");
3104 return OC_STACK_INVALID_PARAM;
3107 // Use the handle to find the resource in the resource linked list
3108 resource = findResource((OCResource *) collectionHandle);
3111 OC_LOG(ERROR, TAG, "Collection handle not found");
3112 return OC_STACK_INVALID_PARAM;
3115 // Look for an open slot to add add the child resource.
3116 // If found, add it and return success
3117 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3119 if (resourceHandle == resource->rsrcResources[i])
3121 resource->rsrcResources[i] = (OCResource *) NULL;
3122 OC_LOG(INFO, TAG, "resource unbound");
3124 // Send notification when resource is unbounded successfully.
3125 #ifdef WITH_PRESENCE
3126 if (presenceResource.handle)
3128 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3129 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3130 OC_PRESENCE_TRIGGER_CHANGE);
3137 OC_LOG(INFO, TAG, "resource not found in collection");
3139 // Unable to add resourceHandle, so return error
3140 return OC_STACK_ERROR;
3143 // Precondition is that the parameter has been checked to not equal NULL.
3144 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3146 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3152 while (resourceItemName[index] != '\0')
3154 if (resourceItemName[index] != '.' &&
3155 resourceItemName[index] != '-' &&
3156 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3157 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3166 OCStackResult BindResourceTypeToResource(OCResource* resource,
3167 const char *resourceTypeName)
3169 OCResourceType *pointer = NULL;
3171 OCStackResult result = OC_STACK_ERROR;
3173 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3175 if (!ValidateResourceTypeInterface(resourceTypeName))
3177 OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3178 return OC_STACK_INVALID_PARAM;
3181 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3184 result = OC_STACK_NO_MEMORY;
3188 str = OICStrdup(resourceTypeName);
3191 result = OC_STACK_NO_MEMORY;
3194 pointer->resourcetypename = str;
3196 insertResourceType(resource, pointer);
3197 result = OC_STACK_OK;
3200 if (result != OC_STACK_OK)
3209 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3210 const char *resourceInterfaceName)
3212 OCResourceInterface *pointer = NULL;
3214 OCStackResult result = OC_STACK_ERROR;
3216 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3218 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3220 OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3221 return OC_STACK_INVALID_PARAM;
3224 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3226 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3229 result = OC_STACK_NO_MEMORY;
3233 str = OICStrdup(resourceInterfaceName);
3236 result = OC_STACK_NO_MEMORY;
3239 pointer->name = str;
3241 // Bind the resourceinterface to the resource
3242 insertResourceInterface(resource, pointer);
3244 result = OC_STACK_OK;
3247 if (result != OC_STACK_OK)
3256 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3257 const char *resourceTypeName)
3260 OCStackResult result = OC_STACK_ERROR;
3261 OCResource *resource = NULL;
3263 resource = findResource((OCResource *) handle);
3266 OC_LOG(ERROR, TAG, "Resource not found");
3267 return OC_STACK_ERROR;
3270 result = BindResourceTypeToResource(resource, resourceTypeName);
3272 #ifdef WITH_PRESENCE
3273 if(presenceResource.handle)
3275 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3276 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3283 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3284 const char *resourceInterfaceName)
3287 OCStackResult result = OC_STACK_ERROR;
3288 OCResource *resource = NULL;
3290 resource = findResource((OCResource *) handle);
3293 OC_LOG(ERROR, TAG, "Resource not found");
3294 return OC_STACK_ERROR;
3297 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3299 #ifdef WITH_PRESENCE
3300 if (presenceResource.handle)
3302 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3303 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3310 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3312 OCResource *pointer = headResource;
3314 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3318 *numResources = *numResources + 1;
3319 pointer = pointer->next;
3324 OCResourceHandle OCGetResourceHandle(uint8_t index)
3326 OCResource *pointer = headResource;
3328 for( uint8_t i = 0; i < index && pointer; ++i)
3330 pointer = pointer->next;
3332 return (OCResourceHandle) pointer;
3335 OCStackResult OCDeleteResource(OCResourceHandle handle)
3339 OC_LOG(ERROR, TAG, "Invalid handle for deletion");
3340 return OC_STACK_INVALID_PARAM;
3343 OCResource *resource = findResource((OCResource *) handle);
3344 if (resource == NULL)
3346 OC_LOG(ERROR, TAG, "Resource not found");
3347 return OC_STACK_NO_RESOURCE;
3350 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3352 OC_LOG(ERROR, TAG, "Error deleting resource");
3353 return OC_STACK_ERROR;
3359 const char *OCGetResourceUri(OCResourceHandle handle)
3361 OCResource *resource = NULL;
3363 resource = findResource((OCResource *) handle);
3366 return resource->uri;
3368 return (const char *) NULL;
3371 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3373 OCResource *resource = NULL;
3375 resource = findResource((OCResource *) handle);
3378 return resource->resourceProperties;
3380 return (OCResourceProperty)-1;
3383 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3384 uint8_t *numResourceTypes)
3386 OCResource *resource = NULL;
3387 OCResourceType *pointer = NULL;
3389 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3390 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3392 *numResourceTypes = 0;
3394 resource = findResource((OCResource *) handle);
3397 pointer = resource->rsrcType;
3400 *numResourceTypes = *numResourceTypes + 1;
3401 pointer = pointer->next;
3407 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3409 OCResourceType *resourceType = NULL;
3411 resourceType = findResourceTypeAtIndex(handle, index);
3414 return resourceType->resourcetypename;
3416 return (const char *) NULL;
3419 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3420 uint8_t *numResourceInterfaces)
3422 OCResourceInterface *pointer = NULL;
3423 OCResource *resource = NULL;
3425 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3426 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3428 *numResourceInterfaces = 0;
3429 resource = findResource((OCResource *) handle);
3432 pointer = resource->rsrcInterface;
3435 *numResourceInterfaces = *numResourceInterfaces + 1;
3436 pointer = pointer->next;
3442 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3444 OCResourceInterface *resourceInterface = NULL;
3446 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3447 if (resourceInterface)
3449 return resourceInterface->name;
3451 return (const char *) NULL;
3454 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3457 OCResource *resource = NULL;
3459 if (index >= MAX_CONTAINED_RESOURCES)
3464 resource = findResource((OCResource *) collectionHandle);
3470 return resource->rsrcResources[index];
3473 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3474 OCEntityHandler entityHandler,
3475 void* callbackParam)
3477 OCResource *resource = NULL;
3479 // Validate parameters
3480 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3482 // Use the handle to find the resource in the resource linked list
3483 resource = findResource((OCResource *)handle);
3486 OC_LOG(ERROR, TAG, "Resource not found");
3487 return OC_STACK_ERROR;
3491 resource->entityHandler = entityHandler;
3492 resource->entityHandlerCallbackParam = callbackParam;
3494 #ifdef WITH_PRESENCE
3495 if (presenceResource.handle)
3497 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3498 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3505 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3507 OCResource *resource = NULL;
3509 resource = findResource((OCResource *)handle);
3512 OC_LOG(ERROR, TAG, "Resource not found");
3517 return resource->entityHandler;
3520 void incrementSequenceNumber(OCResource * resPtr)
3522 // Increment the sequence number
3523 resPtr->sequenceNum += 1;
3524 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3526 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3531 #ifdef WITH_PRESENCE
3532 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3533 OCPresenceTrigger trigger)
3535 OCResource *resPtr = NULL;
3536 OCStackResult result = OC_STACK_ERROR;
3537 OCMethod method = OC_REST_PRESENCE;
3538 uint32_t maxAge = 0;
3539 resPtr = findResource((OCResource *) presenceResource.handle);
3542 return OC_STACK_NO_RESOURCE;
3545 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3547 maxAge = presenceResource.presenceTTL;
3549 result = SendAllObserverNotification(method, resPtr, maxAge,
3550 trigger, resourceType, OC_LOW_QOS);
3556 OCStackResult SendStopNotification()
3558 OCResource *resPtr = NULL;
3559 OCStackResult result = OC_STACK_ERROR;
3560 OCMethod method = OC_REST_PRESENCE;
3561 resPtr = findResource((OCResource *) presenceResource.handle);
3564 return OC_STACK_NO_RESOURCE;
3567 // maxAge is 0. ResourceType is NULL.
3568 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3574 #endif // WITH_PRESENCE
3575 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3577 OCResource *resPtr = NULL;
3578 OCStackResult result = OC_STACK_ERROR;
3579 OCMethod method = OC_REST_NOMETHOD;
3580 uint32_t maxAge = 0;
3582 OC_LOG(INFO, TAG, "Notifying all observers");
3583 #ifdef WITH_PRESENCE
3584 if(handle == presenceResource.handle)
3588 #endif // WITH_PRESENCE
3589 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3591 // Verify that the resource exists
3592 resPtr = findResource ((OCResource *) handle);
3595 return OC_STACK_NO_RESOURCE;
3599 //only increment in the case of regular observing (not presence)
3600 incrementSequenceNumber(resPtr);
3601 method = OC_REST_OBSERVE;
3602 maxAge = MAX_OBSERVE_AGE;
3603 #ifdef WITH_PRESENCE
3604 result = SendAllObserverNotification (method, resPtr, maxAge,
3605 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3607 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3614 OCNotifyListOfObservers (OCResourceHandle handle,
3615 OCObservationId *obsIdList,
3616 uint8_t numberOfIds,
3617 const OCRepPayload *payload,
3618 OCQualityOfService qos)
3620 OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3622 OCResource *resPtr = NULL;
3623 //TODO: we should allow the server to define this
3624 uint32_t maxAge = MAX_OBSERVE_AGE;
3626 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3627 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3628 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3630 resPtr = findResource ((OCResource *) handle);
3631 if (NULL == resPtr || myStackMode == OC_CLIENT)
3633 return OC_STACK_NO_RESOURCE;
3637 incrementSequenceNumber(resPtr);
3639 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3640 payload, maxAge, qos));
3643 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3645 OCStackResult result = OC_STACK_ERROR;
3646 OCServerRequest *serverRequest = NULL;
3648 OC_LOG(INFO, TAG, "Entering OCDoResponse");
3650 // Validate input parameters
3651 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3652 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3655 // Get pointer to request info
3656 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3659 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3660 result = serverRequest->ehResponseHandler(ehResponse);
3666 //-----------------------------------------------------------------------------
3667 // Private internal function definitions
3668 //-----------------------------------------------------------------------------
3669 static OCDoHandle GenerateInvocationHandle()
3671 OCDoHandle handle = NULL;
3672 // Generate token here, it will be deleted when the transaction is deleted
3673 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3676 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3682 #ifdef WITH_PRESENCE
3683 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3684 OCResourceProperty resourceProperties, uint8_t enable)
3688 return OC_STACK_INVALID_PARAM;
3690 if (resourceProperties
3691 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3693 OC_LOG(ERROR, TAG, "Invalid property");
3694 return OC_STACK_INVALID_PARAM;
3698 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3702 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3708 OCStackResult initResources()
3710 OCStackResult result = OC_STACK_OK;
3712 headResource = NULL;
3713 tailResource = NULL;
3714 // Init Virtual Resources
3715 #ifdef WITH_PRESENCE
3716 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3718 result = OCCreateResource(&presenceResource.handle,
3719 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3721 OC_RSRVD_PRESENCE_URI,
3725 //make resource inactive
3726 result = OCChangeResourceProperty(
3727 &(((OCResource *) presenceResource.handle)->resourceProperties),
3730 #ifndef WITH_ARDUINO
3731 if (result == OC_STACK_OK)
3733 result = SRMInitSecureResources();
3737 if(result == OC_STACK_OK)
3739 result = OCCreateResource(&deviceResource,
3740 OC_RSRVD_RESOURCE_TYPE_DEVICE,
3741 OC_RSRVD_INTERFACE_DEFAULT,
3742 OC_RSRVD_DEVICE_URI,
3746 if(result == OC_STACK_OK)
3748 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
3749 OC_RSRVD_INTERFACE_READ);
3753 if(result == OC_STACK_OK)
3755 result = OCCreateResource(&platformResource,
3756 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
3757 OC_RSRVD_INTERFACE_DEFAULT,
3758 OC_RSRVD_PLATFORM_URI,
3762 if(result == OC_STACK_OK)
3764 result = BindResourceInterfaceToResource((OCResource *)platformResource,
3765 OC_RSRVD_INTERFACE_READ);
3772 void insertResource(OCResource *resource)
3776 headResource = resource;
3777 tailResource = resource;
3781 tailResource->next = resource;
3782 tailResource = resource;
3784 resource->next = NULL;
3787 OCResource *findResource(OCResource *resource)
3789 OCResource *pointer = headResource;
3793 if (pointer == resource)
3797 pointer = pointer->next;
3802 void deleteAllResources()
3804 OCResource *pointer = headResource;
3805 OCResource *temp = NULL;
3809 temp = pointer->next;
3810 #ifdef WITH_PRESENCE
3811 if (pointer != (OCResource *) presenceResource.handle)
3813 #endif // WITH_PRESENCE
3814 deleteResource(pointer);
3815 #ifdef WITH_PRESENCE
3817 #endif // WITH_PRESENCE
3821 SRMDeInitSecureResources();
3823 #ifdef WITH_PRESENCE
3824 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3825 // presence notification attributed to their deletion to be processed.
3826 deleteResource((OCResource *) presenceResource.handle);
3827 #endif // WITH_PRESENCE
3830 OCStackResult deleteResource(OCResource *resource)
3832 OCResource *prev = NULL;
3833 OCResource *temp = NULL;
3836 OC_LOG(DEBUG,TAG,"resource is NULL");
3837 return OC_STACK_INVALID_PARAM;
3840 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3842 temp = headResource;
3845 if (temp == resource)
3847 // Invalidate all Resource Properties.
3848 resource->resourceProperties = (OCResourceProperty) 0;
3849 #ifdef WITH_PRESENCE
3850 if(resource != (OCResource *) presenceResource.handle)
3852 #endif // WITH_PRESENCE
3853 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3854 #ifdef WITH_PRESENCE
3857 if(presenceResource.handle)
3859 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3860 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3863 // Only resource in list.
3864 if (temp == headResource && temp == tailResource)
3866 headResource = NULL;
3867 tailResource = NULL;
3870 else if (temp == headResource)
3872 headResource = temp->next;
3875 else if (temp == tailResource)
3877 tailResource = prev;
3878 tailResource->next = NULL;
3882 prev->next = temp->next;
3885 deleteResourceElements(temp);
3896 return OC_STACK_ERROR;
3899 void deleteResourceElements(OCResource *resource)
3906 OICFree(resource->uri);
3907 deleteResourceType(resource->rsrcType);
3908 deleteResourceInterface(resource->rsrcInterface);
3911 void deleteResourceType(OCResourceType *resourceType)
3913 OCResourceType *pointer = resourceType;
3914 OCResourceType *next = NULL;
3918 next = pointer->next;
3919 OICFree(pointer->resourcetypename);
3925 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3927 OCResourceInterface *pointer = resourceInterface;
3928 OCResourceInterface *next = NULL;
3932 next = pointer->next;
3933 OICFree(pointer->name);
3939 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3941 OCResourceType *pointer = NULL;
3942 OCResourceType *previous = NULL;
3943 if (!resource || !resourceType)
3947 // resource type list is empty.
3948 else if (!resource->rsrcType)
3950 resource->rsrcType = resourceType;
3954 pointer = resource->rsrcType;
3958 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3960 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3961 OICFree(resourceType->resourcetypename);
3962 OICFree(resourceType);
3966 pointer = pointer->next;
3968 previous->next = resourceType;
3970 resourceType->next = NULL;
3972 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3975 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3977 OCResource *resource = NULL;
3978 OCResourceType *pointer = NULL;
3980 // Find the specified resource
3981 resource = findResource((OCResource *) handle);
3987 // Make sure a resource has a resourcetype
3988 if (!resource->rsrcType)
3993 // Iterate through the list
3994 pointer = resource->rsrcType;
3995 for(uint8_t i = 0; i< index && pointer; ++i)
3997 pointer = pointer->next;
4002 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4004 if(resourceTypeList && resourceTypeName)
4006 OCResourceType * rtPointer = resourceTypeList;
4007 while(resourceTypeName && rtPointer)
4009 if(rtPointer->resourcetypename &&
4010 strcmp(resourceTypeName, (const char *)
4011 (rtPointer->resourcetypename)) == 0)
4015 rtPointer = rtPointer->next;
4023 * Insert a new interface into interface linked list only if not already present.
4024 * If alredy present, 2nd arg is free'd.
4025 * Default interface will always be first if present.
4027 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4029 OCResourceInterface *pointer = NULL;
4030 OCResourceInterface *previous = NULL;
4032 newInterface->next = NULL;
4034 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4036 if (!*firstInterface)
4038 *firstInterface = newInterface;
4040 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4042 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4044 OICFree(newInterface->name);
4045 OICFree(newInterface);
4050 newInterface->next = *firstInterface;
4051 *firstInterface = newInterface;
4056 pointer = *firstInterface;
4059 if (strcmp(newInterface->name, pointer->name) == 0)
4061 OICFree(newInterface->name);
4062 OICFree(newInterface);
4066 pointer = pointer->next;
4068 previous->next = newInterface;
4072 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4075 OCResource *resource = NULL;
4076 OCResourceInterface *pointer = NULL;
4078 // Find the specified resource
4079 resource = findResource((OCResource *) handle);
4085 // Make sure a resource has a resourceinterface
4086 if (!resource->rsrcInterface)
4091 // Iterate through the list
4092 pointer = resource->rsrcInterface;
4094 for (uint8_t i = 0; i < index && pointer; ++i)
4096 pointer = pointer->next;
4102 * This function splits the uri using the '?' delimiter.
4103 * "uriWithoutQuery" is the block of characters between the beginning
4104 * till the delimiter or '\0' which ever comes first.
4105 * "query" is whatever is to the right of the delimiter if present.
4106 * No delimiter sets the query to NULL.
4107 * If either are present, they will be malloc'ed into the params 2, 3.
4108 * The first param, *uri is left untouched.
4110 * NOTE: This function does not account for whitespace at the end of the uri NOR
4111 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4112 * part of the query.
4114 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4118 return OC_STACK_INVALID_URI;
4120 if(!query || !uriWithoutQuery)
4122 return OC_STACK_INVALID_PARAM;
4126 *uriWithoutQuery = NULL;
4128 size_t uriWithoutQueryLen = 0;
4129 size_t queryLen = 0;
4130 size_t uriLen = strlen(uri);
4132 char *pointerToDelimiter = strstr(uri, "?");
4134 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4135 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4137 if (uriWithoutQueryLen)
4139 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4140 if (!*uriWithoutQuery)
4144 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4148 *query = (char *) OICCalloc(queryLen + 1, 1);
4151 OICFree(*uriWithoutQuery);
4152 *uriWithoutQuery = NULL;
4155 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4161 return OC_STACK_NO_MEMORY;
4164 const OicUuid_t* OCGetServerInstanceID(void)
4166 static bool generated = false;
4167 static OicUuid_t sid;
4173 if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4175 OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4182 const char* OCGetServerInstanceIDString(void)
4184 static bool generated = false;
4185 static char sidStr[UUID_STRING_SIZE];
4192 const OicUuid_t* sid = OCGetServerInstanceID();
4194 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4196 OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4204 CAResult_t OCSelectNetwork()
4206 CAResult_t retResult = CA_STATUS_FAILED;
4207 CAResult_t caResult = CA_STATUS_OK;
4209 CATransportAdapter_t connTypes[] = {
4211 CA_ADAPTER_RFCOMM_BTEDR,
4212 CA_ADAPTER_GATT_BTLE
4215 ,CA_ADAPTER_REMOTE_ACCESS
4222 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4224 for(int i = 0; i<numConnTypes; i++)
4226 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4227 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4229 caResult = CASelectNetwork(connTypes[i]);
4230 if(caResult == CA_STATUS_OK)
4232 retResult = CA_STATUS_OK;
4237 if(retResult != CA_STATUS_OK)
4239 return caResult; // Returns error of appropriate transport that failed fatally.
4245 OCStackResult CAResultToOCResult(CAResult_t caResult)
4251 case CA_STATUS_INVALID_PARAM:
4252 return OC_STACK_INVALID_PARAM;
4253 case CA_ADAPTER_NOT_ENABLED:
4254 return OC_STACK_ADAPTER_NOT_ENABLED;
4255 case CA_SERVER_STARTED_ALREADY:
4257 case CA_SERVER_NOT_STARTED:
4258 return OC_STACK_ERROR;
4259 case CA_DESTINATION_NOT_REACHABLE:
4260 return OC_STACK_COMM_ERROR;
4261 case CA_SOCKET_OPERATION_FAILED:
4262 return OC_STACK_COMM_ERROR;
4263 case CA_SEND_FAILED:
4264 return OC_STACK_COMM_ERROR;
4265 case CA_RECEIVE_FAILED:
4266 return OC_STACK_COMM_ERROR;
4267 case CA_MEMORY_ALLOC_FAILED:
4268 return OC_STACK_NO_MEMORY;
4269 case CA_REQUEST_TIMEOUT:
4270 return OC_STACK_TIMEOUT;
4271 case CA_DESTINATION_DISCONNECTED:
4272 return OC_STACK_COMM_ERROR;
4273 case CA_STATUS_FAILED:
4274 return OC_STACK_ERROR;
4275 case CA_NOT_SUPPORTED:
4276 return OC_STACK_NOTIMPL;
4278 return OC_STACK_ERROR;