1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //-----------------------------------------------------------------------------
24 //-----------------------------------------------------------------------------
26 // Defining _POSIX_C_SOURCE macro with 200112L (or greater) as value
27 // causes header files to expose definitions
28 // corresponding to the POSIX.1-2001 base
29 // specification (excluding the XSI extension).
30 // For POSIX.1-2001 base specification,
31 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
32 #define _POSIX_C_SOURCE 200112L
33 #define __STDC_FORMAT_MACROS
34 #define __STDC_LIMIT_MACROS
40 #include "ocstackinternal.h"
41 #include "ocresourcehandler.h"
42 #include "occlientcb.h"
43 #include "ocobserve.h"
45 #include "oic_malloc.h"
46 #include "oic_string.h"
48 #include "ocserverrequest.h"
49 #include "secureresourcemanager.h"
50 #include "doxmresource.h"
52 #include "cainterface.h"
53 #include "ocpayload.h"
54 #include "ocpayloadcbor.h"
56 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
57 #include "routingutility.h"
58 #ifdef ROUTING_GATEWAY
59 #include "routingmanager.h"
68 #include "coap_time.h"
73 #include <arpa/inet.h>
77 #define UINT32_MAX (0xFFFFFFFFUL)
80 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
85 OC_STACK_UNINITIALIZED = 0,
87 OC_STACK_UNINIT_IN_PROGRESS
93 OC_PRESENCE_UNINITIALIZED = 0,
94 OC_PRESENCE_INITIALIZED
98 //-----------------------------------------------------------------------------
100 //-----------------------------------------------------------------------------
101 static OCStackState stackState = OC_STACK_UNINITIALIZED;
103 OCResource *headResource = NULL;
104 static OCResource *tailResource = NULL;
105 static OCResourceHandle platformResource = {0};
106 static OCResourceHandle deviceResource = {0};
108 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
109 static PresenceResource presenceResource;
110 static uint8_t PresenceTimeOutSize = 0;
111 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
114 static OCMode myStackMode;
116 //TODO: revisit this design
117 static bool gRASetInfo = false;
119 OCDeviceEntityHandler defaultDeviceHandler;
120 void* defaultDeviceHandlerCallbackParameter = NULL;
121 static const char COAP_TCP[] = "coap+tcp:";
123 //-----------------------------------------------------------------------------
125 //-----------------------------------------------------------------------------
126 #define TAG "OCStack"
127 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
128 {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
129 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \
130 TAG, #arg " is NULL"); return (retVal); } }
131 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
132 TAG, #arg " is NULL"); return; } }
133 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL");\
136 //TODO: we should allow the server to define this
137 #define MAX_OBSERVE_AGE (0x2FFFFUL)
139 #define MILLISECONDS_PER_SECOND (1000)
141 //-----------------------------------------------------------------------------
142 // Private internal function prototypes
143 //-----------------------------------------------------------------------------
146 * Generate handle of OCDoResource invocation for callback management.
148 * @return Generated OCDoResource handle.
150 static OCDoHandle GenerateInvocationHandle();
153 * Initialize resource data structures, variables, etc.
155 * @return ::OC_STACK_OK on success, some other value upon failure.
157 static OCStackResult initResources();
160 * Add a resource to the end of the linked list of resources.
162 * @param resource Resource to be added
164 static void insertResource(OCResource *resource);
167 * Find a resource in the linked list of resources.
169 * @param resource Resource to be found.
170 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
173 static OCResource *findResource(OCResource *resource);
176 * Insert a resource type into a resource's resource type linked list.
177 * If resource type already exists, it will not be inserted and the
178 * resourceType will be free'd.
179 * resourceType->next should be null to avoid memory leaks.
180 * Function returns silently for null args.
182 * @param resource Resource where resource type is to be inserted.
183 * @param resourceType Resource type to be inserted.
185 static void insertResourceType(OCResource *resource,
186 OCResourceType *resourceType);
189 * Get a resource type at the specified index within a resource.
191 * @param handle Handle of resource.
192 * @param index Index of resource type.
194 * @return Pointer to resource type if found, NULL otherwise.
196 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
200 * Insert a resource interface into a resource's resource interface linked list.
201 * If resource interface already exists, it will not be inserted and the
202 * resourceInterface will be free'd.
203 * resourceInterface->next should be null to avoid memory leaks.
205 * @param resource Resource where resource interface is to be inserted.
206 * @param resourceInterface Resource interface to be inserted.
208 static void insertResourceInterface(OCResource *resource,
209 OCResourceInterface *resourceInterface);
212 * Get a resource interface at the specified index within a resource.
214 * @param handle Handle of resource.
215 * @param index Index of resource interface.
217 * @return Pointer to resource interface if found, NULL otherwise.
219 static OCResourceInterface *findResourceInterfaceAtIndex(
220 OCResourceHandle handle, uint8_t index);
223 * Delete all of the dynamically allocated elements that were created for the resource type.
225 * @param resourceType Specified resource type.
227 static void deleteResourceType(OCResourceType *resourceType);
230 * Delete all of the dynamically allocated elements that were created for the resource interface.
232 * @param resourceInterface Specified resource interface.
234 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
237 * Delete all of the dynamically allocated elements that were created for the resource.
239 * @param resource Specified resource.
241 static void deleteResourceElements(OCResource *resource);
244 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
247 * @param handle Handle of resource to be deleted.
249 * @return ::OC_STACK_OK on success, some other value upon failure.
251 static OCStackResult deleteResource(OCResource *resource);
254 * Delete all of the resources in the resource list.
256 static void deleteAllResources();
259 * Increment resource sequence number. Handles rollover.
261 * @param resPtr Pointer to resource.
263 static void incrementSequenceNumber(OCResource * resPtr);
266 * Verify the lengths of the URI and the query separately.
268 * @param inputUri Input URI and query.
269 * @param uriLen The length of the initial URI with query.
270 * @return ::OC_STACK_OK on success, some other value upon failure.
272 static OCStackResult verifyUriQueryLength(const char * inputUri,
276 * Attempts to initialize every network interface that the CA Layer might have compiled in.
278 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
279 * return something other than @ref CA_STATUS_OK, then this function fails.
281 * @return ::CA_STATUS_OK on success, some other value upon failure.
283 static CAResult_t OCSelectNetwork();
286 * Get the CoAP ticks after the specified number of milli-seconds.
288 * @param afterMilliSeconds Milli-seconds.
292 static uint32_t GetTicks(uint32_t afterMilliSeconds);
295 * Convert CAResponseResult_t to OCStackResult.
297 * @param caCode CAResponseResult_t code.
298 * @return ::OC_STACK_OK on success, some other value upon failure.
300 static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
303 * Convert OCStackResult to CAResponseResult_t.
305 * @param caCode OCStackResult code.
306 * @param method OCMethod method the return code replies to.
307 * @return ::CA_CONTENT on OK, some other value upon failure.
309 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
312 * Convert OCTransportFlags_t to CATransportModifiers_t.
314 * @param ocConType OCTransportFlags_t input.
315 * @return CATransportFlags
317 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
320 * Convert CATransportFlags_t to OCTransportModifiers_t.
322 * @param caConType CATransportFlags_t input.
323 * @return OCTransportFlags
325 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
328 * Handle response from presence request.
330 * @param endPoint CA remote endpoint.
331 * @param responseInfo CA response info.
332 * @return ::OC_STACK_OK on success, some other value upon failure.
334 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
335 const CAResponseInfo_t *responseInfo);
338 * This function will be called back by CA layer when a response is received.
340 * @param endPoint CA remote endpoint.
341 * @param responseInfo CA response info.
343 static void HandleCAResponses(const CAEndpoint_t* endPoint,
344 const CAResponseInfo_t* responseInfo);
347 * This function will be called back by CA layer when a request is received.
349 * @param endPoint CA remote endpoint.
350 * @param requestInfo CA request info.
352 static void HandleCARequests(const CAEndpoint_t* endPoint,
353 const CARequestInfo_t* requestInfo);
356 * Extract query from a URI.
358 * @param uri Full URI with query.
359 * @param query Pointer to string that will contain query.
360 * @param newURI Pointer to string that will contain URI.
361 * @return ::OC_STACK_OK on success, some other value upon failure.
363 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
366 * Finds a resource type in an OCResourceType link-list.
368 * @param resourceTypeList The link-list to be searched through.
369 * @param resourceTypeName The key to search for.
371 * @return Resource type that matches the key (ie. resourceTypeName) or
372 * NULL if there is either an invalid parameter or this function was unable to find the key.
374 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
375 const char * resourceTypeName);
378 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
379 * TTL will be set to maxAge.
381 * @param cbNode Callback Node for which presence ttl is to be reset.
382 * @param maxAge New value of ttl in seconds.
384 * @return ::OC_STACK_OK on success, some other value upon failure.
386 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
389 * Ensure the accept header option is set appropriatly before sending the requests and routing
390 * header option is updated with destination.
392 * @param object CA remote endpoint.
393 * @param requestInfo CA request info.
395 * @return ::OC_STACK_OK on success, some other value upon failure.
397 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
399 //-----------------------------------------------------------------------------
400 // Internal functions
401 //-----------------------------------------------------------------------------
403 uint32_t GetTicks(uint32_t afterMilliSeconds)
408 // Guard against overflow of uint32_t
409 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
410 COAP_TICKS_PER_SECOND)
412 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
420 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
422 VERIFY_NON_NULL_NR(in, FATAL);
423 VERIFY_NON_NULL_NR(out, FATAL);
425 out->adapter = (OCTransportAdapter)in->adapter;
426 out->flags = CAToOCTransportFlags(in->flags);
427 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
428 out->port = in->port;
429 out->interface = in->interface;
430 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
431 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
435 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
437 VERIFY_NON_NULL_NR(in, FATAL);
438 VERIFY_NON_NULL_NR(out, FATAL);
440 out->adapter = (CATransportAdapter_t)in->adapter;
441 out->flags = OCToCATransportFlags(in->flags);
442 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
443 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
444 memcpy(out->routeData, in->routeData, sizeof(out->routeData));
446 out->port = in->port;
447 out->interface = in->interface;
450 void FixUpClientResponse(OCClientResponse *cr)
452 VERIFY_NON_NULL_NR(cr, FATAL);
454 cr->addr = &cr->devAddr;
455 cr->connType = (OCConnectivityType)
456 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
459 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
461 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
462 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
464 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
465 OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
466 &(requestInfo->info.numOptions));
467 if (OC_STACK_OK != rmResult)
469 OC_LOG(ERROR, TAG, "Add destination option failed");
474 // OC stack prefer CBOR encoded payloads.
475 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
476 CAResult_t result = CASendRequest(object, requestInfo);
477 if(CA_STATUS_OK != result)
479 OC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
480 return CAResultToOCResult(result);
484 //-----------------------------------------------------------------------------
485 // Internal API function
486 //-----------------------------------------------------------------------------
488 // This internal function is called to update the stack with the status of
489 // observers and communication failures
490 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
492 OCStackResult result = OC_STACK_ERROR;
493 ResourceObserver * observer = NULL;
494 OCEntityHandlerRequest ehRequest = {0};
498 case OC_OBSERVER_NOT_INTERESTED:
499 OC_LOG(DEBUG, TAG, "observer not interested in our notifications");
500 observer = GetObserverUsingToken (token, tokenLength);
503 result = FormOCEntityHandlerRequest(&ehRequest,
504 (OCRequestHandle)NULL,
507 (OCResourceHandle)NULL,
508 NULL, PAYLOAD_TYPE_REPRESENTATION,
510 OC_OBSERVE_DEREGISTER,
511 observer->observeId);
512 if(result != OC_STACK_OK)
516 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
517 observer->resource->entityHandlerCallbackParam);
520 result = DeleteObserverUsingToken (token, tokenLength);
521 if(result == OC_STACK_OK)
523 OC_LOG(DEBUG, TAG, "Removed observer successfully");
527 result = OC_STACK_OK;
528 OC_LOG(DEBUG, TAG, "Observer Removal failed");
532 case OC_OBSERVER_STILL_INTERESTED:
533 OC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
534 observer = GetObserverUsingToken (token, tokenLength);
537 observer->forceHighQos = 0;
538 observer->failedCommCount = 0;
539 result = OC_STACK_OK;
543 result = OC_STACK_OBSERVER_NOT_FOUND;
547 case OC_OBSERVER_FAILED_COMM:
548 OC_LOG(DEBUG, TAG, "observer is unreachable");
549 observer = GetObserverUsingToken (token, tokenLength);
552 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
554 result = FormOCEntityHandlerRequest(&ehRequest,
555 (OCRequestHandle)NULL,
558 (OCResourceHandle)NULL,
559 NULL, PAYLOAD_TYPE_REPRESENTATION,
561 OC_OBSERVE_DEREGISTER,
562 observer->observeId);
563 if(result != OC_STACK_OK)
565 return OC_STACK_ERROR;
567 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
568 observer->resource->entityHandlerCallbackParam);
570 result = DeleteObserverUsingToken (token, tokenLength);
571 if(result == OC_STACK_OK)
573 OC_LOG(DEBUG, TAG, "Removed observer successfully");
577 result = OC_STACK_OK;
578 OC_LOG(DEBUG, TAG, "Observer Removal failed");
583 observer->failedCommCount++;
584 result = OC_STACK_CONTINUE;
586 observer->forceHighQos = 1;
587 OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
591 OC_LOG(ERROR, TAG, "Unknown status");
592 result = OC_STACK_ERROR;
597 OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
599 OCStackResult ret = OC_STACK_ERROR;
604 ret = OC_STACK_RESOURCE_CREATED;
607 ret = OC_STACK_RESOURCE_DELETED;
614 ret = OC_STACK_INVALID_QUERY;
616 case CA_UNAUTHORIZED_REQ:
617 ret = OC_STACK_UNAUTHORIZED_REQ;
620 ret = OC_STACK_INVALID_OPTION;
623 ret = OC_STACK_NO_RESOURCE;
625 case CA_RETRANSMIT_TIMEOUT:
626 ret = OC_STACK_COMM_ERROR;
634 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
636 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
645 // This Response Code is like HTTP 204 "No Content" but only used in
646 // response to POST and PUT requests.
650 // This Response Code is like HTTP 200 "OK" but only used in response to
655 // This should not happen but,
656 // give it a value just in case but output an error
658 OC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].", method);
661 case OC_STACK_RESOURCE_CREATED:
664 case OC_STACK_RESOURCE_DELETED:
667 case OC_STACK_INVALID_QUERY:
670 case OC_STACK_INVALID_OPTION:
673 case OC_STACK_NO_RESOURCE:
676 case OC_STACK_COMM_ERROR:
677 ret = CA_RETRANSMIT_TIMEOUT;
679 case OC_STACK_UNAUTHORIZED_REQ:
680 ret = CA_UNAUTHORIZED_REQ;
688 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
690 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
692 // supply default behavior.
693 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
695 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
697 if ((caFlags & OC_MASK_SCOPE) == 0)
699 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
704 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
706 return (OCTransportFlags)caFlags;
709 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
711 uint32_t lowerBound = 0;
712 uint32_t higherBound = 0;
714 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
716 return OC_STACK_INVALID_PARAM;
719 OC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
721 cbNode->presence->TTL = maxAgeSeconds;
723 for (int index = 0; index < PresenceTimeOutSize; index++)
725 // Guard against overflow
726 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
729 lowerBound = GetTicks((PresenceTimeOut[index] *
730 cbNode->presence->TTL *
731 MILLISECONDS_PER_SECOND)/100);
735 lowerBound = GetTicks(UINT32_MAX);
738 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
741 higherBound = GetTicks((PresenceTimeOut[index + 1] *
742 cbNode->presence->TTL *
743 MILLISECONDS_PER_SECOND)/100);
747 higherBound = GetTicks(UINT32_MAX);
750 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
752 OC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
753 OC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
754 OC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
757 cbNode->presence->TTLlevel = 0;
759 OC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
763 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
765 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
767 return OC_RSRVD_TRIGGER_CREATE;
769 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
771 return OC_RSRVD_TRIGGER_CHANGE;
775 return OC_RSRVD_TRIGGER_DELETE;
779 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
783 return OC_PRESENCE_TRIGGER_CREATE;
785 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
787 return OC_PRESENCE_TRIGGER_CREATE;
789 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
791 return OC_PRESENCE_TRIGGER_CHANGE;
795 return OC_PRESENCE_TRIGGER_DELETE;
800 * The cononical presence allows constructed URIs to be string compared.
802 * requestUri must be a char array of size CA_MAX_URI_LENGTH
804 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
807 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
808 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
809 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
811 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
813 if (ep->adapter == CA_ADAPTER_IP)
815 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
817 if ('\0' == ep->addr[0]) // multicast
819 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
823 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
824 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
829 if ('\0' == ep->addr[0]) // multicast
831 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
832 ep->port = OC_MULTICAST_PORT;
834 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
835 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
839 // might work for other adapters (untested, but better than nothing)
840 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
841 OC_RSRVD_PRESENCE_URI);
845 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
846 const CAResponseInfo_t *responseInfo)
848 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
849 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
851 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
852 ClientCB * cbNode = NULL;
853 char *resourceTypeName = NULL;
854 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
855 OCStackResult result = OC_STACK_ERROR;
858 char presenceUri[CA_MAX_URI_LENGTH];
860 int presenceSubscribe = 0;
861 int multicastPresenceSubscribe = 0;
863 if (responseInfo->result != CA_CONTENT)
865 OC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
866 return OC_STACK_ERROR;
869 // check for unicast presence
870 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri);
871 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
873 return OC_STACK_INVALID_URI;
876 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
879 presenceSubscribe = 1;
883 // check for multiicast presence
884 CAEndpoint_t ep = { .adapter = endpoint->adapter,
885 .flags = endpoint->flags };
887 uriLen = FormCanonicalPresenceUri(&ep, OC_RSRVD_PRESENCE_URI, presenceUri);
889 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
892 multicastPresenceSubscribe = 1;
896 if (!presenceSubscribe && !multicastPresenceSubscribe)
898 OC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
902 response.payload = NULL;
903 response.result = OC_STACK_OK;
905 CopyEndpointToDevAddr(endpoint, &response.devAddr);
906 FixUpClientResponse(&response);
908 if (responseInfo->info.payload)
910 result = OCParsePayload(&response.payload,
911 PAYLOAD_TYPE_PRESENCE,
912 responseInfo->info.payload,
913 responseInfo->info.payloadSize);
915 if(result != OC_STACK_OK)
917 OC_LOG(ERROR, TAG, "Presence parse failed");
920 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
922 OC_LOG(ERROR, TAG, "Presence payload was wrong type");
923 result = OC_STACK_ERROR;
926 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
927 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
928 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
931 if (presenceSubscribe)
933 if(cbNode->sequenceNumber == response.sequenceNumber)
935 OC_LOG(INFO, TAG, "No presence change");
936 ResetPresenceTTL(cbNode, maxAge);
937 OC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
943 OC_LOG(INFO, TAG, "Stopping presence");
944 response.result = OC_STACK_PRESENCE_STOPPED;
947 OICFree(cbNode->presence->timeOut);
948 OICFree(cbNode->presence);
949 cbNode->presence = NULL;
954 if(!cbNode->presence)
956 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
958 if(!(cbNode->presence))
960 OC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
961 result = OC_STACK_NO_MEMORY;
965 VERIFY_NON_NULL_V(cbNode->presence);
966 cbNode->presence->timeOut = NULL;
967 cbNode->presence->timeOut = (uint32_t *)
968 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
969 if(!(cbNode->presence->timeOut)){
971 "Could not allocate memory for cbNode->presence->timeOut");
972 OICFree(cbNode->presence);
973 result = OC_STACK_NO_MEMORY;
978 ResetPresenceTTL(cbNode, maxAge);
980 cbNode->sequenceNumber = response.sequenceNumber;
982 // Ensure that a filter is actually applied.
983 if( resourceTypeName && cbNode->filterResourceType)
985 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
994 // This is the multicast case
995 OCMulticastNode* mcNode = NULL;
996 mcNode = GetMCPresenceNode(presenceUri);
1000 if(mcNode->nonce == response.sequenceNumber)
1002 OC_LOG(INFO, TAG, "No presence change (Multicast)");
1005 mcNode->nonce = response.sequenceNumber;
1009 OC_LOG(INFO, TAG, "Stopping presence");
1010 response.result = OC_STACK_PRESENCE_STOPPED;
1015 char* uri = OICStrdup(presenceUri);
1019 "No Memory for URI to store in the presence node");
1020 result = OC_STACK_NO_MEMORY;
1024 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1025 if(result == OC_STACK_NO_MEMORY)
1028 "No Memory for Multicast Presence Node");
1032 // presence node now owns uri
1035 // Ensure that a filter is actually applied.
1036 if(resourceTypeName && cbNode->filterResourceType)
1038 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1045 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1047 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1049 FindAndDeleteClientCB(cbNode);
1053 OCPayloadDestroy(response.payload);
1057 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1059 VERIFY_NON_NULL_NR(endPoint, FATAL);
1060 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1062 OC_LOG(INFO, TAG, "Enter HandleCAResponses");
1064 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1065 #ifdef ROUTING_GATEWAY
1066 bool needRIHandling = false;
1068 * Routing manager is going to update either of endpoint or response or both.
1069 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1070 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1073 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1075 if(ret != OC_STACK_OK || !needRIHandling)
1077 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1083 * Put source in sender endpoint so that the next packet from application can be routed to
1084 * proper destination and remove "RM" coap header option before passing request / response to
1085 * RI as this option will make no sense to either RI or application.
1087 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1088 (uint8_t *) &(responseInfo->info.numOptions),
1089 (CAEndpoint_t *) endPoint);
1092 if(responseInfo->info.resourceUri &&
1093 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1095 HandlePresenceResponse(endPoint, responseInfo);
1099 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1100 responseInfo->info.tokenLength, NULL, NULL);
1102 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1103 responseInfo->info.tokenLength);
1107 OC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1108 if(responseInfo->result == CA_EMPTY)
1110 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1111 // We do not have a case for the client to receive a RESET
1112 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1114 //This is the case of receiving an ACK on a request to a slow resource!
1115 OC_LOG(INFO, TAG, "This is a pure ACK");
1116 //TODO: should we inform the client
1117 // app that at least the request was received at the server?
1120 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1122 OC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1123 OC_LOG(INFO, TAG, "Calling into application address space");
1125 OCClientResponse response =
1126 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1127 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1128 FixUpClientResponse(&response);
1129 response.resourceUri = responseInfo->info.resourceUri;
1130 memcpy(response.identity.id, responseInfo->info.identity.id,
1131 sizeof (response.identity.id));
1132 response.identity.id_length = responseInfo->info.identity.id_length;
1134 response.result = CAToOCStackResult(responseInfo->result);
1135 cbNode->callBack(cbNode->context,
1136 cbNode->handle, &response);
1137 FindAndDeleteClientCB(cbNode);
1141 OC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1142 OC_LOG(INFO, TAG, "Calling into application address space");
1144 OCClientResponse response =
1145 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1146 response.sequenceNumber = OC_OBSERVE_NO_OPTION;
1147 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1148 FixUpClientResponse(&response);
1149 response.resourceUri = responseInfo->info.resourceUri;
1150 memcpy(response.identity.id, responseInfo->info.identity.id,
1151 sizeof (response.identity.id));
1152 response.identity.id_length = responseInfo->info.identity.id_length;
1154 response.result = CAToOCStackResult(responseInfo->result);
1156 if(responseInfo->info.payload &&
1157 responseInfo->info.payloadSize)
1159 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1160 // check the security resource
1161 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1163 type = PAYLOAD_TYPE_SECURITY;
1165 else if (cbNode->method == OC_REST_DISCOVER)
1167 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1168 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1170 type = PAYLOAD_TYPE_DISCOVERY;
1172 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1174 type = PAYLOAD_TYPE_DEVICE;
1176 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1178 type = PAYLOAD_TYPE_PLATFORM;
1180 #ifdef ROUTING_GATEWAY
1181 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1183 type = PAYLOAD_TYPE_REPRESENTATION;
1186 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1188 type = PAYLOAD_TYPE_RD;
1192 OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1193 cbNode->method, cbNode->requestUri);
1197 else if (cbNode->method == OC_REST_GET ||
1198 cbNode->method == OC_REST_PUT ||
1199 cbNode->method == OC_REST_POST ||
1200 cbNode->method == OC_REST_OBSERVE ||
1201 cbNode->method == OC_REST_OBSERVE_ALL ||
1202 cbNode->method == OC_REST_DELETE)
1204 char targetUri[MAX_URI_LENGTH];
1205 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
1206 OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1207 if (strcmp(targetUri, cbNode->requestUri) == 0)
1209 type = PAYLOAD_TYPE_RD;
1211 if (type == PAYLOAD_TYPE_INVALID)
1213 OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1214 cbNode->method, cbNode->requestUri);
1215 type = PAYLOAD_TYPE_REPRESENTATION;
1220 OC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1221 cbNode->method, cbNode->requestUri);
1225 if(OC_STACK_OK != OCParsePayload(&response.payload,
1227 responseInfo->info.payload,
1228 responseInfo->info.payloadSize))
1230 OC_LOG(ERROR, TAG, "Error converting payload");
1231 OCPayloadDestroy(response.payload);
1236 response.numRcvdVendorSpecificHeaderOptions = 0;
1237 if(responseInfo->info.numOptions > 0)
1240 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1241 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1244 uint32_t observationOption;
1245 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1246 for (observationOption=0, i=0;
1247 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1251 (observationOption << 8) | optionData[i];
1253 response.sequenceNumber = observationOption;
1255 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1260 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1263 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1265 OC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1266 OCPayloadDestroy(response.payload);
1270 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1272 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1273 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1277 if (cbNode->method == OC_REST_OBSERVE &&
1278 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1279 response.sequenceNumber <= cbNode->sequenceNumber)
1281 OC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1282 response.sequenceNumber);
1286 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1289 cbNode->sequenceNumber = response.sequenceNumber;
1291 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1293 FindAndDeleteClientCB(cbNode);
1297 // To keep discovery callbacks active.
1298 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1299 MILLISECONDS_PER_SECOND);
1303 //Need to send ACK when the response is CON
1304 if(responseInfo->info.type == CA_MSG_CONFIRM)
1306 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1307 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL);
1310 OCPayloadDestroy(response.payload);
1317 OC_LOG(INFO, TAG, "There is an observer associated with the response token");
1318 if(responseInfo->result == CA_EMPTY)
1320 OC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1321 if(responseInfo->info.type == CA_MSG_RESET)
1323 OC_LOG(INFO, TAG, "This is a RESET");
1324 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1325 OC_OBSERVER_NOT_INTERESTED);
1327 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1329 OC_LOG(INFO, TAG, "This is a pure ACK");
1330 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1331 OC_OBSERVER_STILL_INTERESTED);
1334 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1336 OC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1337 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1338 OC_OBSERVER_FAILED_COMM);
1343 if(!cbNode && !observer)
1345 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1346 || myStackMode == OC_GATEWAY)
1348 OC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1349 if(responseInfo->result == CA_EMPTY)
1351 OC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1355 OC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1356 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1357 CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
1361 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1362 || myStackMode == OC_GATEWAY)
1364 OC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1365 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1367 OC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1368 responseInfo->info.messageId);
1370 if (responseInfo->info.type == CA_MSG_RESET)
1372 OC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1373 responseInfo->info.messageId);
1380 OC_LOG(INFO, TAG, "Exit HandleCAResponses");
1384 * This function handles error response from CA
1385 * code shall be added to handle the errors
1387 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
1389 OC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1391 if(NULL == endPoint)
1393 OC_LOG(ERROR, TAG, "endPoint is NULL");
1397 if(NULL == errrorInfo)
1399 OC_LOG(ERROR, TAG, "errrorInfo is NULL");
1402 OC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1406 * This function sends out Direct Stack Responses. These are responses that are not coming
1407 * from the application entity handler. These responses have no payload and are usually ACKs,
1408 * RESETs or some error conditions that were caught by the stack.
1410 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1411 const CAResponseResult_t responseResult, const CAMessageType_t type,
1412 const uint8_t numOptions, const CAHeaderOption_t *options,
1413 CAToken_t token, uint8_t tokenLength, const char *resourceUri)
1415 CAResponseInfo_t respInfo = {
1416 .result = responseResult
1418 respInfo.info.messageId = coapID;
1419 respInfo.info.numOptions = numOptions;
1421 if (respInfo.info.numOptions)
1423 respInfo.info.options =
1424 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1425 memcpy (respInfo.info.options, options,
1426 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1430 respInfo.info.payload = NULL;
1431 respInfo.info.token = token;
1432 respInfo.info.tokenLength = tokenLength;
1433 respInfo.info.type = type;
1434 respInfo.info.resourceUri = OICStrdup (resourceUri);
1435 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1437 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1438 // Add the destination to route option from the endpoint->routeData.
1439 OCStackResult result = RMAddInfo(endPoint->routeData,
1440 &(respInfo.info.options),
1441 &(respInfo.info.numOptions));
1442 if(OC_STACK_OK != result)
1444 OC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1449 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1451 // resourceUri in the info field is cloned in the CA layer and
1452 // thus ownership is still here.
1453 OICFree (respInfo.info.resourceUri);
1454 OICFree (respInfo.info.options);
1455 if(CA_STATUS_OK != caResult)
1457 OC_LOG(ERROR, TAG, "CASendResponse error");
1458 return CAResultToOCResult(caResult);
1463 //This function will be called back by CA layer when a request is received
1464 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1466 OC_LOG(INFO, TAG, "Enter HandleCARequests");
1469 OC_LOG(ERROR, TAG, "endPoint is NULL");
1475 OC_LOG(ERROR, TAG, "requestInfo is NULL");
1479 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1480 #ifdef ROUTING_GATEWAY
1481 bool needRIHandling = false;
1483 * Routing manager is going to update either of endpoint or request or both.
1484 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
1485 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1486 * destination. It can also remove "RM" coap header option before passing request / response to
1487 * RI as this option will make no sense to either RI or application.
1489 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
1491 if(OC_STACK_OK != ret || !needRIHandling)
1493 OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1499 * Put source in sender endpoint so that the next packet from application can be routed to
1500 * proper destination and remove RM header option.
1502 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
1503 (uint8_t *) &(requestInfo->info.numOptions),
1504 (CAEndpoint_t *) endPoint);
1507 OCStackResult requestResult = OC_STACK_ERROR;
1509 if(myStackMode == OC_CLIENT)
1511 //TODO: should the client be responding to requests?
1515 OCServerProtocolRequest serverRequest = {0};
1517 OC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1519 char * uriWithoutQuery = NULL;
1520 char * query = NULL;
1522 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1524 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1526 OC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1529 OC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1530 OC_LOG_V(INFO, TAG, "Query : %s", query);
1532 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1534 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1535 OICFree(uriWithoutQuery);
1539 OC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1540 OICFree(uriWithoutQuery);
1547 if(strlen(query) < MAX_QUERY_LENGTH)
1549 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1554 OC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1560 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1562 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1563 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1564 memcpy (serverRequest.payload, requestInfo->info.payload,
1565 requestInfo->info.payloadSize);
1569 serverRequest.reqTotalSize = 0;
1572 switch (requestInfo->method)
1575 serverRequest.method = OC_REST_GET;
1578 serverRequest.method = OC_REST_PUT;
1581 serverRequest.method = OC_REST_POST;
1584 serverRequest.method = OC_REST_DELETE;
1587 OC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1588 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1589 requestInfo->info.type, requestInfo->info.numOptions,
1590 requestInfo->info.options, requestInfo->info.token,
1591 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1592 OICFree(serverRequest.payload);
1596 OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1597 requestInfo->info.tokenLength);
1598 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1599 serverRequest.tokenLength = requestInfo->info.tokenLength;
1601 if (!serverRequest.requestToken)
1603 OC_LOG(FATAL, TAG, "Allocation for token failed.");
1604 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1605 requestInfo->info.type, requestInfo->info.numOptions,
1606 requestInfo->info.options, requestInfo->info.token,
1607 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1608 OICFree(serverRequest.payload);
1611 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1613 switch (requestInfo->info.acceptFormat)
1615 case CA_FORMAT_APPLICATION_CBOR:
1616 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1618 case CA_FORMAT_UNDEFINED:
1619 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1622 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1625 if (requestInfo->info.type == CA_MSG_CONFIRM)
1627 serverRequest.qos = OC_HIGH_QOS;
1631 serverRequest.qos = OC_LOW_QOS;
1633 // CA does not need the following field
1634 // Are we sure CA does not need them? how is it responding to multicast
1635 serverRequest.delayedResNeeded = 0;
1637 serverRequest.coapID = requestInfo->info.messageId;
1639 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1641 // copy vendor specific header options
1642 uint8_t tempNum = (requestInfo->info.numOptions);
1644 // Assume no observation requested and it is a pure GET.
1645 // If obs registration/de-registration requested it'll be fetched from the
1646 // options in GetObserveHeaderOption()
1647 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1649 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1650 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1653 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1654 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1655 requestInfo->info.type, requestInfo->info.numOptions,
1656 requestInfo->info.options, requestInfo->info.token,
1657 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1658 OICFree(serverRequest.payload);
1659 OICFree(serverRequest.requestToken);
1662 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1663 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1665 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1666 sizeof(CAHeaderOption_t)*tempNum);
1669 requestResult = HandleStackRequests (&serverRequest);
1671 // Send ACK to client as precursor to slow response
1672 if(requestResult == OC_STACK_SLOW_RESOURCE)
1674 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1675 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
1677 else if(requestResult != OC_STACK_OK)
1679 OC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1681 CAResponseResult_t stackResponse =
1682 OCToCAStackResult(requestResult, serverRequest.method);
1684 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1685 requestInfo->info.type, requestInfo->info.numOptions,
1686 requestInfo->info.options, requestInfo->info.token,
1687 requestInfo->info.tokenLength, requestInfo->info.resourceUri);
1689 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1690 // The token is copied in there, and is thus still owned by this function.
1691 OICFree(serverRequest.payload);
1692 OICFree(serverRequest.requestToken);
1693 OC_LOG(INFO, TAG, "Exit HandleCARequests");
1696 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1698 OC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1699 OCStackResult result = OC_STACK_ERROR;
1700 ResourceHandling resHandling;
1701 OCResource *resource;
1702 if(!protocolRequest)
1704 OC_LOG(ERROR, TAG, "protocolRequest is NULL");
1705 return OC_STACK_INVALID_PARAM;
1708 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1709 protocolRequest->tokenLength);
1712 OC_LOG(INFO, TAG, "This is a new Server Request");
1713 result = AddServerRequest(&request, protocolRequest->coapID,
1714 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1715 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1716 protocolRequest->observationOption, protocolRequest->qos,
1717 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1718 protocolRequest->payload, protocolRequest->requestToken,
1719 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1720 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1721 &protocolRequest->devAddr);
1722 if (OC_STACK_OK != result)
1724 OC_LOG(ERROR, TAG, "Error adding server request");
1730 OC_LOG(ERROR, TAG, "Out of Memory");
1731 return OC_STACK_NO_MEMORY;
1734 if(!protocolRequest->reqMorePacket)
1736 request->requestComplete = 1;
1741 OC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1744 if(request->requestComplete)
1746 OC_LOG(INFO, TAG, "This Server Request is complete");
1747 result = DetermineResourceHandling (request, &resHandling, &resource);
1748 if (result == OC_STACK_OK)
1750 result = ProcessRequest(resHandling, resource, request);
1755 OC_LOG(INFO, TAG, "This Server Request is incomplete");
1756 result = OC_STACK_CONTINUE;
1761 bool validatePlatformInfo(OCPlatformInfo info)
1764 if (!info.platformID)
1766 OC_LOG(ERROR, TAG, "No platform ID found.");
1770 if (info.manufacturerName)
1772 size_t lenManufacturerName = strlen(info.manufacturerName);
1774 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
1776 OC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
1782 OC_LOG(ERROR, TAG, "No manufacturer name present");
1786 if (info.manufacturerUrl)
1788 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
1790 OC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
1797 //-----------------------------------------------------------------------------
1799 //-----------------------------------------------------------------------------
1801 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
1804 !raInfo->username ||
1805 !raInfo->hostname ||
1806 !raInfo->xmpp_domain)
1809 return OC_STACK_INVALID_PARAM;
1811 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
1812 gRASetInfo = (result == OC_STACK_OK)? true : false;
1818 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
1822 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
1825 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
1827 if(stackState == OC_STACK_INITIALIZED)
1829 OC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
1830 OCStop() between them are ignored.");
1834 #ifndef ROUTING_GATEWAY
1835 if (OC_GATEWAY == mode)
1837 OC_LOG(ERROR, TAG, "Routing Manager not supported");
1838 return OC_STACK_INVALID_PARAM;
1845 OC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
1846 return OC_STACK_ERROR;
1850 OCStackResult result = OC_STACK_ERROR;
1851 OC_LOG(INFO, TAG, "Entering OCInit");
1854 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
1855 || (mode == OC_GATEWAY)))
1857 OC_LOG(ERROR, TAG, "Invalid mode");
1858 return OC_STACK_ERROR;
1862 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1864 caglobals.client = true;
1866 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
1868 caglobals.server = true;
1871 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
1872 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
1874 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
1876 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
1877 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
1879 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
1882 defaultDeviceHandler = NULL;
1883 defaultDeviceHandlerCallbackParameter = NULL;
1885 result = CAResultToOCResult(CAInitialize());
1886 VERIFY_SUCCESS(result, OC_STACK_OK);
1888 result = CAResultToOCResult(OCSelectNetwork());
1889 VERIFY_SUCCESS(result, OC_STACK_OK);
1891 switch (myStackMode)
1894 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1895 result = CAResultToOCResult(CAStartDiscoveryServer());
1896 OC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
1899 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1900 result = CAResultToOCResult(CAStartListeningServer());
1901 OC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
1903 case OC_CLIENT_SERVER:
1905 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
1906 result = CAResultToOCResult(CAStartListeningServer());
1907 if(result == OC_STACK_OK)
1909 result = CAResultToOCResult(CAStartDiscoveryServer());
1913 VERIFY_SUCCESS(result, OC_STACK_OK);
1915 #ifdef WITH_PRESENCE
1916 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
1917 #endif // WITH_PRESENCE
1919 //Update Stack state to initialized
1920 stackState = OC_STACK_INITIALIZED;
1922 // Initialize resource
1923 if(myStackMode != OC_CLIENT)
1925 result = initResources();
1928 // Initialize the SRM Policy Engine
1929 if(result == OC_STACK_OK)
1931 result = SRMInitPolicyEngine();
1932 // TODO after BeachHead delivery: consolidate into single SRMInit()
1935 #ifdef ROUTING_GATEWAY
1936 if (OC_GATEWAY == myStackMode)
1938 result = RMInitialize();
1943 if(result != OC_STACK_OK)
1945 OC_LOG(ERROR, TAG, "Stack initialization error");
1946 deleteAllResources();
1948 stackState = OC_STACK_UNINITIALIZED;
1953 OCStackResult OCStop()
1955 OC_LOG(INFO, TAG, "Entering OCStop");
1957 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
1959 OC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
1962 else if (stackState != OC_STACK_INITIALIZED)
1964 OC_LOG(ERROR, TAG, "Stack not initialized");
1965 return OC_STACK_ERROR;
1968 stackState = OC_STACK_UNINIT_IN_PROGRESS;
1970 #ifdef WITH_PRESENCE
1971 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
1972 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
1973 presenceResource.presenceTTL = 0;
1974 #endif // WITH_PRESENCE
1976 #ifdef ROUTING_GATEWAY
1977 if (OC_GATEWAY == myStackMode)
1983 // Free memory dynamically allocated for resources
1984 deleteAllResources();
1986 DeletePlatformInfo();
1988 // Remove all observers
1989 DeleteObserverList();
1990 // Remove all the client callbacks
1991 DeleteClientCBList();
1993 // De-init the SRM Policy Engine
1994 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
1995 SRMDeInitPolicyEngine();
1998 stackState = OC_STACK_UNINITIALIZED;
2002 OCStackResult OCStartMulticastServer()
2004 if(stackState != OC_STACK_INITIALIZED)
2006 OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2007 return OC_STACK_ERROR;
2009 CAResult_t ret = CAStartListeningServer();
2010 if (CA_STATUS_OK != ret)
2012 OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2013 return OC_STACK_ERROR;
2018 OCStackResult OCStopMulticastServer()
2020 CAResult_t ret = CAStopListeningServer();
2021 if (CA_STATUS_OK != ret)
2023 OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2024 return OC_STACK_ERROR;
2029 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2034 return CA_MSG_CONFIRM;
2039 return CA_MSG_NONCONFIRM;
2043 OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
2047 query = strchr (inputUri, '?');
2051 if((query - inputUri) > MAX_URI_LENGTH)
2053 return OC_STACK_INVALID_URI;
2056 if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
2058 return OC_STACK_INVALID_QUERY;
2061 else if(uriLen > MAX_URI_LENGTH)
2063 return OC_STACK_INVALID_URI;
2069 * A request uri consists of the following components in order:
2072 * CoAP over UDP prefix "coap://"
2073 * CoAP over TCP prefix "coap+tcp://"
2075 * IPv6 address "[1234::5678]"
2076 * IPv4 address "192.168.1.1"
2077 * optional port ":5683"
2078 * resource uri "/oc/core..."
2080 * for PRESENCE requests, extract resource type.
2082 static OCStackResult ParseRequestUri(const char *fullUri,
2083 OCTransportAdapter adapter,
2084 OCTransportFlags flags,
2085 OCDevAddr **devAddr,
2087 char **resourceType)
2089 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2091 OCStackResult result = OC_STACK_OK;
2092 OCDevAddr *da = NULL;
2096 // provide defaults for all returned values
2103 *resourceUri = NULL;
2107 *resourceType = NULL;
2110 // delimit url prefix, if any
2111 const char *start = fullUri;
2112 char *slash2 = strstr(start, "//");
2117 char *slash = strchr(start, '/');
2120 return OC_STACK_INVALID_URI;
2123 // process url scheme
2124 size_t prefixLen = slash2 - fullUri;
2128 if ((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
2134 // TODO: this logic should come in with unit tests exercising the various strings
2135 // processs url prefix, if any
2136 size_t urlLen = slash - start;
2140 if (urlLen && devAddr)
2141 { // construct OCDevAddr
2142 if (start[0] == '[')
2144 char *close = strchr(++start, ']');
2145 if (!close || close > slash)
2147 return OC_STACK_INVALID_URI;
2150 if (close[1] == ':')
2154 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2155 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2159 char *dot = strchr(start, '.');
2160 if (dot && dot < slash)
2162 colon = strchr(start, ':');
2163 end = (colon && colon < slash) ? colon : slash;
2167 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2171 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2172 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2181 if (len >= sizeof(da->addr))
2183 return OC_STACK_INVALID_URI;
2185 // collect port, if any
2186 if (colon && colon < slash)
2188 for (colon++; colon < slash; colon++)
2191 if (c < '0' || c > '9')
2193 return OC_STACK_INVALID_URI;
2195 port = 10 * port + c - '0';
2200 if (len >= sizeof(da->addr))
2202 return OC_STACK_INVALID_URI;
2205 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2208 return OC_STACK_NO_MEMORY;
2210 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2212 da->adapter = adapter;
2214 if (!strncmp(fullUri, "coaps:", 6))
2216 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2221 // process resource uri, if any
2223 { // request uri and query
2224 size_t ulen = strlen(slash); // resource uri length
2225 size_t tlen = 0; // resource type length
2228 static const char strPresence[] = "/oic/ad?rt=";
2229 static const size_t lenPresence = sizeof(strPresence) - 1;
2230 if (!strncmp(slash, strPresence, lenPresence))
2232 type = slash + lenPresence;
2233 tlen = ulen - lenPresence;
2238 *resourceUri = (char *)OICMalloc(ulen + 1);
2241 result = OC_STACK_NO_MEMORY;
2244 strcpy(*resourceUri, slash);
2247 if (type && resourceType)
2249 *resourceType = (char *)OICMalloc(tlen + 1);
2252 result = OC_STACK_NO_MEMORY;
2256 OICStrcpy(*resourceType, (tlen+1), type);
2263 // free all returned values
2270 OICFree(*resourceUri);
2274 OICFree(*resourceType);
2279 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2280 char *resourceUri, char **requestUri)
2282 char uri[CA_MAX_URI_LENGTH];
2284 FormCanonicalPresenceUri(endpoint, resourceUri, uri);
2286 *requestUri = OICStrdup(uri);
2289 return OC_STACK_NO_MEMORY;
2296 * Discover or Perform requests on a specified resource
2298 OCStackResult OCDoResource(OCDoHandle *handle,
2300 const char *requestUri,
2301 const OCDevAddr *destination,
2303 OCConnectivityType connectivityType,
2304 OCQualityOfService qos,
2305 OCCallbackData *cbData,
2306 OCHeaderOption *options,
2309 OC_LOG(INFO, TAG, "Entering OCDoResource");
2311 // Validate input parameters
2312 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2313 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2314 VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
2316 OCStackResult result = OC_STACK_ERROR;
2317 CAResult_t caResult;
2318 CAToken_t token = NULL;
2319 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2320 ClientCB *clientCB = NULL;
2321 OCDoHandle resHandle = NULL;
2322 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2323 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2325 OCTransportAdapter adapter;
2326 OCTransportFlags flags;
2327 // the request contents are put here
2328 CARequestInfo_t requestInfo = {.method = CA_GET};
2329 // requestUri will be parsed into the following three variables
2330 OCDevAddr *devAddr = NULL;
2331 char *resourceUri = NULL;
2332 char *resourceType = NULL;
2334 // This validation is broken, but doesn't cause harm
2335 size_t uriLen = strlen(requestUri );
2336 if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
2342 * Support original behavior with address on resourceUri argument.
2344 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2345 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2347 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2349 if (result != OC_STACK_OK)
2351 OC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2358 case OC_REST_OBSERVE:
2359 case OC_REST_OBSERVE_ALL:
2360 case OC_REST_CANCEL_OBSERVE:
2361 requestInfo.method = CA_GET;
2364 requestInfo.method = CA_PUT;
2367 requestInfo.method = CA_POST;
2369 case OC_REST_DELETE:
2370 requestInfo.method = CA_DELETE;
2372 case OC_REST_DISCOVER:
2374 if (destination || devAddr)
2376 requestInfo.isMulticast = false;
2380 tmpDevAddr.adapter = adapter;
2381 tmpDevAddr.flags = flags;
2382 destination = &tmpDevAddr;
2383 requestInfo.isMulticast = true;
2385 // CA_DISCOVER will become GET and isMulticast
2386 requestInfo.method = CA_GET;
2388 #ifdef WITH_PRESENCE
2389 case OC_REST_PRESENCE:
2390 // Replacing method type with GET because "presence"
2391 // is a stack layer only implementation.
2392 requestInfo.method = CA_GET;
2396 result = OC_STACK_INVALID_METHOD;
2400 if (!devAddr && !destination)
2402 OC_LOG(DEBUG, TAG, "no devAddr and no destination");
2403 result = OC_STACK_INVALID_PARAM;
2407 /* If not original behavior, use destination argument */
2408 if (destination && !devAddr)
2410 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2413 result = OC_STACK_NO_MEMORY;
2416 *devAddr = *destination;
2419 resHandle = GenerateInvocationHandle();
2422 result = OC_STACK_NO_MEMORY;
2426 caResult = CAGenerateToken(&token, tokenLength);
2427 if (caResult != CA_STATUS_OK)
2429 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2430 result= OC_STACK_ERROR;
2434 // fill in request data
2435 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2436 requestInfo.info.token = token;
2437 requestInfo.info.tokenLength = tokenLength;
2438 requestInfo.info.resourceUri = resourceUri;
2440 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2442 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2443 options, numOptions, OC_OBSERVE_REGISTER);
2444 if (result != OC_STACK_OK)
2448 requestInfo.info.numOptions = numOptions + 1;
2452 requestInfo.info.numOptions = numOptions;
2453 requestInfo.info.options =
2454 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2455 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2456 numOptions * sizeof(CAHeaderOption_t));
2459 CopyDevAddrToEndpoint(devAddr, &endpoint);
2464 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2467 OC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2470 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2474 requestInfo.info.payload = NULL;
2475 requestInfo.info.payloadSize = 0;
2476 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2479 if (result != OC_STACK_OK)
2481 OC_LOG(ERROR, TAG, "CACreateEndpoint error");
2485 // prepare for response
2486 #ifdef WITH_PRESENCE
2487 if (method == OC_REST_PRESENCE)
2489 char *presenceUri = NULL;
2490 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri);
2491 if (OC_STACK_OK != result)
2496 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2497 // Presence notification will form a canonical uri to
2498 // look for callbacks into the application.
2499 resourceUri = presenceUri;
2503 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2504 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2505 method, devAddr, resourceUri, resourceType, ttl);
2506 if (OC_STACK_OK != result)
2511 devAddr = NULL; // Client CB list entry now owns it
2512 resourceUri = NULL; // Client CB list entry now owns it
2513 resourceType = NULL; // Client CB list entry now owns it
2516 result = OCSendRequest(&endpoint, &requestInfo);
2517 if (OC_STACK_OK != result)
2524 *handle = resHandle;
2528 if (result != OC_STACK_OK)
2530 OC_LOG(ERROR, TAG, "OCDoResource error");
2531 FindAndDeleteClientCB(clientCB);
2532 CADestroyToken(token);
2540 // This is the owner of the payload object, so we free it
2541 OCPayloadDestroy(payload);
2542 OICFree(requestInfo.info.payload);
2544 OICFree(resourceUri);
2545 OICFree(resourceType);
2546 OICFree(requestInfo.info.options);
2550 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2554 * This ftn is implemented one of two ways in the case of observation:
2556 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2557 * Remove the callback associated on client side.
2558 * When the next notification comes in from server,
2559 * reply with RESET message to server.
2560 * Keep in mind that the server will react to RESET only
2561 * if the last notification was sent as CON
2563 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2564 * and it is associated with an observe request
2565 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2566 * Send CON Observe request to server with
2567 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2568 * Remove the callback associated on client side.
2570 OCStackResult ret = OC_STACK_OK;
2571 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2572 CARequestInfo_t requestInfo = {.method = CA_GET};
2576 return OC_STACK_INVALID_PARAM;
2579 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2582 OC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2583 return OC_STACK_ERROR;
2586 switch (clientCB->method)
2588 case OC_REST_OBSERVE:
2589 case OC_REST_OBSERVE_ALL:
2591 OC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
2592 clientCB->requestUri);
2593 if (qos != OC_HIGH_QOS)
2595 FindAndDeleteClientCB(clientCB);
2599 OC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2601 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2602 requestInfo.info.token = clientCB->token;
2603 requestInfo.info.tokenLength = clientCB->tokenLength;
2605 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2606 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2608 return OC_STACK_ERROR;
2610 requestInfo.info.numOptions = numOptions + 1;
2611 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2613 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2615 ret = OCSendRequest(&endpoint, &requestInfo);
2617 if (requestInfo.info.options)
2619 OICFree (requestInfo.info.options);
2621 if (requestInfo.info.resourceUri)
2623 OICFree (requestInfo.info.resourceUri);
2628 case OC_REST_DISCOVER:
2629 OC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2630 clientCB->requestUri);
2631 FindAndDeleteClientCB(clientCB);
2634 #ifdef WITH_PRESENCE
2635 case OC_REST_PRESENCE:
2636 FindAndDeleteClientCB(clientCB);
2641 ret = OC_STACK_INVALID_METHOD;
2649 * @brief Register Persistent storage callback.
2650 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2652 * OC_STACK_OK - No errors; Success
2653 * OC_STACK_INVALID_PARAM - Invalid parameter
2655 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2657 OC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2658 if(!persistentStorageHandler)
2660 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2661 return OC_STACK_INVALID_PARAM;
2665 if( !persistentStorageHandler->open ||
2666 !persistentStorageHandler->close ||
2667 !persistentStorageHandler->read ||
2668 !persistentStorageHandler->unlink ||
2669 !persistentStorageHandler->write)
2671 OC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2672 return OC_STACK_INVALID_PARAM;
2675 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2678 #ifdef WITH_PRESENCE
2680 OCStackResult OCProcessPresence()
2682 OCStackResult result = OC_STACK_OK;
2684 // the following line floods the log with messages that are irrelevant
2685 // to most purposes. Uncomment as needed.
2686 //OC_LOG(INFO, TAG, "Entering RequestPresence");
2687 ClientCB* cbNode = NULL;
2688 OCClientResponse clientResponse;
2689 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
2691 LL_FOREACH(cbList, cbNode)
2693 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
2698 uint32_t now = GetTicks(0);
2699 OC_LOG_V(DEBUG, TAG, "this TTL level %d",
2700 cbNode->presence->TTLlevel);
2701 OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
2703 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
2708 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
2710 OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
2711 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
2713 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
2715 OC_LOG(DEBUG, TAG, "No more timeout ticks");
2717 clientResponse.sequenceNumber = 0;
2718 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
2719 clientResponse.devAddr = *cbNode->devAddr;
2720 FixUpClientResponse(&clientResponse);
2721 clientResponse.payload = NULL;
2723 // Increment the TTLLevel (going to a next state), so we don't keep
2724 // sending presence notification to client.
2725 cbNode->presence->TTLlevel++;
2726 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
2727 cbNode->presence->TTLlevel);
2729 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
2730 if (cbResult == OC_STACK_DELETE_TRANSACTION)
2732 FindAndDeleteClientCB(cbNode);
2736 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
2741 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2742 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
2743 CARequestInfo_t requestInfo = {.method = CA_GET};
2745 OC_LOG(DEBUG, TAG, "time to test server presence");
2747 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
2749 requestData.type = CA_MSG_NONCONFIRM;
2750 requestData.token = cbNode->token;
2751 requestData.tokenLength = cbNode->tokenLength;
2752 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
2753 requestInfo.method = CA_GET;
2754 requestInfo.info = requestData;
2756 result = OCSendRequest(&endpoint, &requestInfo);
2757 if (OC_STACK_OK != result)
2762 cbNode->presence->TTLlevel++;
2763 OC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
2766 if (result != OC_STACK_OK)
2768 OC_LOG(ERROR, TAG, "OCProcessPresence error");
2773 #endif // WITH_PRESENCE
2775 OCStackResult OCProcess()
2777 #ifdef WITH_PRESENCE
2778 OCProcessPresence();
2780 CAHandleRequestResponse();
2782 #ifdef ROUTING_GATEWAY
2788 #ifdef WITH_PRESENCE
2789 OCStackResult OCStartPresence(const uint32_t ttl)
2791 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2792 OCChangeResourceProperty(
2793 &(((OCResource *)presenceResource.handle)->resourceProperties),
2796 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
2798 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
2799 OC_LOG(INFO, TAG, "Setting Presence TTL to max value");
2803 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
2804 OC_LOG(INFO, TAG, "Setting Presence TTL to default value");
2808 presenceResource.presenceTTL = ttl;
2810 OC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
2812 if (OC_PRESENCE_UNINITIALIZED == presenceState)
2814 presenceState = OC_PRESENCE_INITIALIZED;
2816 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
2818 CAToken_t caToken = NULL;
2819 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
2820 if (caResult != CA_STATUS_OK)
2822 OC_LOG(ERROR, TAG, "CAGenerateToken error");
2823 CADestroyToken(caToken);
2824 return OC_STACK_ERROR;
2827 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
2828 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
2829 CADestroyToken(caToken);
2832 // Each time OCStartPresence is called
2833 // a different random 32-bit integer number is used
2834 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2836 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
2837 OC_PRESENCE_TRIGGER_CREATE);
2840 OCStackResult OCStopPresence()
2842 OCStackResult result = OC_STACK_ERROR;
2844 if(presenceResource.handle)
2846 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
2848 // make resource inactive
2849 result = OCChangeResourceProperty(
2850 &(((OCResource *) presenceResource.handle)->resourceProperties),
2854 if(result != OC_STACK_OK)
2857 "Changing the presence resource properties to ACTIVE not successful");
2861 return SendStopNotification();
2865 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
2866 void* callbackParameter)
2868 defaultDeviceHandler = entityHandler;
2869 defaultDeviceHandlerCallbackParameter = callbackParameter;
2874 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
2876 OC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
2878 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
2880 if (validatePlatformInfo(platformInfo))
2882 return SavePlatformInfo(platformInfo);
2886 return OC_STACK_INVALID_PARAM;
2891 return OC_STACK_ERROR;
2895 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
2897 OC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
2899 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
2901 OC_LOG(ERROR, TAG, "Null or empty device name.");
2902 return OC_STACK_INVALID_PARAM;
2905 return SaveDeviceInfo(deviceInfo);
2908 OCStackResult OCCreateResource(OCResourceHandle *handle,
2909 const char *resourceTypeName,
2910 const char *resourceInterfaceName,
2911 const char *uri, OCEntityHandler entityHandler,
2912 void* callbackParam,
2913 uint8_t resourceProperties)
2916 OCResource *pointer = NULL;
2917 OCStackResult result = OC_STACK_ERROR;
2919 OC_LOG(INFO, TAG, "Entering OCCreateResource");
2921 if(myStackMode == OC_CLIENT)
2923 return OC_STACK_INVALID_PARAM;
2925 // Validate parameters
2926 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
2928 OC_LOG(ERROR, TAG, "URI is empty or too long");
2929 return OC_STACK_INVALID_URI;
2931 // Is it presented during resource discovery?
2932 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
2934 OC_LOG(ERROR, TAG, "Input parameter is NULL");
2935 return OC_STACK_INVALID_PARAM;
2938 if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
2940 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
2943 // Make sure resourceProperties bitmask has allowed properties specified
2944 if (resourceProperties
2945 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
2946 OC_EXPLICIT_DISCOVERABLE))
2948 OC_LOG(ERROR, TAG, "Invalid property");
2949 return OC_STACK_INVALID_PARAM;
2952 // If the headResource is NULL, then no resources have been created...
2953 pointer = headResource;
2956 // At least one resources is in the resource list, so we need to search for
2957 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
2960 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
2962 OC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
2963 return OC_STACK_INVALID_PARAM;
2965 pointer = pointer->next;
2968 // Create the pointer and insert it into the resource list
2969 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
2972 result = OC_STACK_NO_MEMORY;
2975 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
2977 insertResource(pointer);
2980 pointer->uri = OICStrdup(uri);
2983 result = OC_STACK_NO_MEMORY;
2987 // Set properties. Set OC_ACTIVE
2988 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
2991 // Add the resourcetype to the resource
2992 result = BindResourceTypeToResource(pointer, resourceTypeName);
2993 if (result != OC_STACK_OK)
2995 OC_LOG(ERROR, TAG, "Error adding resourcetype");
2999 // Add the resourceinterface to the resource
3000 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3001 if (result != OC_STACK_OK)
3003 OC_LOG(ERROR, TAG, "Error adding resourceinterface");
3007 // If an entity handler has been passed, attach it to the newly created
3008 // resource. Otherwise, set the default entity handler.
3011 pointer->entityHandler = entityHandler;
3012 pointer->entityHandlerCallbackParam = callbackParam;
3016 pointer->entityHandler = defaultResourceEHandler;
3017 pointer->entityHandlerCallbackParam = NULL;
3021 result = OC_STACK_OK;
3023 #ifdef WITH_PRESENCE
3024 if (presenceResource.handle)
3026 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3027 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3031 if (result != OC_STACK_OK)
3033 // Deep delete of resource and other dynamic elements that it contains
3034 deleteResource(pointer);
3040 OCStackResult OCBindResource(
3041 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3043 OCResource *resource = NULL;
3046 OC_LOG(INFO, TAG, "Entering OCBindResource");
3048 // Validate parameters
3049 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3050 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3051 // Container cannot contain itself
3052 if (collectionHandle == resourceHandle)
3054 OC_LOG(ERROR, TAG, "Added handle equals collection handle");
3055 return OC_STACK_INVALID_PARAM;
3058 // Use the handle to find the resource in the resource linked list
3059 resource = findResource((OCResource *) collectionHandle);
3062 OC_LOG(ERROR, TAG, "Collection handle not found");
3063 return OC_STACK_INVALID_PARAM;
3066 // Look for an open slot to add add the child resource.
3067 // If found, add it and return success
3068 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3070 if (!resource->rsrcResources[i])
3072 resource->rsrcResources[i] = (OCResource *) resourceHandle;
3073 OC_LOG(INFO, TAG, "resource bound");
3075 #ifdef WITH_PRESENCE
3076 if (presenceResource.handle)
3078 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3079 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3080 OC_PRESENCE_TRIGGER_CHANGE);
3088 // Unable to add resourceHandle, so return error
3089 return OC_STACK_ERROR;
3092 OCStackResult OCUnBindResource(
3093 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3095 OCResource *resource = NULL;
3098 OC_LOG(INFO, TAG, "Entering OCUnBindResource");
3100 // Validate parameters
3101 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3102 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3103 // Container cannot contain itself
3104 if (collectionHandle == resourceHandle)
3106 OC_LOG(ERROR, TAG, "removing handle equals collection handle");
3107 return OC_STACK_INVALID_PARAM;
3110 // Use the handle to find the resource in the resource linked list
3111 resource = findResource((OCResource *) collectionHandle);
3114 OC_LOG(ERROR, TAG, "Collection handle not found");
3115 return OC_STACK_INVALID_PARAM;
3118 // Look for an open slot to add add the child resource.
3119 // If found, add it and return success
3120 for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
3122 if (resourceHandle == resource->rsrcResources[i])
3124 resource->rsrcResources[i] = (OCResource *) NULL;
3125 OC_LOG(INFO, TAG, "resource unbound");
3127 // Send notification when resource is unbounded successfully.
3128 #ifdef WITH_PRESENCE
3129 if (presenceResource.handle)
3131 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3132 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3133 OC_PRESENCE_TRIGGER_CHANGE);
3140 OC_LOG(INFO, TAG, "resource not found in collection");
3142 // Unable to add resourceHandle, so return error
3143 return OC_STACK_ERROR;
3146 // Precondition is that the parameter has been checked to not equal NULL.
3147 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3149 if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
3155 while (resourceItemName[index] != '\0')
3157 if (resourceItemName[index] != '.' &&
3158 resourceItemName[index] != '-' &&
3159 (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
3160 (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3169 OCStackResult BindResourceTypeToResource(OCResource* resource,
3170 const char *resourceTypeName)
3172 OCResourceType *pointer = NULL;
3174 OCStackResult result = OC_STACK_ERROR;
3176 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3178 if (!ValidateResourceTypeInterface(resourceTypeName))
3180 OC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3181 return OC_STACK_INVALID_PARAM;
3184 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3187 result = OC_STACK_NO_MEMORY;
3191 str = OICStrdup(resourceTypeName);
3194 result = OC_STACK_NO_MEMORY;
3197 pointer->resourcetypename = str;
3199 insertResourceType(resource, pointer);
3200 result = OC_STACK_OK;
3203 if (result != OC_STACK_OK)
3212 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3213 const char *resourceInterfaceName)
3215 OCResourceInterface *pointer = NULL;
3217 OCStackResult result = OC_STACK_ERROR;
3219 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3221 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3223 OC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3224 return OC_STACK_INVALID_PARAM;
3227 OC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3229 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3232 result = OC_STACK_NO_MEMORY;
3236 str = OICStrdup(resourceInterfaceName);
3239 result = OC_STACK_NO_MEMORY;
3242 pointer->name = str;
3244 // Bind the resourceinterface to the resource
3245 insertResourceInterface(resource, pointer);
3247 result = OC_STACK_OK;
3250 if (result != OC_STACK_OK)
3259 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3260 const char *resourceTypeName)
3263 OCStackResult result = OC_STACK_ERROR;
3264 OCResource *resource = NULL;
3266 resource = findResource((OCResource *) handle);
3269 OC_LOG(ERROR, TAG, "Resource not found");
3270 return OC_STACK_ERROR;
3273 result = BindResourceTypeToResource(resource, resourceTypeName);
3275 #ifdef WITH_PRESENCE
3276 if(presenceResource.handle)
3278 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3279 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3286 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3287 const char *resourceInterfaceName)
3290 OCStackResult result = OC_STACK_ERROR;
3291 OCResource *resource = NULL;
3293 resource = findResource((OCResource *) handle);
3296 OC_LOG(ERROR, TAG, "Resource not found");
3297 return OC_STACK_ERROR;
3300 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3302 #ifdef WITH_PRESENCE
3303 if (presenceResource.handle)
3305 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3306 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3313 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3315 OCResource *pointer = headResource;
3317 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3321 *numResources = *numResources + 1;
3322 pointer = pointer->next;
3327 OCResourceHandle OCGetResourceHandle(uint8_t index)
3329 OCResource *pointer = headResource;
3331 for( uint8_t i = 0; i < index && pointer; ++i)
3333 pointer = pointer->next;
3335 return (OCResourceHandle) pointer;
3338 OCStackResult OCDeleteResource(OCResourceHandle handle)
3342 OC_LOG(ERROR, TAG, "Invalid handle for deletion");
3343 return OC_STACK_INVALID_PARAM;
3346 OCResource *resource = findResource((OCResource *) handle);
3347 if (resource == NULL)
3349 OC_LOG(ERROR, TAG, "Resource not found");
3350 return OC_STACK_NO_RESOURCE;
3353 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3355 OC_LOG(ERROR, TAG, "Error deleting resource");
3356 return OC_STACK_ERROR;
3362 const char *OCGetResourceUri(OCResourceHandle handle)
3364 OCResource *resource = NULL;
3366 resource = findResource((OCResource *) handle);
3369 return resource->uri;
3371 return (const char *) NULL;
3374 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3376 OCResource *resource = NULL;
3378 resource = findResource((OCResource *) handle);
3381 return resource->resourceProperties;
3383 return (OCResourceProperty)-1;
3386 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3387 uint8_t *numResourceTypes)
3389 OCResource *resource = NULL;
3390 OCResourceType *pointer = NULL;
3392 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3393 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3395 *numResourceTypes = 0;
3397 resource = findResource((OCResource *) handle);
3400 pointer = resource->rsrcType;
3403 *numResourceTypes = *numResourceTypes + 1;
3404 pointer = pointer->next;
3410 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3412 OCResourceType *resourceType = NULL;
3414 resourceType = findResourceTypeAtIndex(handle, index);
3417 return resourceType->resourcetypename;
3419 return (const char *) NULL;
3422 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3423 uint8_t *numResourceInterfaces)
3425 OCResourceInterface *pointer = NULL;
3426 OCResource *resource = NULL;
3428 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3429 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3431 *numResourceInterfaces = 0;
3432 resource = findResource((OCResource *) handle);
3435 pointer = resource->rsrcInterface;
3438 *numResourceInterfaces = *numResourceInterfaces + 1;
3439 pointer = pointer->next;
3445 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3447 OCResourceInterface *resourceInterface = NULL;
3449 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3450 if (resourceInterface)
3452 return resourceInterface->name;
3454 return (const char *) NULL;
3457 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3460 OCResource *resource = NULL;
3462 if (index >= MAX_CONTAINED_RESOURCES)
3467 resource = findResource((OCResource *) collectionHandle);
3473 return resource->rsrcResources[index];
3476 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3477 OCEntityHandler entityHandler,
3478 void* callbackParam)
3480 OCResource *resource = NULL;
3482 // Validate parameters
3483 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3485 // Use the handle to find the resource in the resource linked list
3486 resource = findResource((OCResource *)handle);
3489 OC_LOG(ERROR, TAG, "Resource not found");
3490 return OC_STACK_ERROR;
3494 resource->entityHandler = entityHandler;
3495 resource->entityHandlerCallbackParam = callbackParam;
3497 #ifdef WITH_PRESENCE
3498 if (presenceResource.handle)
3500 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3501 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3508 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3510 OCResource *resource = NULL;
3512 resource = findResource((OCResource *)handle);
3515 OC_LOG(ERROR, TAG, "Resource not found");
3520 return resource->entityHandler;
3523 void incrementSequenceNumber(OCResource * resPtr)
3525 // Increment the sequence number
3526 resPtr->sequenceNum += 1;
3527 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3529 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3534 #ifdef WITH_PRESENCE
3535 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3536 OCPresenceTrigger trigger)
3538 OCResource *resPtr = NULL;
3539 OCStackResult result = OC_STACK_ERROR;
3540 OCMethod method = OC_REST_PRESENCE;
3541 uint32_t maxAge = 0;
3542 resPtr = findResource((OCResource *) presenceResource.handle);
3545 return OC_STACK_NO_RESOURCE;
3548 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3550 maxAge = presenceResource.presenceTTL;
3552 result = SendAllObserverNotification(method, resPtr, maxAge,
3553 trigger, resourceType, OC_LOW_QOS);
3559 OCStackResult SendStopNotification()
3561 OCResource *resPtr = NULL;
3562 OCStackResult result = OC_STACK_ERROR;
3563 OCMethod method = OC_REST_PRESENCE;
3564 resPtr = findResource((OCResource *) presenceResource.handle);
3567 return OC_STACK_NO_RESOURCE;
3570 // maxAge is 0. ResourceType is NULL.
3571 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
3577 #endif // WITH_PRESENCE
3578 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
3580 OCResource *resPtr = NULL;
3581 OCStackResult result = OC_STACK_ERROR;
3582 OCMethod method = OC_REST_NOMETHOD;
3583 uint32_t maxAge = 0;
3585 OC_LOG(INFO, TAG, "Notifying all observers");
3586 #ifdef WITH_PRESENCE
3587 if(handle == presenceResource.handle)
3591 #endif // WITH_PRESENCE
3592 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3594 // Verify that the resource exists
3595 resPtr = findResource ((OCResource *) handle);
3598 return OC_STACK_NO_RESOURCE;
3602 //only increment in the case of regular observing (not presence)
3603 incrementSequenceNumber(resPtr);
3604 method = OC_REST_OBSERVE;
3605 maxAge = MAX_OBSERVE_AGE;
3606 #ifdef WITH_PRESENCE
3607 result = SendAllObserverNotification (method, resPtr, maxAge,
3608 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
3610 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
3617 OCNotifyListOfObservers (OCResourceHandle handle,
3618 OCObservationId *obsIdList,
3619 uint8_t numberOfIds,
3620 const OCRepPayload *payload,
3621 OCQualityOfService qos)
3623 OC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
3625 OCResource *resPtr = NULL;
3626 //TODO: we should allow the server to define this
3627 uint32_t maxAge = MAX_OBSERVE_AGE;
3629 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
3630 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
3631 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
3633 resPtr = findResource ((OCResource *) handle);
3634 if (NULL == resPtr || myStackMode == OC_CLIENT)
3636 return OC_STACK_NO_RESOURCE;
3640 incrementSequenceNumber(resPtr);
3642 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
3643 payload, maxAge, qos));
3646 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
3648 OCStackResult result = OC_STACK_ERROR;
3649 OCServerRequest *serverRequest = NULL;
3651 OC_LOG(INFO, TAG, "Entering OCDoResponse");
3653 // Validate input parameters
3654 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
3655 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
3658 // Get pointer to request info
3659 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
3662 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
3663 result = serverRequest->ehResponseHandler(ehResponse);
3669 //-----------------------------------------------------------------------------
3670 // Private internal function definitions
3671 //-----------------------------------------------------------------------------
3672 static OCDoHandle GenerateInvocationHandle()
3674 OCDoHandle handle = NULL;
3675 // Generate token here, it will be deleted when the transaction is deleted
3676 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3679 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
3685 #ifdef WITH_PRESENCE
3686 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
3687 OCResourceProperty resourceProperties, uint8_t enable)
3691 return OC_STACK_INVALID_PARAM;
3693 if (resourceProperties
3694 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
3696 OC_LOG(ERROR, TAG, "Invalid property");
3697 return OC_STACK_INVALID_PARAM;
3701 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
3705 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
3711 OCStackResult initResources()
3713 OCStackResult result = OC_STACK_OK;
3715 headResource = NULL;
3716 tailResource = NULL;
3717 // Init Virtual Resources
3718 #ifdef WITH_PRESENCE
3719 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3721 result = OCCreateResource(&presenceResource.handle,
3722 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
3724 OC_RSRVD_PRESENCE_URI,
3728 //make resource inactive
3729 result = OCChangeResourceProperty(
3730 &(((OCResource *) presenceResource.handle)->resourceProperties),
3733 #ifndef WITH_ARDUINO
3734 if (result == OC_STACK_OK)
3736 result = SRMInitSecureResources();
3740 if(result == OC_STACK_OK)
3742 result = OCCreateResource(&deviceResource,
3743 OC_RSRVD_RESOURCE_TYPE_DEVICE,
3744 OC_RSRVD_INTERFACE_DEFAULT,
3745 OC_RSRVD_DEVICE_URI,
3749 if(result == OC_STACK_OK)
3751 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
3752 OC_RSRVD_INTERFACE_READ);
3756 if(result == OC_STACK_OK)
3758 result = OCCreateResource(&platformResource,
3759 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
3760 OC_RSRVD_INTERFACE_DEFAULT,
3761 OC_RSRVD_PLATFORM_URI,
3765 if(result == OC_STACK_OK)
3767 result = BindResourceInterfaceToResource((OCResource *)platformResource,
3768 OC_RSRVD_INTERFACE_READ);
3775 void insertResource(OCResource *resource)
3779 headResource = resource;
3780 tailResource = resource;
3784 tailResource->next = resource;
3785 tailResource = resource;
3787 resource->next = NULL;
3790 OCResource *findResource(OCResource *resource)
3792 OCResource *pointer = headResource;
3796 if (pointer == resource)
3800 pointer = pointer->next;
3805 void deleteAllResources()
3807 OCResource *pointer = headResource;
3808 OCResource *temp = NULL;
3812 temp = pointer->next;
3813 #ifdef WITH_PRESENCE
3814 if (pointer != (OCResource *) presenceResource.handle)
3816 #endif // WITH_PRESENCE
3817 deleteResource(pointer);
3818 #ifdef WITH_PRESENCE
3820 #endif // WITH_PRESENCE
3824 SRMDeInitSecureResources();
3826 #ifdef WITH_PRESENCE
3827 // Ensure that the last resource to be deleted is the presence resource. This allows for all
3828 // presence notification attributed to their deletion to be processed.
3829 deleteResource((OCResource *) presenceResource.handle);
3830 #endif // WITH_PRESENCE
3833 OCStackResult deleteResource(OCResource *resource)
3835 OCResource *prev = NULL;
3836 OCResource *temp = NULL;
3839 OC_LOG(DEBUG,TAG,"resource is NULL");
3840 return OC_STACK_INVALID_PARAM;
3843 OC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
3845 temp = headResource;
3848 if (temp == resource)
3850 // Invalidate all Resource Properties.
3851 resource->resourceProperties = (OCResourceProperty) 0;
3852 #ifdef WITH_PRESENCE
3853 if(resource != (OCResource *) presenceResource.handle)
3855 #endif // WITH_PRESENCE
3856 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
3857 #ifdef WITH_PRESENCE
3860 if(presenceResource.handle)
3862 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3863 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
3866 // Only resource in list.
3867 if (temp == headResource && temp == tailResource)
3869 headResource = NULL;
3870 tailResource = NULL;
3873 else if (temp == headResource)
3875 headResource = temp->next;
3878 else if (temp == tailResource)
3880 tailResource = prev;
3881 tailResource->next = NULL;
3885 prev->next = temp->next;
3888 deleteResourceElements(temp);
3899 return OC_STACK_ERROR;
3902 void deleteResourceElements(OCResource *resource)
3909 OICFree(resource->uri);
3910 deleteResourceType(resource->rsrcType);
3911 deleteResourceInterface(resource->rsrcInterface);
3914 void deleteResourceType(OCResourceType *resourceType)
3916 OCResourceType *pointer = resourceType;
3917 OCResourceType *next = NULL;
3921 next = pointer->next;
3922 OICFree(pointer->resourcetypename);
3928 void deleteResourceInterface(OCResourceInterface *resourceInterface)
3930 OCResourceInterface *pointer = resourceInterface;
3931 OCResourceInterface *next = NULL;
3935 next = pointer->next;
3936 OICFree(pointer->name);
3942 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
3944 OCResourceType *pointer = NULL;
3945 OCResourceType *previous = NULL;
3946 if (!resource || !resourceType)
3950 // resource type list is empty.
3951 else if (!resource->rsrcType)
3953 resource->rsrcType = resourceType;
3957 pointer = resource->rsrcType;
3961 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
3963 OC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
3964 OICFree(resourceType->resourcetypename);
3965 OICFree(resourceType);
3969 pointer = pointer->next;
3971 previous->next = resourceType;
3973 resourceType->next = NULL;
3975 OC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
3978 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
3980 OCResource *resource = NULL;
3981 OCResourceType *pointer = NULL;
3983 // Find the specified resource
3984 resource = findResource((OCResource *) handle);
3990 // Make sure a resource has a resourcetype
3991 if (!resource->rsrcType)
3996 // Iterate through the list
3997 pointer = resource->rsrcType;
3998 for(uint8_t i = 0; i< index && pointer; ++i)
4000 pointer = pointer->next;
4005 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4007 if(resourceTypeList && resourceTypeName)
4009 OCResourceType * rtPointer = resourceTypeList;
4010 while(resourceTypeName && rtPointer)
4012 if(rtPointer->resourcetypename &&
4013 strcmp(resourceTypeName, (const char *)
4014 (rtPointer->resourcetypename)) == 0)
4018 rtPointer = rtPointer->next;
4026 * Insert a new interface into interface linked list only if not already present.
4027 * If alredy present, 2nd arg is free'd.
4028 * Default interface will always be first if present.
4030 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4032 OCResourceInterface *pointer = NULL;
4033 OCResourceInterface *previous = NULL;
4035 newInterface->next = NULL;
4037 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4039 if (!*firstInterface)
4041 *firstInterface = newInterface;
4043 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4045 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4047 OICFree(newInterface->name);
4048 OICFree(newInterface);
4053 newInterface->next = *firstInterface;
4054 *firstInterface = newInterface;
4059 pointer = *firstInterface;
4062 if (strcmp(newInterface->name, pointer->name) == 0)
4064 OICFree(newInterface->name);
4065 OICFree(newInterface);
4069 pointer = pointer->next;
4071 previous->next = newInterface;
4075 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4078 OCResource *resource = NULL;
4079 OCResourceInterface *pointer = NULL;
4081 // Find the specified resource
4082 resource = findResource((OCResource *) handle);
4088 // Make sure a resource has a resourceinterface
4089 if (!resource->rsrcInterface)
4094 // Iterate through the list
4095 pointer = resource->rsrcInterface;
4097 for (uint8_t i = 0; i < index && pointer; ++i)
4099 pointer = pointer->next;
4105 * This function splits the uri using the '?' delimiter.
4106 * "uriWithoutQuery" is the block of characters between the beginning
4107 * till the delimiter or '\0' which ever comes first.
4108 * "query" is whatever is to the right of the delimiter if present.
4109 * No delimiter sets the query to NULL.
4110 * If either are present, they will be malloc'ed into the params 2, 3.
4111 * The first param, *uri is left untouched.
4113 * NOTE: This function does not account for whitespace at the end of the uri NOR
4114 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4115 * part of the query.
4117 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4121 return OC_STACK_INVALID_URI;
4123 if(!query || !uriWithoutQuery)
4125 return OC_STACK_INVALID_PARAM;
4129 *uriWithoutQuery = NULL;
4131 size_t uriWithoutQueryLen = 0;
4132 size_t queryLen = 0;
4133 size_t uriLen = strlen(uri);
4135 char *pointerToDelimiter = strstr(uri, "?");
4137 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4138 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4140 if (uriWithoutQueryLen)
4142 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4143 if (!*uriWithoutQuery)
4147 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4151 *query = (char *) OICCalloc(queryLen + 1, 1);
4154 OICFree(*uriWithoutQuery);
4155 *uriWithoutQuery = NULL;
4158 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4164 return OC_STACK_NO_MEMORY;
4167 const OicUuid_t* OCGetServerInstanceID(void)
4169 static bool generated = false;
4170 static OicUuid_t sid;
4176 if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
4178 OC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4185 const char* OCGetServerInstanceIDString(void)
4187 static bool generated = false;
4188 static char sidStr[UUID_STRING_SIZE];
4195 const OicUuid_t* sid = OCGetServerInstanceID();
4197 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4199 OC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4207 CAResult_t OCSelectNetwork()
4209 CAResult_t retResult = CA_STATUS_FAILED;
4210 CAResult_t caResult = CA_STATUS_OK;
4212 CATransportAdapter_t connTypes[] = {
4214 CA_ADAPTER_RFCOMM_BTEDR,
4215 CA_ADAPTER_GATT_BTLE
4218 ,CA_ADAPTER_REMOTE_ACCESS
4225 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4227 for(int i = 0; i<numConnTypes; i++)
4229 // Ignore CA_NOT_SUPPORTED error. The CA Layer may have not compiled in the interface.
4230 if(caResult == CA_STATUS_OK || caResult == CA_NOT_SUPPORTED)
4232 caResult = CASelectNetwork(connTypes[i]);
4233 if(caResult == CA_STATUS_OK)
4235 retResult = CA_STATUS_OK;
4240 if(retResult != CA_STATUS_OK)
4242 return caResult; // Returns error of appropriate transport that failed fatally.
4248 OCStackResult CAResultToOCResult(CAResult_t caResult)
4254 case CA_STATUS_INVALID_PARAM:
4255 return OC_STACK_INVALID_PARAM;
4256 case CA_ADAPTER_NOT_ENABLED:
4257 return OC_STACK_ADAPTER_NOT_ENABLED;
4258 case CA_SERVER_STARTED_ALREADY:
4260 case CA_SERVER_NOT_STARTED:
4261 return OC_STACK_ERROR;
4262 case CA_DESTINATION_NOT_REACHABLE:
4263 return OC_STACK_COMM_ERROR;
4264 case CA_SOCKET_OPERATION_FAILED:
4265 return OC_STACK_COMM_ERROR;
4266 case CA_SEND_FAILED:
4267 return OC_STACK_COMM_ERROR;
4268 case CA_RECEIVE_FAILED:
4269 return OC_STACK_COMM_ERROR;
4270 case CA_MEMORY_ALLOC_FAILED:
4271 return OC_STACK_NO_MEMORY;
4272 case CA_REQUEST_TIMEOUT:
4273 return OC_STACK_TIMEOUT;
4274 case CA_DESTINATION_DISCONNECTED:
4275 return OC_STACK_COMM_ERROR;
4276 case CA_STATUS_FAILED:
4277 return OC_STACK_ERROR;
4278 case CA_NOT_SUPPORTED:
4279 return OC_STACK_NOTIMPL;
4281 return OC_STACK_ERROR;