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 #ifndef __STDC_FORMAT_MACROS
34 #define __STDC_FORMAT_MACROS
36 #ifndef __STDC_LIMIT_MACROS
37 #define __STDC_LIMIT_MACROS
39 #include "iotivity_config.h"
45 #include "ocstackinternal.h"
46 #include "ocresourcehandler.h"
47 #include "occlientcb.h"
48 #include "ocobserve.h"
50 #include "oic_malloc.h"
51 #include "oic_string.h"
53 #include "ocserverrequest.h"
54 #include "secureresourcemanager.h"
55 #include "psinterface.h"
56 #include "doxmresource.h"
58 #include "cainterface.h"
59 #include "ocpayload.h"
60 #include "ocpayloadcbor.h"
61 #include "cautilinterface.h"
64 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
65 #include "routingutility.h"
66 #ifdef ROUTING_GATEWAY
67 #include "routingmanager.h"
72 #include "oickeepalive.h"
75 //#ifdef DIRECT_PAIRING
76 #include "directpairing.h"
79 #ifdef HAVE_ARDUINO_TIME_H
82 #ifdef HAVE_SYS_TIME_H
85 #include <coap/coap.h>
87 #ifdef HAVE_ARPA_INET_H
88 #include <arpa/inet.h>
92 #define UINT32_MAX (0xFFFFFFFFUL)
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
100 OC_STACK_UNINITIALIZED = 0,
101 OC_STACK_INITIALIZED,
102 OC_STACK_UNINIT_IN_PROGRESS
108 OC_PRESENCE_UNINITIALIZED = 0,
109 OC_PRESENCE_INITIALIZED
113 //-----------------------------------------------------------------------------
115 //-----------------------------------------------------------------------------
116 static OCStackState stackState = OC_STACK_UNINITIALIZED;
118 OCResource *headResource = NULL;
119 static OCResource *tailResource = NULL;
120 static OCResourceHandle platformResource = {0};
121 static OCResourceHandle deviceResource = {0};
123 static OCResourceHandle brokerResource = {0};
127 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
128 static PresenceResource presenceResource = {0};
129 static uint8_t PresenceTimeOutSize = 0;
130 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
133 static OCMode myStackMode;
135 //TODO: revisit this design
136 static bool gRASetInfo = false;
138 OCDeviceEntityHandler defaultDeviceHandler;
139 void* defaultDeviceHandlerCallbackParameter = NULL;
140 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
141 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
142 static const char CORESPEC[] = "core";
144 CAAdapterStateChangedCB g_adapterHandler = NULL;
145 CAConnectionStateChangedCB g_connectionHandler = NULL;
147 //-----------------------------------------------------------------------------
149 //-----------------------------------------------------------------------------
150 #define TAG "OIC_RI_STACK"
151 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
152 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
153 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
154 TAG, #arg " is NULL"); return (retVal); } }
155 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
156 TAG, #arg " is NULL"); return; } }
157 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
160 //TODO: we should allow the server to define this
161 #define MAX_OBSERVE_AGE (0x2FFFFUL)
163 #define MILLISECONDS_PER_SECOND (1000)
165 //-----------------------------------------------------------------------------
166 // Private internal function prototypes
167 //-----------------------------------------------------------------------------
170 * Generate handle of OCDoResource invocation for callback management.
172 * @return Generated OCDoResource handle.
174 static OCDoHandle GenerateInvocationHandle();
177 * Initialize resource data structures, variables, etc.
179 * @return ::OC_STACK_OK on success, some other value upon failure.
181 static OCStackResult initResources();
184 * Add a resource to the end of the linked list of resources.
186 * @param resource Resource to be added
188 static void insertResource(OCResource *resource);
191 * Find a resource in the linked list of resources.
193 * @param resource Resource to be found.
194 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
197 static OCResource *findResource(OCResource *resource);
200 * Insert a resource type into a resource's resource type linked list.
201 * If resource type already exists, it will not be inserted and the
202 * resourceType will be free'd.
203 * resourceType->next should be null to avoid memory leaks.
204 * Function returns silently for null args.
206 * @param resource Resource where resource type is to be inserted.
207 * @param resourceType Resource type to be inserted.
209 static void insertResourceType(OCResource *resource,
210 OCResourceType *resourceType);
213 * Get a resource type at the specified index within a resource.
215 * @param handle Handle of resource.
216 * @param index Index of resource type.
218 * @return Pointer to resource type if found, NULL otherwise.
220 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
224 * Insert a resource interface into a resource's resource interface linked list.
225 * If resource interface already exists, it will not be inserted and the
226 * resourceInterface will be free'd.
227 * resourceInterface->next should be null to avoid memory leaks.
229 * @param resource Resource where resource interface is to be inserted.
230 * @param resourceInterface Resource interface to be inserted.
232 static void insertResourceInterface(OCResource *resource,
233 OCResourceInterface *resourceInterface);
236 * Get a resource interface at the specified index within a resource.
238 * @param handle Handle of resource.
239 * @param index Index of resource interface.
241 * @return Pointer to resource interface if found, NULL otherwise.
243 static OCResourceInterface *findResourceInterfaceAtIndex(
244 OCResourceHandle handle, uint8_t index);
247 * Delete all of the dynamically allocated elements that were created for the resource type.
249 * @param resourceType Specified resource type.
251 static void deleteResourceType(OCResourceType *resourceType);
254 * Delete all of the dynamically allocated elements that were created for the resource interface.
256 * @param resourceInterface Specified resource interface.
258 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
261 * Delete all of the dynamically allocated elements that were created for the resource.
263 * @param resource Specified resource.
265 static void deleteResourceElements(OCResource *resource);
268 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
271 * @param handle Handle of resource to be deleted.
273 * @return ::OC_STACK_OK on success, some other value upon failure.
275 static OCStackResult deleteResource(OCResource *resource);
278 * Delete all of the resources in the resource list.
280 static void deleteAllResources();
283 * Increment resource sequence number. Handles rollover.
285 * @param resPtr Pointer to resource.
287 static void incrementSequenceNumber(OCResource * resPtr);
290 * Attempts to initialize every network interface that the CA Layer might have compiled in.
292 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
293 * return something other than @ref CA_STATUS_OK, then this function fails.
295 * @return ::CA_STATUS_OK on success, some other value upon failure.
297 static CAResult_t OCSelectNetwork();
300 * Get the CoAP ticks after the specified number of milli-seconds.
302 * @param afterMilliSeconds Milli-seconds.
306 static uint32_t GetTicks(uint32_t afterMilliSeconds);
309 * Convert CAResult_t to OCStackResult.
311 * @param caResult CAResult_t code.
312 * @return ::OC_STACK_OK on success, some other value upon failure.
314 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
317 * Convert CAResponseResult_t to OCStackResult.
319 * @param caCode CAResponseResult_t code.
320 * @return ::OC_STACK_OK on success, some other value upon failure.
322 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
325 * Convert OCTransportFlags_t to CATransportModifiers_t.
327 * @param ocConType OCTransportFlags_t input.
328 * @return CATransportFlags
330 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
333 * Convert CATransportFlags_t to OCTransportModifiers_t.
335 * @param caConType CATransportFlags_t input.
336 * @return OCTransportFlags
338 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
341 * Handle response from presence request.
343 * @param endPoint CA remote endpoint.
344 * @param responseInfo CA response info.
345 * @return ::OC_STACK_OK on success, some other value upon failure.
347 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
348 const CAResponseInfo_t *responseInfo);
351 * This function will be called back by CA layer when a response is received.
353 * @param endPoint CA remote endpoint.
354 * @param responseInfo CA response info.
356 static void HandleCAResponses(const CAEndpoint_t* endPoint,
357 const CAResponseInfo_t* responseInfo);
360 * This function will be called back by CA layer when a request is received.
362 * @param endPoint CA remote endpoint.
363 * @param requestInfo CA request info.
365 static void HandleCARequests(const CAEndpoint_t* endPoint,
366 const CARequestInfo_t* requestInfo);
369 * Extract query from a URI.
371 * @param uri Full URI with query.
372 * @param query Pointer to string that will contain query.
373 * @param newURI Pointer to string that will contain URI.
374 * @return ::OC_STACK_OK on success, some other value upon failure.
376 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
379 * Finds a resource type in an OCResourceType link-list.
381 * @param resourceTypeList The link-list to be searched through.
382 * @param resourceTypeName The key to search for.
384 * @return Resource type that matches the key (ie. resourceTypeName) or
385 * NULL if there is either an invalid parameter or this function was unable to find the key.
387 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
388 const char * resourceTypeName);
391 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
392 * TTL will be set to maxAge.
394 * @param cbNode Callback Node for which presence ttl is to be reset.
395 * @param maxAge New value of ttl in seconds.
397 * @return ::OC_STACK_OK on success, some other value upon failure.
399 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
402 * Ensure the accept header option is set appropriatly before sending the requests and routing
403 * header option is updated with destination.
405 * @param object CA remote endpoint.
406 * @param requestInfo CA request info.
408 * @return ::OC_STACK_OK on success, some other value upon failure.
410 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
413 * default adapter state change callback method
415 * @param adapter CA network adapter type.
416 * @param enabled current adapter state.
418 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
421 * default connection state change callback method
423 * @param info CAEndpoint which has address, port and etc.
424 * @param isConnected current connection state.
426 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
429 * Register network monitoring callback.
430 * Network status changes are delivered these callback.
431 * @param adapterHandler Adapter state monitoring callback.
432 * @param connectionHandler Connection state monitoring callback.
434 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
435 CAConnectionStateChangedCB connectionHandler);
437 //-----------------------------------------------------------------------------
438 // Internal functions
439 //-----------------------------------------------------------------------------
441 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
443 if (!options || 0 == numOptions)
445 OIC_LOG (INFO, TAG, "No options present");
449 for (uint8_t i = 0; i < numOptions; i++)
451 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
453 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
460 uint32_t GetTicks(uint32_t afterMilliSeconds)
465 // Guard against overflow of uint32_t
466 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
467 COAP_TICKS_PER_SECOND)
469 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
477 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
479 VERIFY_NON_NULL_NR(in, FATAL);
480 VERIFY_NON_NULL_NR(out, FATAL);
482 out->adapter = (OCTransportAdapter)in->adapter;
483 out->flags = CAToOCTransportFlags(in->flags);
484 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
485 out->port = in->port;
486 out->ifindex = in->ifindex;
487 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
488 /* This assert is to prevent accidental mismatch between address size macros defined in
489 * RI and CA and cause crash here. */
490 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
491 "Address size mismatch between RI and CA");
492 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
496 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
498 VERIFY_NON_NULL_NR(in, FATAL);
499 VERIFY_NON_NULL_NR(out, FATAL);
501 out->adapter = (CATransportAdapter_t)in->adapter;
502 out->flags = OCToCATransportFlags(in->flags);
503 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
504 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
505 /* This assert is to prevent accidental mismatch between address size macros defined in
506 * RI and CA and cause crash here. */
507 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
508 "Address size mismatch between RI and CA");
509 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
511 out->port = in->port;
512 out->ifindex = in->ifindex;
515 void FixUpClientResponse(OCClientResponse *cr)
517 VERIFY_NON_NULL_NR(cr, FATAL);
519 cr->addr = &cr->devAddr;
520 cr->connType = (OCConnectivityType)
521 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
524 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
526 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
527 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
529 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
530 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
531 if (OC_STACK_OK != rmResult)
533 OIC_LOG(ERROR, TAG, "Add destination option failed");
538 // OC stack prefer CBOR encoded payloads.
539 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
540 CAResult_t result = CASendRequest(object, requestInfo);
541 if(CA_STATUS_OK != result)
543 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
544 return CAResultToOCResult(result);
548 //-----------------------------------------------------------------------------
549 // Internal API function
550 //-----------------------------------------------------------------------------
552 // This internal function is called to update the stack with the status of
553 // observers and communication failures
554 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
556 OCStackResult result = OC_STACK_ERROR;
557 ResourceObserver * observer = NULL;
558 OCEntityHandlerRequest ehRequest = {0};
562 case OC_OBSERVER_NOT_INTERESTED:
563 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
564 observer = GetObserverUsingToken (token, tokenLength);
567 result = FormOCEntityHandlerRequest(&ehRequest,
568 (OCRequestHandle)NULL,
571 (OCResourceHandle)NULL,
572 NULL, PAYLOAD_TYPE_REPRESENTATION,
574 OC_OBSERVE_DEREGISTER,
577 if(result != OC_STACK_OK)
581 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
582 observer->resource->entityHandlerCallbackParam);
585 result = DeleteObserverUsingToken (token, tokenLength);
586 if(result == OC_STACK_OK)
588 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
592 result = OC_STACK_OK;
593 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
597 case OC_OBSERVER_STILL_INTERESTED:
598 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
599 observer = GetObserverUsingToken (token, tokenLength);
602 observer->forceHighQos = 0;
603 observer->failedCommCount = 0;
604 result = OC_STACK_OK;
608 result = OC_STACK_OBSERVER_NOT_FOUND;
612 case OC_OBSERVER_FAILED_COMM:
613 OIC_LOG(DEBUG, TAG, "observer is unreachable");
614 observer = GetObserverUsingToken (token, tokenLength);
617 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
619 result = FormOCEntityHandlerRequest(&ehRequest,
620 (OCRequestHandle)NULL,
623 (OCResourceHandle)NULL,
624 NULL, PAYLOAD_TYPE_REPRESENTATION,
626 OC_OBSERVE_DEREGISTER,
629 if(result != OC_STACK_OK)
631 return OC_STACK_ERROR;
633 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
634 observer->resource->entityHandlerCallbackParam);
636 result = DeleteObserverUsingToken (token, tokenLength);
637 if(result == OC_STACK_OK)
639 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
643 result = OC_STACK_OK;
644 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
649 observer->failedCommCount++;
650 result = OC_STACK_CONTINUE;
652 observer->forceHighQos = 1;
653 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
657 OIC_LOG(ERROR, TAG, "Unknown status");
658 result = OC_STACK_ERROR;
664 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
666 OCStackResult ret = OC_STACK_ERROR;
670 case CA_ADAPTER_NOT_ENABLED:
671 case CA_SERVER_NOT_STARTED:
672 ret = OC_STACK_ADAPTER_NOT_ENABLED;
674 case CA_MEMORY_ALLOC_FAILED:
675 ret = OC_STACK_NO_MEMORY;
677 case CA_STATUS_INVALID_PARAM:
678 ret = OC_STACK_INVALID_PARAM;
686 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
688 OCStackResult ret = OC_STACK_ERROR;
692 ret = OC_STACK_RESOURCE_CREATED;
695 ret = OC_STACK_RESOURCE_DELETED;
698 ret = OC_STACK_RESOURCE_CHANGED;
705 ret = OC_STACK_INVALID_QUERY;
707 case CA_UNAUTHORIZED_REQ:
708 ret = OC_STACK_UNAUTHORIZED_REQ;
711 ret = OC_STACK_INVALID_OPTION;
714 ret = OC_STACK_NO_RESOURCE;
716 case CA_RETRANSMIT_TIMEOUT:
717 ret = OC_STACK_COMM_ERROR;
719 case CA_REQUEST_ENTITY_TOO_LARGE:
720 ret = OC_STACK_TOO_LARGE_REQ;
722 case CA_FORBIDDEN_REQ:
723 ret = OC_STACK_FORBIDDEN_REQ;
725 case CA_INTERNAL_SERVER_ERROR:
726 ret = OC_STACK_INTERNAL_SERVER_ERROR;
734 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
736 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
745 // This Response Code is like HTTP 204 "No Content" but only used in
746 // response to POST and PUT requests.
750 // This Response Code is like HTTP 200 "OK" but only used in response to
755 // This should not happen but,
756 // give it a value just in case but output an error
758 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
762 case OC_STACK_RESOURCE_CREATED:
765 case OC_STACK_RESOURCE_DELETED:
768 case OC_STACK_RESOURCE_CHANGED:
771 case OC_STACK_INVALID_QUERY:
774 case OC_STACK_INVALID_OPTION:
777 case OC_STACK_NO_RESOURCE:
780 case OC_STACK_COMM_ERROR:
781 ret = CA_RETRANSMIT_TIMEOUT;
783 case OC_STACK_UNAUTHORIZED_REQ:
784 ret = CA_UNAUTHORIZED_REQ;
786 case OC_STACK_FORBIDDEN_REQ:
787 ret = CA_FORBIDDEN_REQ;
789 case OC_STACK_INTERNAL_SERVER_ERROR:
790 ret = CA_INTERNAL_SERVER_ERROR;
798 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
800 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
802 // supply default behavior.
803 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
805 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
807 if ((caFlags & OC_MASK_SCOPE) == 0)
809 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
814 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
816 return (OCTransportFlags)caFlags;
819 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
821 uint32_t lowerBound = 0;
822 uint32_t higherBound = 0;
824 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
826 return OC_STACK_INVALID_PARAM;
829 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
831 cbNode->presence->TTL = maxAgeSeconds;
833 for (int index = 0; index < PresenceTimeOutSize; index++)
835 // Guard against overflow
836 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
839 lowerBound = GetTicks((PresenceTimeOut[index] *
840 cbNode->presence->TTL *
841 MILLISECONDS_PER_SECOND)/100);
845 lowerBound = GetTicks(UINT32_MAX);
848 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
851 higherBound = GetTicks((PresenceTimeOut[index + 1] *
852 cbNode->presence->TTL *
853 MILLISECONDS_PER_SECOND)/100);
857 higherBound = GetTicks(UINT32_MAX);
860 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
862 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
863 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
864 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
867 cbNode->presence->TTLlevel = 0;
869 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
873 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
875 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
877 return OC_RSRVD_TRIGGER_CREATE;
879 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
881 return OC_RSRVD_TRIGGER_CHANGE;
885 return OC_RSRVD_TRIGGER_DELETE;
889 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
893 return OC_PRESENCE_TRIGGER_CREATE;
895 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
897 return OC_PRESENCE_TRIGGER_CREATE;
899 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
901 return OC_PRESENCE_TRIGGER_CHANGE;
905 return OC_PRESENCE_TRIGGER_DELETE;
910 * Encode an address string to match RFC 6874.
912 * @param outputAddress a char array to be written with the encoded string.
914 * @param outputSize size of outputAddress buffer.
916 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
917 * containing a valid IPv6 address string.
919 * @return OC_STACK_OK if encoding succeeded.
920 * Else an error occured.
922 OCStackResult encodeAddressForRFC6874(char *outputAddress,
924 const char *inputAddress)
926 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
927 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
929 size_t inputLength = strnlen(inputAddress, outputSize);
931 // inputSize includes the null terminator
932 size_t inputSize = inputLength + 1;
934 if (inputSize > outputSize)
936 OIC_LOG_V(ERROR, TAG,
937 "encodeAddressForRFC6874 failed: "
938 "outputSize (%zu) < inputSize (%zu)",
939 outputSize, inputSize);
941 return OC_STACK_ERROR;
944 char* percentChar = strchr(inputAddress, '%');
946 // If there is no '%' character, then no change is required to the string.
947 if (NULL == percentChar)
949 OICStrcpy(outputAddress, outputSize, inputAddress);
953 const char* addressPart = &inputAddress[0];
954 const char* scopeIdPart = percentChar + 1;
956 // Sanity check to make sure this string doesn't have more '%' characters
957 if (NULL != strchr(scopeIdPart, '%'))
959 return OC_STACK_ERROR;
962 // If no string follows the first '%', then the input was invalid.
963 if (scopeIdPart[0] == '\0')
965 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
966 return OC_STACK_ERROR;
969 // Check to see if the string is already encoded
970 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
972 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
973 return OC_STACK_ERROR;
976 // Fail if we don't have room for encoded string's two additional chars
977 if (outputSize < (inputSize + 2))
979 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
980 return OC_STACK_ERROR;
983 // Restore the null terminator with an escaped '%' character, per RFC 6874
984 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
985 strcat(outputAddress, "%25");
986 strcat(outputAddress, scopeIdPart);
992 * The cononical presence allows constructed URIs to be string compared.
994 * requestUri must be a char array of size CA_MAX_URI_LENGTH
996 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
997 char *presenceUri, bool isMulticast)
999 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
1000 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1004 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1005 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1008 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1009 if (ep->adapter == CA_ADAPTER_IP)
1011 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1013 if ('\0' == ep->addr[0]) // multicast
1015 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1019 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1021 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
1022 sizeof(addressEncoded),
1025 if (OC_STACK_OK != result)
1030 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1031 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1036 if ('\0' == ep->addr[0]) // multicast
1038 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1039 ep->port = OC_MULTICAST_PORT;
1041 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1042 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1046 // might work for other adapters (untested, but better than nothing)
1047 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1048 OC_RSRVD_PRESENCE_URI);
1052 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1053 const CAResponseInfo_t *responseInfo)
1055 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1056 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1058 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1059 ClientCB * cbNode = NULL;
1060 char *resourceTypeName = NULL;
1061 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1062 OCStackResult result = OC_STACK_ERROR;
1063 uint32_t maxAge = 0;
1065 char presenceUri[CA_MAX_URI_LENGTH];
1067 int presenceSubscribe = 0;
1068 int multicastPresenceSubscribe = 0;
1070 if (responseInfo->result != CA_CONTENT)
1072 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1073 return OC_STACK_ERROR;
1076 response.payload = NULL;
1077 response.result = OC_STACK_OK;
1079 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1080 FixUpClientResponse(&response);
1082 if (responseInfo->info.payload)
1084 result = OCParsePayload(&response.payload,
1085 PAYLOAD_TYPE_PRESENCE,
1086 responseInfo->info.payload,
1087 responseInfo->info.payloadSize);
1089 if(result != OC_STACK_OK)
1091 OIC_LOG(ERROR, TAG, "Presence parse failed");
1094 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1096 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1097 result = OC_STACK_ERROR;
1100 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1101 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1102 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1105 // check for unicast presence
1106 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1107 responseInfo->isMulticast);
1108 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1110 return OC_STACK_INVALID_URI;
1112 OIC_LOG(ERROR, TAG, "check for unicast presence");
1113 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1116 presenceSubscribe = 1;
1120 // check for multicast presence
1121 OIC_LOG(ERROR, TAG, "check for multicast presence");
1122 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1125 multicastPresenceSubscribe = 1;
1129 if (!presenceSubscribe && !multicastPresenceSubscribe)
1131 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1135 if (presenceSubscribe)
1137 if(cbNode->sequenceNumber == response.sequenceNumber)
1139 OIC_LOG(INFO, TAG, "No presence change");
1140 ResetPresenceTTL(cbNode, maxAge);
1141 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1147 OIC_LOG(INFO, TAG, "Stopping presence");
1148 response.result = OC_STACK_PRESENCE_STOPPED;
1149 if(cbNode->presence)
1151 OICFree(cbNode->presence->timeOut);
1152 OICFree(cbNode->presence);
1153 cbNode->presence = NULL;
1158 if(!cbNode->presence)
1160 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1162 if(!(cbNode->presence))
1164 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1165 result = OC_STACK_NO_MEMORY;
1169 VERIFY_NON_NULL_V(cbNode->presence);
1170 cbNode->presence->timeOut = NULL;
1171 cbNode->presence->timeOut = (uint32_t *)
1172 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1173 if(!(cbNode->presence->timeOut)){
1175 "Could not allocate memory for cbNode->presence->timeOut");
1176 OICFree(cbNode->presence);
1177 result = OC_STACK_NO_MEMORY;
1182 ResetPresenceTTL(cbNode, maxAge);
1184 cbNode->sequenceNumber = response.sequenceNumber;
1189 // This is the multicast case
1190 OIC_LOG(INFO, TAG, "this is the multicast presence");
1193 OIC_LOG(INFO, TAG, "Stopping presence");
1194 response.result = OC_STACK_PRESENCE_STOPPED;
1198 // Ensure that a filter is actually applied.
1199 if (resourceTypeName && cbNode->filterResourceType)
1201 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1202 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1208 OIC_LOG(INFO, TAG, "Callback for presence");
1210 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1212 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1214 FindAndDeleteClientCB(cbNode);
1218 OCPayloadDestroy(response.payload);
1222 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1224 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1226 if(responseInfo->info.resourceUri &&
1227 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1229 HandlePresenceResponse(endPoint, responseInfo);
1233 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1234 responseInfo->info.tokenLength, NULL, NULL);
1236 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1237 responseInfo->info.tokenLength);
1241 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1242 if(responseInfo->result == CA_EMPTY)
1244 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1245 // We do not have a case for the client to receive a RESET
1246 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1248 //This is the case of receiving an ACK on a request to a slow resource!
1249 OIC_LOG(INFO, TAG, "This is a pure ACK");
1250 //TODO: should we inform the client
1251 // app that at least the request was received at the server?
1254 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1256 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1257 OIC_LOG(INFO, TAG, "Calling into application address space");
1259 OCClientResponse response =
1260 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1261 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1262 FixUpClientResponse(&response);
1263 response.resourceUri = responseInfo->info.resourceUri;
1264 memcpy(response.identity.id, responseInfo->info.identity.id,
1265 sizeof (response.identity.id));
1266 response.identity.id_length = responseInfo->info.identity.id_length;
1268 response.result = CAResponseToOCStackResult(responseInfo->result);
1269 cbNode->callBack(cbNode->context,
1270 cbNode->handle, &response);
1271 FindAndDeleteClientCB(cbNode);
1275 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1276 OIC_LOG(INFO, TAG, "Calling into application address space");
1278 OCClientResponse response =
1279 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1280 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1281 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1282 FixUpClientResponse(&response);
1283 response.resourceUri = responseInfo->info.resourceUri;
1284 memcpy(response.identity.id, responseInfo->info.identity.id,
1285 sizeof (response.identity.id));
1286 response.identity.id_length = responseInfo->info.identity.id_length;
1288 response.result = CAResponseToOCStackResult(responseInfo->result);
1290 if(responseInfo->info.payload &&
1291 responseInfo->info.payloadSize)
1293 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1294 // check the security resource
1295 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1297 type = PAYLOAD_TYPE_SECURITY;
1299 else if (cbNode->method == OC_REST_DISCOVER)
1301 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1302 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1304 type = PAYLOAD_TYPE_DISCOVERY;
1307 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1309 type = PAYLOAD_TYPE_DISCOVERY;
1312 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1314 type = PAYLOAD_TYPE_DEVICE;
1316 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1318 type = PAYLOAD_TYPE_PLATFORM;
1320 #ifdef ROUTING_GATEWAY
1321 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1323 type = PAYLOAD_TYPE_REPRESENTATION;
1326 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1328 type = PAYLOAD_TYPE_REPRESENTATION ;
1331 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1333 type = PAYLOAD_TYPE_REPRESENTATION;
1338 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1339 cbNode->method, cbNode->requestUri);
1343 else if (cbNode->method == OC_REST_GET ||
1344 cbNode->method == OC_REST_PUT ||
1345 cbNode->method == OC_REST_POST ||
1346 cbNode->method == OC_REST_OBSERVE ||
1347 cbNode->method == OC_REST_OBSERVE_ALL ||
1348 cbNode->method == OC_REST_DELETE)
1350 if (cbNode->requestUri)
1352 if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1354 type = PAYLOAD_TYPE_PLATFORM;
1356 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1358 type = PAYLOAD_TYPE_DEVICE;
1360 if (type == PAYLOAD_TYPE_INVALID)
1362 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1363 cbNode->method, cbNode->requestUri);
1364 type = PAYLOAD_TYPE_REPRESENTATION;
1369 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1370 type = PAYLOAD_TYPE_REPRESENTATION;
1375 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1376 cbNode->method, cbNode->requestUri);
1380 if(OC_STACK_OK != OCParsePayload(&response.payload,
1382 responseInfo->info.payload,
1383 responseInfo->info.payloadSize))
1385 OIC_LOG(ERROR, TAG, "Error converting payload");
1386 OCPayloadDestroy(response.payload);
1391 response.numRcvdVendorSpecificHeaderOptions = 0;
1392 if(responseInfo->info.numOptions > 0)
1395 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1396 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1399 uint32_t observationOption;
1400 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1401 for (observationOption=0, i=0;
1402 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1406 (observationOption << 8) | optionData[i];
1408 response.sequenceNumber = observationOption;
1409 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1414 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1417 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1419 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1420 OCPayloadDestroy(response.payload);
1424 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1426 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1427 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1431 if (cbNode->method == OC_REST_OBSERVE &&
1432 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1433 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1434 response.sequenceNumber <= cbNode->sequenceNumber)
1436 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1437 response.sequenceNumber);
1441 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1444 cbNode->sequenceNumber = response.sequenceNumber;
1446 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1448 FindAndDeleteClientCB(cbNode);
1452 // To keep discovery callbacks active.
1453 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1454 MILLISECONDS_PER_SECOND);
1458 //Need to send ACK when the response is CON
1459 if(responseInfo->info.type == CA_MSG_CONFIRM)
1461 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1462 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1465 OCPayloadDestroy(response.payload);
1472 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1473 if(responseInfo->result == CA_EMPTY)
1475 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1476 if(responseInfo->info.type == CA_MSG_RESET)
1478 OIC_LOG(INFO, TAG, "This is a RESET");
1479 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1480 OC_OBSERVER_NOT_INTERESTED);
1482 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1484 OIC_LOG(INFO, TAG, "This is a pure ACK");
1485 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1486 OC_OBSERVER_STILL_INTERESTED);
1489 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1491 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1492 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1493 OC_OBSERVER_FAILED_COMM);
1498 if(!cbNode && !observer)
1500 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1501 || myStackMode == OC_GATEWAY)
1503 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1504 if(responseInfo->result == CA_EMPTY)
1506 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1510 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1511 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1512 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1516 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1517 || myStackMode == OC_GATEWAY)
1519 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1520 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1522 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1523 responseInfo->info.messageId);
1525 if (responseInfo->info.type == CA_MSG_RESET)
1527 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1528 responseInfo->info.messageId);
1536 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1538 VERIFY_NON_NULL_NR(endPoint, FATAL);
1539 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1541 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1543 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1544 #ifdef ROUTING_GATEWAY
1545 bool needRIHandling = false;
1547 * Routing manager is going to update either of endpoint or response or both.
1548 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1549 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1552 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1554 if(ret != OC_STACK_OK || !needRIHandling)
1556 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1562 * Put source in sender endpoint so that the next packet from application can be routed to
1563 * proper destination and remove "RM" coap header option before passing request / response to
1564 * RI as this option will make no sense to either RI or application.
1566 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1567 (uint8_t *) &(responseInfo->info.numOptions),
1568 (CAEndpoint_t *) endPoint);
1571 OCHandleResponse(endPoint, responseInfo);
1573 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1577 * This function handles error response from CA
1578 * code shall be added to handle the errors
1580 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1582 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1584 if (NULL == endPoint)
1586 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1590 if (NULL == errorInfo)
1592 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1596 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1597 errorInfo->info.tokenLength, NULL, NULL);
1600 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1601 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1602 FixUpClientResponse(&response);
1603 response.resourceUri = errorInfo->info.resourceUri;
1604 memcpy(response.identity.id, errorInfo->info.identity.id,
1605 sizeof (response.identity.id));
1606 response.identity.id_length = errorInfo->info.identity.id_length;
1607 response.result = CAResultToOCStackResult(errorInfo->result);
1609 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1612 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1616 * This function sends out Direct Stack Responses. These are responses that are not coming
1617 * from the application entity handler. These responses have no payload and are usually ACKs,
1618 * RESETs or some error conditions that were caught by the stack.
1620 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1621 const CAResponseResult_t responseResult, const CAMessageType_t type,
1622 const uint8_t numOptions, const CAHeaderOption_t *options,
1623 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1624 CADataType_t dataType)
1626 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1627 CAResponseInfo_t respInfo = {
1628 .result = responseResult
1630 respInfo.info.messageId = coapID;
1631 respInfo.info.numOptions = numOptions;
1633 if (respInfo.info.numOptions)
1635 respInfo.info.options =
1636 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1637 memcpy (respInfo.info.options, options,
1638 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1642 respInfo.info.payload = NULL;
1643 respInfo.info.token = token;
1644 respInfo.info.tokenLength = tokenLength;
1645 respInfo.info.type = type;
1646 respInfo.info.resourceUri = OICStrdup (resourceUri);
1647 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1648 respInfo.info.dataType = dataType;
1650 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1651 // Add the destination to route option from the endpoint->routeData.
1652 bool doPost = false;
1653 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1654 if(OC_STACK_OK != result)
1656 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1661 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1662 CARequestInfo_t reqInfo = {.method = CA_POST };
1663 /* The following initialization is not done in a single initializer block as in
1664 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1665 * does not have designated initalizers. This is a work-around for now.
1667 reqInfo.info.type = CA_MSG_NONCONFIRM;
1668 reqInfo.info.messageId = coapID;
1669 reqInfo.info.tokenLength = tokenLength;
1670 reqInfo.info.token = token;
1671 reqInfo.info.numOptions = respInfo.info.numOptions;
1672 reqInfo.info.payload = NULL;
1673 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1674 if (reqInfo.info.numOptions)
1676 reqInfo.info.options =
1677 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1678 if (NULL == reqInfo.info.options)
1680 OIC_LOG(ERROR, TAG, "Calloc failed");
1681 return OC_STACK_NO_MEMORY;
1683 memcpy (reqInfo.info.options, respInfo.info.options,
1684 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1687 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1688 OICFree (reqInfo.info.resourceUri);
1689 OICFree (reqInfo.info.options);
1690 OICFree (respInfo.info.resourceUri);
1691 OICFree (respInfo.info.options);
1692 if (CA_STATUS_OK != caResult)
1694 OIC_LOG(ERROR, TAG, "CASendRequest error");
1695 return CAResultToOCResult(caResult);
1701 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1703 // resourceUri in the info field is cloned in the CA layer and
1704 // thus ownership is still here.
1705 OICFree (respInfo.info.resourceUri);
1706 OICFree (respInfo.info.options);
1707 if(CA_STATUS_OK != caResult)
1709 OIC_LOG(ERROR, TAG, "CASendResponse error");
1710 return CAResultToOCResult(caResult);
1713 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1717 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1719 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1720 OCStackResult result = OC_STACK_ERROR;
1721 if(!protocolRequest)
1723 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1724 return OC_STACK_INVALID_PARAM;
1727 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1728 protocolRequest->tokenLength);
1731 OIC_LOG(INFO, TAG, "This is a new Server Request");
1732 result = AddServerRequest(&request, protocolRequest->coapID,
1733 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1734 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1735 protocolRequest->observationOption, protocolRequest->qos,
1736 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1737 protocolRequest->payload, protocolRequest->requestToken,
1738 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1739 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1740 &protocolRequest->devAddr);
1741 if (OC_STACK_OK != result)
1743 OIC_LOG(ERROR, TAG, "Error adding server request");
1749 OIC_LOG(ERROR, TAG, "Out of Memory");
1750 return OC_STACK_NO_MEMORY;
1753 if(!protocolRequest->reqMorePacket)
1755 request->requestComplete = 1;
1760 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1763 if(request->requestComplete)
1765 OIC_LOG(INFO, TAG, "This Server Request is complete");
1766 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1767 OCResource *resource = NULL;
1768 result = DetermineResourceHandling (request, &resHandling, &resource);
1769 if (result == OC_STACK_OK)
1771 result = ProcessRequest(resHandling, resource, request);
1776 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1777 result = OC_STACK_CONTINUE;
1782 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1784 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1786 OCStackResult requestResult = OC_STACK_ERROR;
1788 if(myStackMode == OC_CLIENT)
1790 //TODO: should the client be responding to requests?
1794 OCServerProtocolRequest serverRequest = {0};
1796 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1798 char * uriWithoutQuery = NULL;
1799 char * query = NULL;
1801 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1803 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1805 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1808 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1809 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1811 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1813 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1814 OICFree(uriWithoutQuery);
1818 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1819 OICFree(uriWithoutQuery);
1826 if(strlen(query) < MAX_QUERY_LENGTH)
1828 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1833 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1839 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1841 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1842 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1843 if (!serverRequest.payload)
1845 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1848 memcpy (serverRequest.payload, requestInfo->info.payload,
1849 requestInfo->info.payloadSize);
1853 serverRequest.reqTotalSize = 0;
1856 switch (requestInfo->method)
1859 serverRequest.method = OC_REST_GET;
1862 serverRequest.method = OC_REST_PUT;
1865 serverRequest.method = OC_REST_POST;
1868 serverRequest.method = OC_REST_DELETE;
1871 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1872 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1873 requestInfo->info.type, requestInfo->info.numOptions,
1874 requestInfo->info.options, requestInfo->info.token,
1875 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1877 OICFree(serverRequest.payload);
1881 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1882 requestInfo->info.tokenLength);
1884 serverRequest.tokenLength = requestInfo->info.tokenLength;
1885 if (serverRequest.tokenLength) {
1887 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1889 if (!serverRequest.requestToken)
1891 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1892 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1893 requestInfo->info.type, requestInfo->info.numOptions,
1894 requestInfo->info.options, requestInfo->info.token,
1895 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1897 OICFree(serverRequest.payload);
1900 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1903 switch (requestInfo->info.acceptFormat)
1905 case CA_FORMAT_APPLICATION_CBOR:
1906 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1908 case CA_FORMAT_UNDEFINED:
1909 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1912 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1915 if (requestInfo->info.type == CA_MSG_CONFIRM)
1917 serverRequest.qos = OC_HIGH_QOS;
1921 serverRequest.qos = OC_LOW_QOS;
1923 // CA does not need the following field
1924 // Are we sure CA does not need them? how is it responding to multicast
1925 serverRequest.delayedResNeeded = 0;
1927 serverRequest.coapID = requestInfo->info.messageId;
1929 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1931 // copy vendor specific header options
1932 uint8_t tempNum = (requestInfo->info.numOptions);
1934 // Assume no observation requested and it is a pure GET.
1935 // If obs registration/de-registration requested it'll be fetched from the
1936 // options in GetObserveHeaderOption()
1937 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1939 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1940 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1943 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1944 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1945 requestInfo->info.type, requestInfo->info.numOptions,
1946 requestInfo->info.options, requestInfo->info.token,
1947 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1949 OICFree(serverRequest.payload);
1950 OICFree(serverRequest.requestToken);
1953 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1954 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1956 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1957 sizeof(CAHeaderOption_t)*tempNum);
1960 requestResult = HandleStackRequests (&serverRequest);
1962 // Send ACK to client as precursor to slow response
1963 if (requestResult == OC_STACK_SLOW_RESOURCE)
1965 if (requestInfo->info.type == CA_MSG_CONFIRM)
1967 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1968 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1972 if (requestResult == OC_STACK_RESOURCE_ERROR
1973 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
1975 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
1977 else if(!OCResultToSuccess(requestResult))
1979 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1981 CAResponseResult_t stackResponse =
1982 OCToCAStackResult(requestResult, serverRequest.method);
1984 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1985 requestInfo->info.type, requestInfo->info.numOptions,
1986 requestInfo->info.options, requestInfo->info.token,
1987 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1990 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1991 // The token is copied in there, and is thus still owned by this function.
1992 OICFree(serverRequest.payload);
1993 OICFree(serverRequest.requestToken);
1994 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1997 //This function will be called back by CA layer when a request is received
1998 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2000 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2003 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2009 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2013 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2014 #ifdef ROUTING_GATEWAY
2015 bool needRIHandling = false;
2016 bool isEmptyMsg = false;
2018 * Routing manager is going to update either of endpoint or request or both.
2019 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2020 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2021 * destination. It can also remove "RM" coap header option before passing request / response to
2022 * RI as this option will make no sense to either RI or application.
2024 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2025 &needRIHandling, &isEmptyMsg);
2026 if(OC_STACK_OK != ret || !needRIHandling)
2028 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2034 * Put source in sender endpoint so that the next packet from application can be routed to
2035 * proper destination and remove RM header option.
2037 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2038 (uint8_t *) &(requestInfo->info.numOptions),
2039 (CAEndpoint_t *) endPoint);
2041 #ifdef ROUTING_GATEWAY
2045 * In Gateways, the MSGType in route option is used to check if the actual
2046 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2047 * EMPTY response is sent in the form of POST request which need to be changed
2048 * to a EMPTY response by RM. This translation is done in this part of the code.
2050 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2051 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2052 .info.messageId = requestInfo->info.messageId,
2053 .info.type = CA_MSG_ACKNOWLEDGE};
2054 OCHandleResponse(endPoint, &respInfo);
2060 // Normal handling of the packet
2061 OCHandleRequests(endPoint, requestInfo);
2063 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2066 bool validatePlatformInfo(OCPlatformInfo info)
2069 if (!info.platformID)
2071 OIC_LOG(ERROR, TAG, "No platform ID found.");
2075 if (info.manufacturerName)
2077 size_t lenManufacturerName = strlen(info.manufacturerName);
2079 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2081 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2087 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2091 if (info.manufacturerUrl)
2093 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2095 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2102 //-----------------------------------------------------------------------------
2104 //-----------------------------------------------------------------------------
2106 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2109 !raInfo->username ||
2110 !raInfo->hostname ||
2111 !raInfo->xmpp_domain)
2114 return OC_STACK_INVALID_PARAM;
2116 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2117 gRASetInfo = (result == OC_STACK_OK)? true : false;
2123 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2127 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2130 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2132 if(stackState == OC_STACK_INITIALIZED)
2134 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2135 OCStop() between them are ignored.");
2139 #ifndef ROUTING_GATEWAY
2140 if (OC_GATEWAY == mode)
2142 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2143 return OC_STACK_INVALID_PARAM;
2150 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2151 return OC_STACK_ERROR;
2155 OCStackResult result = OC_STACK_ERROR;
2156 OIC_LOG(INFO, TAG, "Entering OCInit");
2159 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2160 || (mode == OC_GATEWAY)))
2162 OIC_LOG(ERROR, TAG, "Invalid mode");
2163 return OC_STACK_ERROR;
2167 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2169 caglobals.client = true;
2171 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2173 caglobals.server = true;
2176 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2177 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2179 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2181 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2182 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2184 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2187 defaultDeviceHandler = NULL;
2188 defaultDeviceHandlerCallbackParameter = NULL;
2190 result = InitializeScheduleResourceList();
2191 VERIFY_SUCCESS(result, OC_STACK_OK);
2193 result = CAResultToOCResult(CAInitialize());
2194 VERIFY_SUCCESS(result, OC_STACK_OK);
2196 result = CAResultToOCResult(OCSelectNetwork());
2197 VERIFY_SUCCESS(result, OC_STACK_OK);
2199 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2200 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2201 VERIFY_SUCCESS(result, OC_STACK_OK);
2203 switch (myStackMode)
2206 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2207 result = CAResultToOCResult(CAStartDiscoveryServer());
2208 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2211 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2212 result = CAResultToOCResult(CAStartListeningServer());
2213 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2215 case OC_CLIENT_SERVER:
2217 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2218 result = CAResultToOCResult(CAStartListeningServer());
2219 if(result == OC_STACK_OK)
2221 result = CAResultToOCResult(CAStartDiscoveryServer());
2225 VERIFY_SUCCESS(result, OC_STACK_OK);
2228 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2231 #ifdef WITH_PRESENCE
2232 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2233 #endif // WITH_PRESENCE
2235 //Update Stack state to initialized
2236 stackState = OC_STACK_INITIALIZED;
2238 // Initialize resource
2239 if(myStackMode != OC_CLIENT)
2241 result = initResources();
2244 // Initialize the SRM Policy Engine
2245 if(result == OC_STACK_OK)
2247 result = SRMInitPolicyEngine();
2248 // TODO after BeachHead delivery: consolidate into single SRMInit()
2250 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2251 RMSetStackMode(mode);
2252 #ifdef ROUTING_GATEWAY
2253 if (OC_GATEWAY == myStackMode)
2255 result = RMInitialize();
2261 if (result == OC_STACK_OK)
2263 result = InitializeKeepAlive(myStackMode);
2268 if(result != OC_STACK_OK)
2270 OIC_LOG(ERROR, TAG, "Stack initialization error");
2271 deleteAllResources();
2273 TerminateScheduleResourceList();
2274 stackState = OC_STACK_UNINITIALIZED;
2279 OCStackResult OCStop()
2281 OIC_LOG(INFO, TAG, "Entering OCStop");
2283 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2285 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2288 else if (stackState != OC_STACK_INITIALIZED)
2290 OIC_LOG(ERROR, TAG, "Stack not initialized");
2291 return OC_STACK_ERROR;
2294 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2296 #ifdef WITH_PRESENCE
2297 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2298 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2299 presenceResource.presenceTTL = 0;
2300 #endif // WITH_PRESENCE
2302 #ifdef ROUTING_GATEWAY
2303 if (OC_GATEWAY == myStackMode)
2310 TerminateKeepAlive(myStackMode);
2313 // Free memory dynamically allocated for resources
2314 deleteAllResources();
2316 DeletePlatformInfo();
2318 TerminateScheduleResourceList();
2319 // Remove all observers
2320 DeleteObserverList();
2321 // Remove all the client callbacks
2322 DeleteClientCBList();
2324 // De-init the SRM Policy Engine
2325 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2326 SRMDeInitPolicyEngine();
2329 stackState = OC_STACK_UNINITIALIZED;
2333 OCStackResult OCStartMulticastServer()
2335 if(stackState != OC_STACK_INITIALIZED)
2337 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2338 return OC_STACK_ERROR;
2340 CAResult_t ret = CAStartListeningServer();
2341 if (CA_STATUS_OK != ret)
2343 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2344 return OC_STACK_ERROR;
2349 OCStackResult OCStopMulticastServer()
2351 CAResult_t ret = CAStopListeningServer();
2352 if (CA_STATUS_OK != ret)
2354 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2355 return OC_STACK_ERROR;
2360 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2365 return CA_MSG_CONFIRM;
2370 return CA_MSG_NONCONFIRM;
2375 * A request uri consists of the following components in order:
2378 * CoAP over UDP prefix "coap://"
2379 * CoAP over TCP prefix "coap+tcp://"
2380 * CoAP over DTLS prefix "coaps://"
2381 * CoAP over TLS prefix "coaps+tcp://"
2383 * IPv6 address "[1234::5678]"
2384 * IPv4 address "192.168.1.1"
2385 * optional port ":5683"
2386 * resource uri "/oc/core..."
2388 * for PRESENCE requests, extract resource type.
2390 static OCStackResult ParseRequestUri(const char *fullUri,
2391 OCTransportAdapter adapter,
2392 OCTransportFlags flags,
2393 OCDevAddr **devAddr,
2395 char **resourceType)
2397 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2399 OCStackResult result = OC_STACK_OK;
2400 OCDevAddr *da = NULL;
2404 // provide defaults for all returned values
2411 *resourceUri = NULL;
2415 *resourceType = NULL;
2418 // delimit url prefix, if any
2419 const char *start = fullUri;
2420 char *slash2 = strstr(start, "//");
2425 char *slash = strchr(start, '/');
2428 return OC_STACK_INVALID_URI;
2431 // process url scheme
2432 size_t prefixLen = slash2 - fullUri;
2436 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2437 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2443 // TODO: this logic should come in with unit tests exercising the various strings
2444 // processs url prefix, if any
2445 size_t urlLen = slash - start;
2449 if (urlLen && devAddr)
2450 { // construct OCDevAddr
2451 if (start[0] == '[')
2453 char *close = strchr(++start, ']');
2454 if (!close || close > slash)
2456 return OC_STACK_INVALID_URI;
2459 if (close[1] == ':')
2466 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2470 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2472 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2476 char *dot = strchr(start, '.');
2477 if (dot && dot < slash)
2479 colon = strchr(start, ':');
2480 end = (colon && colon < slash) ? colon : slash;
2485 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2489 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2491 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2499 if (len >= sizeof(da->addr))
2501 return OC_STACK_INVALID_URI;
2503 // collect port, if any
2504 if (colon && colon < slash)
2506 for (colon++; colon < slash; colon++)
2509 if (c < '0' || c > '9')
2511 return OC_STACK_INVALID_URI;
2513 port = 10 * port + c - '0';
2518 if (len >= sizeof(da->addr))
2520 return OC_STACK_INVALID_URI;
2523 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2526 return OC_STACK_NO_MEMORY;
2528 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2530 da->adapter = adapter;
2532 if (!strncmp(fullUri, "coaps", 5))
2534 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2539 // process resource uri, if any
2541 { // request uri and query
2542 size_t ulen = strlen(slash); // resource uri length
2543 size_t tlen = 0; // resource type length
2546 static const char strPresence[] = "/oic/ad?rt=";
2547 static const size_t lenPresence = sizeof(strPresence) - 1;
2548 if (!strncmp(slash, strPresence, lenPresence))
2550 type = slash + lenPresence;
2551 tlen = ulen - lenPresence;
2556 *resourceUri = (char *)OICMalloc(ulen + 1);
2559 result = OC_STACK_NO_MEMORY;
2562 strcpy(*resourceUri, slash);
2565 if (type && resourceType)
2567 *resourceType = (char *)OICMalloc(tlen + 1);
2570 result = OC_STACK_NO_MEMORY;
2574 OICStrcpy(*resourceType, (tlen+1), type);
2581 // free all returned values
2588 OICFree(*resourceUri);
2592 OICFree(*resourceType);
2597 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2601 char uri[CA_MAX_URI_LENGTH];
2603 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2605 *requestUri = OICStrdup(uri);
2608 return OC_STACK_NO_MEMORY;
2615 * Discover or Perform requests on a specified resource
2617 OCStackResult OCDoResource(OCDoHandle *handle,
2619 const char *requestUri,
2620 const OCDevAddr *destination,
2622 OCConnectivityType connectivityType,
2623 OCQualityOfService qos,
2624 OCCallbackData *cbData,
2625 OCHeaderOption *options,
2628 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2630 // Validate input parameters
2631 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2632 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2634 OCStackResult result = OC_STACK_ERROR;
2635 CAResult_t caResult;
2636 CAToken_t token = NULL;
2637 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2638 ClientCB *clientCB = NULL;
2639 OCDoHandle resHandle = NULL;
2640 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2641 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2643 OCTransportAdapter adapter;
2644 OCTransportFlags flags;
2645 // the request contents are put here
2646 CARequestInfo_t requestInfo = {.method = CA_GET};
2647 // requestUri will be parsed into the following three variables
2648 OCDevAddr *devAddr = NULL;
2649 char *resourceUri = NULL;
2650 char *resourceType = NULL;
2653 * Support original behavior with address on resourceUri argument.
2655 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2656 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2660 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2661 if (result != OC_STACK_OK)
2663 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2667 else if (!checkProxyUri(options, numOptions))
2669 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2676 case OC_REST_OBSERVE:
2677 case OC_REST_OBSERVE_ALL:
2678 requestInfo.method = CA_GET;
2681 requestInfo.method = CA_PUT;
2684 requestInfo.method = CA_POST;
2686 case OC_REST_DELETE:
2687 requestInfo.method = CA_DELETE;
2689 case OC_REST_DISCOVER:
2691 #ifdef WITH_PRESENCE
2692 case OC_REST_PRESENCE:
2694 if (destination || devAddr)
2696 requestInfo.isMulticast = false;
2700 tmpDevAddr.adapter = adapter;
2701 tmpDevAddr.flags = flags;
2702 destination = &tmpDevAddr;
2703 requestInfo.isMulticast = true;
2705 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2706 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2707 // replacing method type with GET.
2708 requestInfo.method = CA_GET;
2711 result = OC_STACK_INVALID_METHOD;
2715 if (!devAddr && !destination)
2717 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2718 result = OC_STACK_INVALID_PARAM;
2722 /* If not original behavior, use destination argument */
2723 if (destination && !devAddr)
2725 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2728 result = OC_STACK_NO_MEMORY;
2731 *devAddr = *destination;
2734 resHandle = GenerateInvocationHandle();
2737 result = OC_STACK_NO_MEMORY;
2741 caResult = CAGenerateToken(&token, tokenLength);
2742 if (caResult != CA_STATUS_OK)
2744 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2745 result= OC_STACK_ERROR;
2749 // fill in request data
2750 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2751 requestInfo.info.token = token;
2752 requestInfo.info.tokenLength = tokenLength;
2754 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2756 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2757 options, numOptions, OC_OBSERVE_REGISTER);
2758 if (result != OC_STACK_OK)
2762 requestInfo.info.numOptions = numOptions + 1;
2766 requestInfo.info.numOptions = numOptions;
2767 requestInfo.info.options =
2768 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2769 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2770 numOptions * sizeof(CAHeaderOption_t));
2773 CopyDevAddrToEndpoint(devAddr, &endpoint);
2778 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2781 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2784 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2788 requestInfo.info.payload = NULL;
2789 requestInfo.info.payloadSize = 0;
2790 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2793 // prepare for response
2794 #ifdef WITH_PRESENCE
2795 if (method == OC_REST_PRESENCE)
2797 char *presenceUri = NULL;
2798 result = OCPreparePresence(&endpoint, &presenceUri,
2799 requestInfo.isMulticast);
2800 if (OC_STACK_OK != result)
2805 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2806 // Presence notification will form a canonical uri to
2807 // look for callbacks into the application.
2810 OICFree(resourceUri);
2812 resourceUri = presenceUri;
2816 // update resourceUri onto requestInfo after check presence uri
2817 requestInfo.info.resourceUri = resourceUri;
2819 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2820 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2821 method, devAddr, resourceUri, resourceType, ttl);
2822 if (OC_STACK_OK != result)
2827 devAddr = NULL; // Client CB list entry now owns it
2828 resourceUri = NULL; // Client CB list entry now owns it
2829 resourceType = NULL; // Client CB list entry now owns it
2831 #ifdef WITH_PRESENCE
2832 if (method == OC_REST_PRESENCE)
2834 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
2840 result = OCSendRequest(&endpoint, &requestInfo);
2841 if (OC_STACK_OK != result)
2848 *handle = resHandle;
2852 if (result != OC_STACK_OK)
2854 OIC_LOG(ERROR, TAG, "OCDoResource error");
2855 FindAndDeleteClientCB(clientCB);
2856 CADestroyToken(token);
2864 // This is the owner of the payload object, so we free it
2865 OCPayloadDestroy(payload);
2866 OICFree(requestInfo.info.payload);
2868 OICFree(resourceUri);
2869 OICFree(resourceType);
2870 OICFree(requestInfo.info.options);
2874 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2878 * This ftn is implemented one of two ways in the case of observation:
2880 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2881 * Remove the callback associated on client side.
2882 * When the next notification comes in from server,
2883 * reply with RESET message to server.
2884 * Keep in mind that the server will react to RESET only
2885 * if the last notification was sent as CON
2887 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2888 * and it is associated with an observe request
2889 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2890 * Send CON Observe request to server with
2891 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2892 * Remove the callback associated on client side.
2894 OCStackResult ret = OC_STACK_OK;
2895 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2896 CARequestInfo_t requestInfo = {.method = CA_GET};
2900 return OC_STACK_INVALID_PARAM;
2903 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2906 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2907 return OC_STACK_ERROR;
2910 switch (clientCB->method)
2912 case OC_REST_OBSERVE:
2913 case OC_REST_OBSERVE_ALL:
2915 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2917 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2919 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2921 FindAndDeleteClientCB(clientCB);
2925 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2927 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2928 requestInfo.info.token = clientCB->token;
2929 requestInfo.info.tokenLength = clientCB->tokenLength;
2931 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2932 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2934 return OC_STACK_ERROR;
2936 requestInfo.info.numOptions = numOptions + 1;
2937 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2940 ret = OCSendRequest(&endpoint, &requestInfo);
2942 if (requestInfo.info.options)
2944 OICFree (requestInfo.info.options);
2946 if (requestInfo.info.resourceUri)
2948 OICFree (requestInfo.info.resourceUri);
2953 case OC_REST_DISCOVER:
2954 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2955 clientCB->requestUri);
2956 FindAndDeleteClientCB(clientCB);
2959 #ifdef WITH_PRESENCE
2960 case OC_REST_PRESENCE:
2961 FindAndDeleteClientCB(clientCB);
2966 ret = OC_STACK_INVALID_METHOD;
2974 * @brief Register Persistent storage callback.
2975 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2977 * OC_STACK_OK - No errors; Success
2978 * OC_STACK_INVALID_PARAM - Invalid parameter
2980 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2982 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2983 if(!persistentStorageHandler)
2985 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2986 return OC_STACK_INVALID_PARAM;
2990 if( !persistentStorageHandler->open ||
2991 !persistentStorageHandler->close ||
2992 !persistentStorageHandler->read ||
2993 !persistentStorageHandler->unlink ||
2994 !persistentStorageHandler->write)
2996 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2997 return OC_STACK_INVALID_PARAM;
3000 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3003 #ifdef WITH_PRESENCE
3005 OCStackResult OCProcessPresence()
3007 OCStackResult result = OC_STACK_OK;
3009 // the following line floods the log with messages that are irrelevant
3010 // to most purposes. Uncomment as needed.
3011 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3012 ClientCB* cbNode = NULL;
3013 OCClientResponse clientResponse;
3014 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3016 LL_FOREACH(cbList, cbNode)
3018 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3023 uint32_t now = GetTicks(0);
3024 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3025 cbNode->presence->TTLlevel);
3026 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3028 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3033 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3035 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3036 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3038 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3040 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3042 clientResponse.sequenceNumber = 0;
3043 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3044 clientResponse.devAddr = *cbNode->devAddr;
3045 FixUpClientResponse(&clientResponse);
3046 clientResponse.payload = NULL;
3048 // Increment the TTLLevel (going to a next state), so we don't keep
3049 // sending presence notification to client.
3050 cbNode->presence->TTLlevel++;
3051 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3052 cbNode->presence->TTLlevel);
3054 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3055 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3057 FindAndDeleteClientCB(cbNode);
3061 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3066 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3067 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3068 CARequestInfo_t requestInfo = {.method = CA_GET};
3070 OIC_LOG(DEBUG, TAG, "time to test server presence");
3072 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3074 requestData.type = CA_MSG_NONCONFIRM;
3075 requestData.token = cbNode->token;
3076 requestData.tokenLength = cbNode->tokenLength;
3077 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3078 requestInfo.method = CA_GET;
3079 requestInfo.info = requestData;
3081 result = OCSendRequest(&endpoint, &requestInfo);
3082 if (OC_STACK_OK != result)
3087 cbNode->presence->TTLlevel++;
3088 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3091 if (result != OC_STACK_OK)
3093 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3098 #endif // WITH_PRESENCE
3100 OCStackResult OCProcess()
3102 #ifdef WITH_PRESENCE
3103 OCProcessPresence();
3105 CAHandleRequestResponse();
3107 #ifdef ROUTING_GATEWAY
3117 #ifdef WITH_PRESENCE
3118 OCStackResult OCStartPresence(const uint32_t ttl)
3120 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3121 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3122 OCChangeResourceProperty(
3123 &(((OCResource *)presenceResource.handle)->resourceProperties),
3126 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3128 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3129 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3133 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3134 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3138 presenceResource.presenceTTL = ttl;
3140 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3142 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3144 presenceState = OC_PRESENCE_INITIALIZED;
3146 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3148 CAToken_t caToken = NULL;
3149 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3150 if (caResult != CA_STATUS_OK)
3152 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3153 CADestroyToken(caToken);
3154 return OC_STACK_ERROR;
3157 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3158 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3159 CADestroyToken(caToken);
3162 // Each time OCStartPresence is called
3163 // a different random 32-bit integer number is used
3164 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3166 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3167 OC_PRESENCE_TRIGGER_CREATE);
3170 OCStackResult OCStopPresence()
3172 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3173 OCStackResult result = OC_STACK_ERROR;
3175 if(presenceResource.handle)
3177 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3179 // make resource inactive
3180 result = OCChangeResourceProperty(
3181 &(((OCResource *) presenceResource.handle)->resourceProperties),
3185 if(result != OC_STACK_OK)
3188 "Changing the presence resource properties to ACTIVE not successful");
3192 return SendStopNotification();
3196 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3197 void* callbackParameter)
3199 defaultDeviceHandler = entityHandler;
3200 defaultDeviceHandlerCallbackParameter = callbackParameter;
3205 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3207 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3209 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3211 if (validatePlatformInfo(platformInfo))
3213 return SavePlatformInfo(platformInfo);
3217 return OC_STACK_INVALID_PARAM;
3222 return OC_STACK_ERROR;
3226 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3228 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3230 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3232 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3233 return OC_STACK_INVALID_PARAM;
3236 if (deviceInfo.types)
3238 OCStringLL *type = deviceInfo.types;
3239 OCResource *resource = findResource((OCResource *) deviceResource);
3242 return OC_STACK_INVALID_PARAM;
3247 OCBindResourceTypeToResource(deviceResource, type->value);
3251 return SaveDeviceInfo(deviceInfo);
3254 OCStackResult OCCreateResource(OCResourceHandle *handle,
3255 const char *resourceTypeName,
3256 const char *resourceInterfaceName,
3257 const char *uri, OCEntityHandler entityHandler,
3258 void* callbackParam,
3259 uint8_t resourceProperties)
3262 OCResource *pointer = NULL;
3263 OCStackResult result = OC_STACK_ERROR;
3265 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3267 if(myStackMode == OC_CLIENT)
3269 return OC_STACK_INVALID_PARAM;
3271 // Validate parameters
3272 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3274 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3275 return OC_STACK_INVALID_URI;
3277 // Is it presented during resource discovery?
3278 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3280 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3281 return OC_STACK_INVALID_PARAM;
3284 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3286 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3290 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3292 // Make sure resourceProperties bitmask has allowed properties specified
3293 if (resourceProperties
3294 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3295 OC_EXPLICIT_DISCOVERABLE
3304 OIC_LOG(ERROR, TAG, "Invalid property");
3305 return OC_STACK_INVALID_PARAM;
3308 // If the headResource is NULL, then no resources have been created...
3309 pointer = headResource;
3312 // At least one resources is in the resource list, so we need to search for
3313 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3316 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3318 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3319 return OC_STACK_INVALID_PARAM;
3321 pointer = pointer->next;
3324 // Create the pointer and insert it into the resource list
3325 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3328 result = OC_STACK_NO_MEMORY;
3331 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3333 insertResource(pointer);
3336 pointer->uri = OICStrdup(uri);
3339 result = OC_STACK_NO_MEMORY;
3343 // Set properties. Set OC_ACTIVE
3344 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3347 // Add the resourcetype to the resource
3348 result = BindResourceTypeToResource(pointer, resourceTypeName);
3349 if (result != OC_STACK_OK)
3351 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3355 // Add the resourceinterface to the resource
3356 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3357 if (result != OC_STACK_OK)
3359 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3363 // If an entity handler has been passed, attach it to the newly created
3364 // resource. Otherwise, set the default entity handler.
3367 pointer->entityHandler = entityHandler;
3368 pointer->entityHandlerCallbackParam = callbackParam;
3372 pointer->entityHandler = defaultResourceEHandler;
3373 pointer->entityHandlerCallbackParam = NULL;
3376 // Initialize a pointer indicating child resources in case of collection
3377 pointer->rsrcChildResourcesHead = NULL;
3380 result = OC_STACK_OK;
3382 #ifdef WITH_PRESENCE
3383 if (presenceResource.handle)
3385 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3386 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3390 if (result != OC_STACK_OK)
3392 // Deep delete of resource and other dynamic elements that it contains
3393 deleteResource(pointer);
3398 OCStackResult OCBindResource(
3399 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3401 OCResource *resource = NULL;
3402 OCChildResource *tempChildResource = NULL;
3403 OCChildResource *newChildResource = NULL;
3405 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3407 // Validate parameters
3408 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3409 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3410 // Container cannot contain itself
3411 if (collectionHandle == resourceHandle)
3413 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3414 return OC_STACK_INVALID_PARAM;
3417 // Use the handle to find the resource in the resource linked list
3418 resource = findResource((OCResource *) collectionHandle);
3421 OIC_LOG(ERROR, TAG, "Collection handle not found");
3422 return OC_STACK_INVALID_PARAM;
3425 // Look for an open slot to add add the child resource.
3426 // If found, add it and return success
3428 tempChildResource = resource->rsrcChildResourcesHead;
3430 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3432 // TODO: what if one of child resource was deregistered without unbinding?
3433 tempChildResource = tempChildResource->next;
3436 // Do memory allocation for child resource
3437 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3438 if(!newChildResource)
3440 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3441 return OC_STACK_ERROR;
3444 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3445 newChildResource->next = NULL;
3447 if(!resource->rsrcChildResourcesHead)
3449 resource->rsrcChildResourcesHead = newChildResource;
3452 tempChildResource->next = newChildResource;
3455 OIC_LOG(INFO, TAG, "resource bound");
3457 #ifdef WITH_PRESENCE
3458 if (presenceResource.handle)
3460 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3461 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3462 OC_PRESENCE_TRIGGER_CHANGE);
3469 OCStackResult OCUnBindResource(
3470 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3472 OCResource *resource = NULL;
3473 OCChildResource *tempChildResource = NULL;
3474 OCChildResource *tempLastChildResource = NULL;
3476 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3478 // Validate parameters
3479 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3480 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3481 // Container cannot contain itself
3482 if (collectionHandle == resourceHandle)
3484 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3485 return OC_STACK_INVALID_PARAM;
3488 // Use the handle to find the resource in the resource linked list
3489 resource = findResource((OCResource *) collectionHandle);
3492 OIC_LOG(ERROR, TAG, "Collection handle not found");
3493 return OC_STACK_INVALID_PARAM;
3496 // Look for an open slot to add add the child resource.
3497 // If found, add it and return success
3498 if(!resource->rsrcChildResourcesHead)
3500 OIC_LOG(INFO, TAG, "resource not found in collection");
3502 // Unable to add resourceHandle, so return error
3503 return OC_STACK_ERROR;
3507 tempChildResource = resource->rsrcChildResourcesHead;
3509 while (tempChildResource)
3511 if(tempChildResource->rsrcResource == resourceHandle)
3513 // if resource going to be unbinded is the head one.
3514 if( tempChildResource == resource->rsrcChildResourcesHead )
3516 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3517 OICFree(resource->rsrcChildResourcesHead);
3518 resource->rsrcChildResourcesHead = temp;
3523 OCChildResource *temp = tempChildResource->next;
3524 OICFree(tempChildResource);
3525 tempLastChildResource->next = temp;
3529 OIC_LOG(INFO, TAG, "resource unbound");
3531 // Send notification when resource is unbounded successfully.
3532 #ifdef WITH_PRESENCE
3533 if (presenceResource.handle)
3535 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3536 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3537 OC_PRESENCE_TRIGGER_CHANGE);
3540 tempChildResource = NULL;
3541 tempLastChildResource = NULL;
3547 tempLastChildResource = tempChildResource;
3548 tempChildResource = tempChildResource->next;
3551 OIC_LOG(INFO, TAG, "resource not found in collection");
3553 tempChildResource = NULL;
3554 tempLastChildResource = NULL;
3556 // Unable to add resourceHandle, so return error
3557 return OC_STACK_ERROR;
3560 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3562 if (!resourceItemName)
3566 // Per RFC 6690 only registered values must follow the first rule below.
3567 // At this point in time the only values registered begin with "core", and
3568 // all other values are specified as opaque strings where multiple values
3569 // are separated by a space.
3570 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3572 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3574 if (resourceItemName[index] != '.'
3575 && resourceItemName[index] != '-'
3576 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3577 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3585 for (size_t index = 0; resourceItemName[index]; ++index)
3587 if (resourceItemName[index] == ' '
3588 || resourceItemName[index] == '\t'
3589 || resourceItemName[index] == '\r'
3590 || resourceItemName[index] == '\n')
3600 OCStackResult BindResourceTypeToResource(OCResource* resource,
3601 const char *resourceTypeName)
3603 OCResourceType *pointer = NULL;
3605 OCStackResult result = OC_STACK_ERROR;
3607 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3609 if (!ValidateResourceTypeInterface(resourceTypeName))
3611 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3612 return OC_STACK_INVALID_PARAM;
3615 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3618 result = OC_STACK_NO_MEMORY;
3622 str = OICStrdup(resourceTypeName);
3625 result = OC_STACK_NO_MEMORY;
3628 pointer->resourcetypename = str;
3629 pointer->next = NULL;
3631 insertResourceType(resource, pointer);
3632 result = OC_STACK_OK;
3635 if (result != OC_STACK_OK)
3644 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3645 const char *resourceInterfaceName)
3647 OCResourceInterface *pointer = NULL;
3649 OCStackResult result = OC_STACK_ERROR;
3651 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3653 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3655 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3656 return OC_STACK_INVALID_PARAM;
3659 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3661 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3664 result = OC_STACK_NO_MEMORY;
3668 str = OICStrdup(resourceInterfaceName);
3671 result = OC_STACK_NO_MEMORY;
3674 pointer->name = str;
3676 // Bind the resourceinterface to the resource
3677 insertResourceInterface(resource, pointer);
3679 result = OC_STACK_OK;
3682 if (result != OC_STACK_OK)
3691 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3692 const char *resourceTypeName)
3695 OCStackResult result = OC_STACK_ERROR;
3696 OCResource *resource = NULL;
3698 resource = findResource((OCResource *) handle);
3701 OIC_LOG(ERROR, TAG, "Resource not found");
3702 return OC_STACK_ERROR;
3705 result = BindResourceTypeToResource(resource, resourceTypeName);
3707 #ifdef WITH_PRESENCE
3708 if(presenceResource.handle)
3710 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3711 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3718 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3719 const char *resourceInterfaceName)
3722 OCStackResult result = OC_STACK_ERROR;
3723 OCResource *resource = NULL;
3725 resource = findResource((OCResource *) handle);
3728 OIC_LOG(ERROR, TAG, "Resource not found");
3729 return OC_STACK_ERROR;
3732 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3734 #ifdef WITH_PRESENCE
3735 if (presenceResource.handle)
3737 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3738 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3745 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3747 OCResource *pointer = headResource;
3749 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3753 *numResources = *numResources + 1;
3754 pointer = pointer->next;
3759 OCResourceHandle OCGetResourceHandle(uint8_t index)
3761 OCResource *pointer = headResource;
3763 for( uint8_t i = 0; i < index && pointer; ++i)
3765 pointer = pointer->next;
3767 return (OCResourceHandle) pointer;
3770 OCStackResult OCDeleteResource(OCResourceHandle handle)
3774 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3775 return OC_STACK_INVALID_PARAM;
3778 OCResource *resource = findResource((OCResource *) handle);
3779 if (resource == NULL)
3781 OIC_LOG(ERROR, TAG, "Resource not found");
3782 return OC_STACK_NO_RESOURCE;
3785 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3787 OIC_LOG(ERROR, TAG, "Error deleting resource");
3788 return OC_STACK_ERROR;
3794 const char *OCGetResourceUri(OCResourceHandle handle)
3796 OCResource *resource = NULL;
3798 resource = findResource((OCResource *) handle);
3801 return resource->uri;
3803 return (const char *) NULL;
3806 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3808 OCResource *resource = NULL;
3810 resource = findResource((OCResource *) handle);
3813 return resource->resourceProperties;
3815 return (OCResourceProperty)-1;
3818 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3819 uint8_t *numResourceTypes)
3821 OCResource *resource = NULL;
3822 OCResourceType *pointer = NULL;
3824 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3825 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3827 *numResourceTypes = 0;
3829 resource = findResource((OCResource *) handle);
3832 pointer = resource->rsrcType;
3835 *numResourceTypes = *numResourceTypes + 1;
3836 pointer = pointer->next;
3842 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3844 OCResourceType *resourceType = NULL;
3846 resourceType = findResourceTypeAtIndex(handle, index);
3849 return resourceType->resourcetypename;
3851 return (const char *) NULL;
3854 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3855 uint8_t *numResourceInterfaces)
3857 OCResourceInterface *pointer = NULL;
3858 OCResource *resource = NULL;
3860 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3861 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3863 *numResourceInterfaces = 0;
3864 resource = findResource((OCResource *) handle);
3867 pointer = resource->rsrcInterface;
3870 *numResourceInterfaces = *numResourceInterfaces + 1;
3871 pointer = pointer->next;
3877 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3879 OCResourceInterface *resourceInterface = NULL;
3881 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3882 if (resourceInterface)
3884 return resourceInterface->name;
3886 return (const char *) NULL;
3889 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3892 OCResource *resource = NULL;
3893 OCChildResource *tempChildResource = NULL;
3896 resource = findResource((OCResource *) collectionHandle);
3902 tempChildResource = resource->rsrcChildResourcesHead;
3904 while(tempChildResource)
3908 return tempChildResource->rsrcResource;
3911 tempChildResource = tempChildResource->next;
3914 // In this case, the number of resource handles in the collection exceeds the index
3915 tempChildResource = NULL;
3919 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3920 OCEntityHandler entityHandler,
3921 void* callbackParam)
3923 OCResource *resource = NULL;
3925 // Validate parameters
3926 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3928 // Use the handle to find the resource in the resource linked list
3929 resource = findResource((OCResource *)handle);
3932 OIC_LOG(ERROR, TAG, "Resource not found");
3933 return OC_STACK_ERROR;
3937 resource->entityHandler = entityHandler;
3938 resource->entityHandlerCallbackParam = callbackParam;
3940 #ifdef WITH_PRESENCE
3941 if (presenceResource.handle)
3943 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3944 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3951 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3953 OCResource *resource = NULL;
3955 resource = findResource((OCResource *)handle);
3958 OIC_LOG(ERROR, TAG, "Resource not found");
3963 return resource->entityHandler;
3966 void incrementSequenceNumber(OCResource * resPtr)
3968 // Increment the sequence number
3969 resPtr->sequenceNum += 1;
3970 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3972 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3977 #ifdef WITH_PRESENCE
3978 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3979 OCPresenceTrigger trigger)
3981 OIC_LOG(INFO, TAG, "SendPresenceNotification");
3982 OCResource *resPtr = NULL;
3983 OCStackResult result = OC_STACK_ERROR;
3984 OCMethod method = OC_REST_PRESENCE;
3985 uint32_t maxAge = 0;
3986 resPtr = findResource((OCResource *) presenceResource.handle);
3989 return OC_STACK_NO_RESOURCE;
3992 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3994 maxAge = presenceResource.presenceTTL;
3996 result = SendAllObserverNotification(method, resPtr, maxAge,
3997 trigger, resourceType, OC_LOW_QOS);
4003 OCStackResult SendStopNotification()
4005 OIC_LOG(INFO, TAG, "SendStopNotification");
4006 OCResource *resPtr = NULL;
4007 OCStackResult result = OC_STACK_ERROR;
4008 OCMethod method = OC_REST_PRESENCE;
4009 resPtr = findResource((OCResource *) presenceResource.handle);
4012 return OC_STACK_NO_RESOURCE;
4015 // maxAge is 0. ResourceType is NULL.
4016 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4022 #endif // WITH_PRESENCE
4023 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4025 OCResource *resPtr = NULL;
4026 OCStackResult result = OC_STACK_ERROR;
4027 OCMethod method = OC_REST_NOMETHOD;
4028 uint32_t maxAge = 0;
4030 OIC_LOG(INFO, TAG, "Notifying all observers");
4031 #ifdef WITH_PRESENCE
4032 if(handle == presenceResource.handle)
4036 #endif // WITH_PRESENCE
4037 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4039 // Verify that the resource exists
4040 resPtr = findResource ((OCResource *) handle);
4043 return OC_STACK_NO_RESOURCE;
4047 //only increment in the case of regular observing (not presence)
4048 incrementSequenceNumber(resPtr);
4049 method = OC_REST_OBSERVE;
4050 maxAge = MAX_OBSERVE_AGE;
4051 #ifdef WITH_PRESENCE
4052 result = SendAllObserverNotification (method, resPtr, maxAge,
4053 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4055 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4062 OCNotifyListOfObservers (OCResourceHandle handle,
4063 OCObservationId *obsIdList,
4064 uint8_t numberOfIds,
4065 const OCRepPayload *payload,
4066 OCQualityOfService qos)
4068 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4070 OCResource *resPtr = NULL;
4071 //TODO: we should allow the server to define this
4072 uint32_t maxAge = MAX_OBSERVE_AGE;
4074 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4075 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4076 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4078 resPtr = findResource ((OCResource *) handle);
4079 if (NULL == resPtr || myStackMode == OC_CLIENT)
4081 return OC_STACK_NO_RESOURCE;
4085 incrementSequenceNumber(resPtr);
4087 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4088 payload, maxAge, qos));
4091 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4093 OCStackResult result = OC_STACK_ERROR;
4094 OCServerRequest *serverRequest = NULL;
4096 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4098 // Validate input parameters
4099 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4100 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4103 // Get pointer to request info
4104 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4107 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4108 result = serverRequest->ehResponseHandler(ehResponse);
4114 //#ifdef DIRECT_PAIRING
4115 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4117 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4118 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4120 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4124 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4127 const OCDPDev_t* OCGetDirectPairedDevices()
4129 return (const OCDPDev_t*)DPGetPairedDevices();
4132 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4133 OCDirectPairingCB resultCallback)
4135 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4136 if(NULL == peer || NULL == pinNumber)
4138 OIC_LOG(ERROR, TAG, "Invalid parameters");
4139 return OC_STACK_INVALID_PARAM;
4141 if (NULL == resultCallback)
4143 OIC_LOG(ERROR, TAG, "Invalid callback");
4144 return OC_STACK_INVALID_CALLBACK;
4147 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4148 pinNumber, (OCDirectPairingResultCB)resultCallback);
4150 //#endif // DIRECT_PAIRING
4152 //-----------------------------------------------------------------------------
4153 // Private internal function definitions
4154 //-----------------------------------------------------------------------------
4155 static OCDoHandle GenerateInvocationHandle()
4157 OCDoHandle handle = NULL;
4158 // Generate token here, it will be deleted when the transaction is deleted
4159 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4162 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4168 #ifdef WITH_PRESENCE
4169 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4170 OCResourceProperty resourceProperties, uint8_t enable)
4174 return OC_STACK_INVALID_PARAM;
4176 if (resourceProperties
4177 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4179 OIC_LOG(ERROR, TAG, "Invalid property");
4180 return OC_STACK_INVALID_PARAM;
4184 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4188 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4194 OCStackResult initResources()
4196 OCStackResult result = OC_STACK_OK;
4198 headResource = NULL;
4199 tailResource = NULL;
4200 // Init Virtual Resources
4201 #ifdef WITH_PRESENCE
4202 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4204 result = OCCreateResource(&presenceResource.handle,
4205 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4207 OC_RSRVD_PRESENCE_URI,
4211 //make resource inactive
4212 result = OCChangeResourceProperty(
4213 &(((OCResource *) presenceResource.handle)->resourceProperties),
4216 #ifndef WITH_ARDUINO
4217 if (result == OC_STACK_OK)
4219 result = SRMInitSecureResources();
4223 if(result == OC_STACK_OK)
4225 CreateResetProfile();
4226 result = OCCreateResource(&deviceResource,
4227 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4228 OC_RSRVD_INTERFACE_DEFAULT,
4229 OC_RSRVD_DEVICE_URI,
4233 if(result == OC_STACK_OK)
4235 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4236 OC_RSRVD_INTERFACE_READ);
4240 if(result == OC_STACK_OK)
4242 result = OCCreateResource(&platformResource,
4243 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4244 OC_RSRVD_INTERFACE_DEFAULT,
4245 OC_RSRVD_PLATFORM_URI,
4249 if(result == OC_STACK_OK)
4251 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4252 OC_RSRVD_INTERFACE_READ);
4259 void insertResource(OCResource *resource)
4263 headResource = resource;
4264 tailResource = resource;
4268 tailResource->next = resource;
4269 tailResource = resource;
4271 resource->next = NULL;
4274 OCResource *findResource(OCResource *resource)
4276 OCResource *pointer = headResource;
4280 if (pointer == resource)
4284 pointer = pointer->next;
4289 void deleteAllResources()
4291 OCResource *pointer = headResource;
4292 OCResource *temp = NULL;
4296 temp = pointer->next;
4297 #ifdef WITH_PRESENCE
4298 if (pointer != (OCResource *) presenceResource.handle)
4300 #endif // WITH_PRESENCE
4301 deleteResource(pointer);
4302 #ifdef WITH_PRESENCE
4304 #endif // WITH_PRESENCE
4307 memset(&platformResource, 0, sizeof(platformResource));
4308 memset(&deviceResource, 0, sizeof(deviceResource));
4310 memset(&brokerResource, 0, sizeof(brokerResource));
4313 SRMDeInitSecureResources();
4315 #ifdef WITH_PRESENCE
4316 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4317 // presence notification attributed to their deletion to be processed.
4318 deleteResource((OCResource *) presenceResource.handle);
4319 memset(&presenceResource, 0, sizeof(presenceResource));
4320 #endif // WITH_PRESENCE
4323 OCStackResult deleteResource(OCResource *resource)
4325 OCResource *prev = NULL;
4326 OCResource *temp = NULL;
4329 OIC_LOG(DEBUG,TAG,"resource is NULL");
4330 return OC_STACK_INVALID_PARAM;
4333 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4335 temp = headResource;
4338 if (temp == resource)
4340 // Invalidate all Resource Properties.
4341 resource->resourceProperties = (OCResourceProperty) 0;
4342 #ifdef WITH_PRESENCE
4343 if(resource != (OCResource *) presenceResource.handle)
4345 #endif // WITH_PRESENCE
4346 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4347 #ifdef WITH_PRESENCE
4350 if(presenceResource.handle)
4352 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4353 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4356 // Only resource in list.
4357 if (temp == headResource && temp == tailResource)
4359 headResource = NULL;
4360 tailResource = NULL;
4363 else if (temp == headResource)
4365 headResource = temp->next;
4368 else if (temp == tailResource)
4370 tailResource = prev;
4371 tailResource->next = NULL;
4375 prev->next = temp->next;
4378 deleteResourceElements(temp);
4389 return OC_STACK_ERROR;
4392 void deleteResourceElements(OCResource *resource)
4399 OICFree(resource->uri);
4400 deleteResourceType(resource->rsrcType);
4401 deleteResourceInterface(resource->rsrcInterface);
4404 void deleteResourceType(OCResourceType *resourceType)
4406 OCResourceType *pointer = resourceType;
4407 OCResourceType *next = NULL;
4411 next = pointer->next;
4412 OICFree(pointer->resourcetypename);
4418 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4420 OCResourceInterface *pointer = resourceInterface;
4421 OCResourceInterface *next = NULL;
4425 next = pointer->next;
4426 OICFree(pointer->name);
4432 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4434 OCResourceType *pointer = NULL;
4435 OCResourceType *previous = NULL;
4436 if (!resource || !resourceType)
4440 // resource type list is empty.
4441 else if (!resource->rsrcType)
4443 resource->rsrcType = resourceType;
4447 pointer = resource->rsrcType;
4451 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4453 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4454 OICFree(resourceType->resourcetypename);
4455 OICFree(resourceType);
4459 pointer = pointer->next;
4464 previous->next = resourceType;
4467 resourceType->next = NULL;
4469 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4472 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4474 OCResource *resource = NULL;
4475 OCResourceType *pointer = NULL;
4477 // Find the specified resource
4478 resource = findResource((OCResource *) handle);
4484 // Make sure a resource has a resourcetype
4485 if (!resource->rsrcType)
4490 // Iterate through the list
4491 pointer = resource->rsrcType;
4492 for(uint8_t i = 0; i< index && pointer; ++i)
4494 pointer = pointer->next;
4499 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4501 if(resourceTypeList && resourceTypeName)
4503 OCResourceType * rtPointer = resourceTypeList;
4504 while(resourceTypeName && rtPointer)
4506 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4507 if(rtPointer->resourcetypename &&
4508 strcmp(resourceTypeName, (const char *)
4509 (rtPointer->resourcetypename)) == 0)
4513 rtPointer = rtPointer->next;
4521 * Insert a new interface into interface linked list only if not already present.
4522 * If alredy present, 2nd arg is free'd.
4523 * Default interface will always be first if present.
4525 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4527 OCResourceInterface *pointer = NULL;
4528 OCResourceInterface *previous = NULL;
4530 newInterface->next = NULL;
4532 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4534 if (!*firstInterface)
4536 // If first interface is not oic.if.baseline, by default add it as first interface type.
4537 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4539 *firstInterface = newInterface;
4543 OCStackResult result = BindResourceInterfaceToResource(resource,
4544 OC_RSRVD_INTERFACE_DEFAULT);
4545 if (result != OC_STACK_OK)
4547 OICFree(newInterface->name);
4548 OICFree(newInterface);
4551 if (*firstInterface)
4553 (*firstInterface)->next = newInterface;
4557 // If once add oic.if.baseline, later too below code take care of freeing memory.
4558 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4560 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4562 OICFree(newInterface->name);
4563 OICFree(newInterface);
4566 // This code will not hit anymore, keeping
4569 newInterface->next = *firstInterface;
4570 *firstInterface = newInterface;
4575 pointer = *firstInterface;
4578 if (strcmp(newInterface->name, pointer->name) == 0)
4580 OICFree(newInterface->name);
4581 OICFree(newInterface);
4585 pointer = pointer->next;
4590 previous->next = newInterface;
4595 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4598 OCResource *resource = NULL;
4599 OCResourceInterface *pointer = NULL;
4601 // Find the specified resource
4602 resource = findResource((OCResource *) handle);
4608 // Make sure a resource has a resourceinterface
4609 if (!resource->rsrcInterface)
4614 // Iterate through the list
4615 pointer = resource->rsrcInterface;
4617 for (uint8_t i = 0; i < index && pointer; ++i)
4619 pointer = pointer->next;
4625 * This function splits the uri using the '?' delimiter.
4626 * "uriWithoutQuery" is the block of characters between the beginning
4627 * till the delimiter or '\0' which ever comes first.
4628 * "query" is whatever is to the right of the delimiter if present.
4629 * No delimiter sets the query to NULL.
4630 * If either are present, they will be malloc'ed into the params 2, 3.
4631 * The first param, *uri is left untouched.
4633 * NOTE: This function does not account for whitespace at the end of the uri NOR
4634 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4635 * part of the query.
4637 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4641 return OC_STACK_INVALID_URI;
4643 if(!query || !uriWithoutQuery)
4645 return OC_STACK_INVALID_PARAM;
4649 *uriWithoutQuery = NULL;
4651 size_t uriWithoutQueryLen = 0;
4652 size_t queryLen = 0;
4653 size_t uriLen = strlen(uri);
4655 char *pointerToDelimiter = strstr(uri, "?");
4657 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4658 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4660 if (uriWithoutQueryLen)
4662 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4663 if (!*uriWithoutQuery)
4667 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4671 *query = (char *) OICCalloc(queryLen + 1, 1);
4674 OICFree(*uriWithoutQuery);
4675 *uriWithoutQuery = NULL;
4678 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4684 return OC_STACK_NO_MEMORY;
4687 static const OicUuid_t* OCGetServerInstanceID(void)
4689 static bool generated = false;
4690 static OicUuid_t sid;
4696 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4698 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4705 const char* OCGetServerInstanceIDString(void)
4707 static bool generated = false;
4708 static char sidStr[UUID_STRING_SIZE];
4715 const OicUuid_t *sid = OCGetServerInstanceID();
4716 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4718 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4726 CAResult_t OCSelectNetwork()
4728 CAResult_t retResult = CA_STATUS_FAILED;
4729 CAResult_t caResult = CA_STATUS_OK;
4731 CATransportAdapter_t connTypes[] = {
4733 CA_ADAPTER_RFCOMM_BTEDR,
4734 CA_ADAPTER_GATT_BTLE,
4737 ,CA_ADAPTER_REMOTE_ACCESS
4744 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4746 for(int i = 0; i < numConnTypes; i++)
4748 // If CA status is not initialized, CASelectNetwork() will not be called.
4749 if (caResult != CA_STATUS_NOT_INITIALIZED)
4751 caResult = CASelectNetwork(connTypes[i]);
4752 if (caResult == CA_STATUS_OK)
4754 retResult = CA_STATUS_OK;
4759 if (retResult != CA_STATUS_OK)
4761 return caResult; // Returns error of appropriate transport that failed fatally.
4767 OCStackResult CAResultToOCResult(CAResult_t caResult)
4773 case CA_STATUS_INVALID_PARAM:
4774 return OC_STACK_INVALID_PARAM;
4775 case CA_ADAPTER_NOT_ENABLED:
4776 return OC_STACK_ADAPTER_NOT_ENABLED;
4777 case CA_SERVER_STARTED_ALREADY:
4779 case CA_SERVER_NOT_STARTED:
4780 return OC_STACK_ERROR;
4781 case CA_DESTINATION_NOT_REACHABLE:
4782 return OC_STACK_COMM_ERROR;
4783 case CA_SOCKET_OPERATION_FAILED:
4784 return OC_STACK_COMM_ERROR;
4785 case CA_SEND_FAILED:
4786 return OC_STACK_COMM_ERROR;
4787 case CA_RECEIVE_FAILED:
4788 return OC_STACK_COMM_ERROR;
4789 case CA_MEMORY_ALLOC_FAILED:
4790 return OC_STACK_NO_MEMORY;
4791 case CA_REQUEST_TIMEOUT:
4792 return OC_STACK_TIMEOUT;
4793 case CA_DESTINATION_DISCONNECTED:
4794 return OC_STACK_COMM_ERROR;
4795 case CA_STATUS_FAILED:
4796 return OC_STACK_ERROR;
4797 case CA_NOT_SUPPORTED:
4798 return OC_STACK_NOTIMPL;
4800 return OC_STACK_ERROR;
4804 bool OCResultToSuccess(OCStackResult ocResult)
4809 case OC_STACK_RESOURCE_CREATED:
4810 case OC_STACK_RESOURCE_DELETED:
4811 case OC_STACK_CONTINUE:
4812 case OC_STACK_RESOURCE_CHANGED:
4813 case OC_STACK_SLOW_RESOURCE:
4821 OCStackResult OCSetProxyURI(const char *uri)
4823 return CAResultToOCResult(CASetProxyUri(uri));
4827 #if defined(RD_CLIENT) || defined(RD_SERVER)
4828 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4830 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4832 OCResource *resource = NULL;
4834 resource = findResource((OCResource *) handle);
4837 OIC_LOG(ERROR, TAG, "Resource not found");
4838 return OC_STACK_ERROR;
4841 resource->ins = ins;
4846 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4850 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4854 OCResource *pointer = headResource;
4858 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4860 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4863 pointer = pointer->next;
4868 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4870 OCResource *resource = NULL;
4872 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4873 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4875 resource = findResource((OCResource *) handle);
4878 *ins = resource->ins;
4881 return OC_STACK_ERROR;
4884 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4885 void* optionData, size_t optionDataLength)
4889 OIC_LOG (INFO, TAG, "Header options are NULL");
4890 return OC_STACK_INVALID_PARAM;
4895 OIC_LOG (INFO, TAG, "optionData are NULL");
4896 return OC_STACK_INVALID_PARAM;
4901 OIC_LOG (INFO, TAG, "numOptions is NULL");
4902 return OC_STACK_INVALID_PARAM;
4905 if (*numOptions >= MAX_HEADER_OPTIONS)
4907 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4908 return OC_STACK_NO_MEMORY;
4911 ocHdrOpt += *numOptions;
4912 ocHdrOpt->protocolID = OC_COAP_ID;
4913 ocHdrOpt->optionID = optionID;
4914 ocHdrOpt->optionLength =
4915 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4916 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4917 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4922 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
4923 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
4925 if (!ocHdrOpt || !numOptions)
4927 OIC_LOG (INFO, TAG, "No options present");
4933 OIC_LOG (INFO, TAG, "optionData are NULL");
4934 return OC_STACK_INVALID_PARAM;
4937 if (!receivedDataLength)
4939 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
4940 return OC_STACK_INVALID_PARAM;
4943 for (uint8_t i = 0; i < numOptions; i++)
4945 if (ocHdrOpt[i].optionID == optionID)
4947 if (optionDataLength >= ocHdrOpt->optionLength)
4949 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
4950 *receivedDataLength = ocHdrOpt->optionLength;
4955 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
4956 return OC_STACK_ERROR;
4964 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
4966 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
4967 if (g_adapterHandler)
4969 g_adapterHandler(adapter, enabled);
4973 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
4975 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
4976 if (g_connectionHandler)
4978 g_connectionHandler(info, isConnected);
4982 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
4983 CAConnectionStateChangedCB connectionHandler)
4985 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
4986 g_adapterHandler = adapterHandler;
4987 g_connectionHandler = connectionHandler;
4990 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
4995 ret = GetDoxmDeviceID(&oicUuid);
4996 if (OC_STACK_OK == ret)
4998 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5002 OIC_LOG(ERROR, TAG, "Device ID Get error");
5007 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5011 OIC_LOG(ERROR, TAG, "Set deviceId DOXM");
5013 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5014 for(int i=0;i < UUID_LENGTH; i++)
5016 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5018 ret = SetDoxmDeviceID(&oicUuid);