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;
728 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
730 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
739 // This Response Code is like HTTP 204 "No Content" but only used in
740 // response to POST and PUT requests.
744 // This Response Code is like HTTP 200 "OK" but only used in response to
749 // This should not happen but,
750 // give it a value just in case but output an error
752 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
756 case OC_STACK_RESOURCE_CREATED:
759 case OC_STACK_RESOURCE_DELETED:
762 case OC_STACK_RESOURCE_CHANGED:
765 case OC_STACK_INVALID_QUERY:
768 case OC_STACK_INVALID_OPTION:
771 case OC_STACK_NO_RESOURCE:
774 case OC_STACK_COMM_ERROR:
775 ret = CA_RETRANSMIT_TIMEOUT;
777 case OC_STACK_UNAUTHORIZED_REQ:
778 ret = CA_UNAUTHORIZED_REQ;
786 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
788 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
790 // supply default behavior.
791 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
793 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
795 if ((caFlags & OC_MASK_SCOPE) == 0)
797 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
802 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
804 return (OCTransportFlags)caFlags;
807 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
809 uint32_t lowerBound = 0;
810 uint32_t higherBound = 0;
812 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
814 return OC_STACK_INVALID_PARAM;
817 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
819 cbNode->presence->TTL = maxAgeSeconds;
821 for (int index = 0; index < PresenceTimeOutSize; index++)
823 // Guard against overflow
824 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
827 lowerBound = GetTicks((PresenceTimeOut[index] *
828 cbNode->presence->TTL *
829 MILLISECONDS_PER_SECOND)/100);
833 lowerBound = GetTicks(UINT32_MAX);
836 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
839 higherBound = GetTicks((PresenceTimeOut[index + 1] *
840 cbNode->presence->TTL *
841 MILLISECONDS_PER_SECOND)/100);
845 higherBound = GetTicks(UINT32_MAX);
848 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
850 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
851 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
852 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
855 cbNode->presence->TTLlevel = 0;
857 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
861 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
863 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
865 return OC_RSRVD_TRIGGER_CREATE;
867 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
869 return OC_RSRVD_TRIGGER_CHANGE;
873 return OC_RSRVD_TRIGGER_DELETE;
877 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
881 return OC_PRESENCE_TRIGGER_CREATE;
883 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
885 return OC_PRESENCE_TRIGGER_CREATE;
887 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
889 return OC_PRESENCE_TRIGGER_CHANGE;
893 return OC_PRESENCE_TRIGGER_DELETE;
898 * Encode an address string to match RFC 6874.
900 * @param outputAddress a char array to be written with the encoded string.
902 * @param outputSize size of outputAddress buffer.
904 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
905 * containing a valid IPv6 address string.
907 * @return OC_STACK_OK if encoding succeeded.
908 * Else an error occured.
910 OCStackResult encodeAddressForRFC6874(char *outputAddress,
912 const char *inputAddress)
914 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
915 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
917 size_t inputLength = strnlen(inputAddress, outputSize);
919 // inputSize includes the null terminator
920 size_t inputSize = inputLength + 1;
922 if (inputSize > outputSize)
924 OIC_LOG_V(ERROR, TAG,
925 "encodeAddressForRFC6874 failed: "
926 "outputSize (%zu) < inputSize (%zu)",
927 outputSize, inputSize);
929 return OC_STACK_ERROR;
932 char* percentChar = strchr(inputAddress, '%');
934 // If there is no '%' character, then no change is required to the string.
935 if (NULL == percentChar)
937 OICStrcpy(outputAddress, outputSize, inputAddress);
941 const char* addressPart = &inputAddress[0];
942 const char* scopeIdPart = percentChar + 1;
944 // Sanity check to make sure this string doesn't have more '%' characters
945 if (NULL != strchr(scopeIdPart, '%'))
947 return OC_STACK_ERROR;
950 // If no string follows the first '%', then the input was invalid.
951 if (scopeIdPart[0] == '\0')
953 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
954 return OC_STACK_ERROR;
957 // Check to see if the string is already encoded
958 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
960 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
961 return OC_STACK_ERROR;
964 // Fail if we don't have room for encoded string's two additional chars
965 if (outputSize < (inputSize + 2))
967 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
968 return OC_STACK_ERROR;
971 // Restore the null terminator with an escaped '%' character, per RFC 6874
972 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
973 strcat(outputAddress, "%25");
974 strcat(outputAddress, scopeIdPart);
980 * The cononical presence allows constructed URIs to be string compared.
982 * requestUri must be a char array of size CA_MAX_URI_LENGTH
984 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint,
985 char *presenceUri, bool isMulticast)
987 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
988 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
992 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
993 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
996 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
997 if (ep->adapter == CA_ADAPTER_IP)
999 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1001 if ('\0' == ep->addr[0]) // multicast
1003 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1007 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1009 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
1010 sizeof(addressEncoded),
1013 if (OC_STACK_OK != result)
1018 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1019 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1024 if ('\0' == ep->addr[0]) // multicast
1026 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1027 ep->port = OC_MULTICAST_PORT;
1029 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1030 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1034 // might work for other adapters (untested, but better than nothing)
1035 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1036 OC_RSRVD_PRESENCE_URI);
1040 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1041 const CAResponseInfo_t *responseInfo)
1043 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1044 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1046 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1047 ClientCB * cbNode = NULL;
1048 char *resourceTypeName = NULL;
1049 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1050 OCStackResult result = OC_STACK_ERROR;
1051 uint32_t maxAge = 0;
1053 char presenceUri[CA_MAX_URI_LENGTH];
1055 int presenceSubscribe = 0;
1056 int multicastPresenceSubscribe = 0;
1058 if (responseInfo->result != CA_CONTENT)
1060 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1061 return OC_STACK_ERROR;
1064 response.payload = NULL;
1065 response.result = OC_STACK_OK;
1067 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1068 FixUpClientResponse(&response);
1070 if (responseInfo->info.payload)
1072 result = OCParsePayload(&response.payload,
1073 PAYLOAD_TYPE_PRESENCE,
1074 responseInfo->info.payload,
1075 responseInfo->info.payloadSize);
1077 if(result != OC_STACK_OK)
1079 OIC_LOG(ERROR, TAG, "Presence parse failed");
1082 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1084 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1085 result = OC_STACK_ERROR;
1088 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1089 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1090 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1093 // check for unicast presence
1094 uriLen = FormCanonicalPresenceUri(endpoint, presenceUri,
1095 responseInfo->isMulticast);
1096 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1098 return OC_STACK_INVALID_URI;
1100 OIC_LOG(ERROR, TAG, "check for unicast presence");
1101 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1104 presenceSubscribe = 1;
1108 // check for multicast presence
1109 OIC_LOG(ERROR, TAG, "check for multicast presence");
1110 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1113 multicastPresenceSubscribe = 1;
1117 if (!presenceSubscribe && !multicastPresenceSubscribe)
1119 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1123 if (presenceSubscribe)
1125 if(cbNode->sequenceNumber == response.sequenceNumber)
1127 OIC_LOG(INFO, TAG, "No presence change");
1128 ResetPresenceTTL(cbNode, maxAge);
1129 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1135 OIC_LOG(INFO, TAG, "Stopping presence");
1136 response.result = OC_STACK_PRESENCE_STOPPED;
1137 if(cbNode->presence)
1139 OICFree(cbNode->presence->timeOut);
1140 OICFree(cbNode->presence);
1141 cbNode->presence = NULL;
1146 if(!cbNode->presence)
1148 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1150 if(!(cbNode->presence))
1152 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1153 result = OC_STACK_NO_MEMORY;
1157 VERIFY_NON_NULL_V(cbNode->presence);
1158 cbNode->presence->timeOut = NULL;
1159 cbNode->presence->timeOut = (uint32_t *)
1160 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1161 if(!(cbNode->presence->timeOut)){
1163 "Could not allocate memory for cbNode->presence->timeOut");
1164 OICFree(cbNode->presence);
1165 result = OC_STACK_NO_MEMORY;
1170 ResetPresenceTTL(cbNode, maxAge);
1172 cbNode->sequenceNumber = response.sequenceNumber;
1177 // This is the multicast case
1178 OIC_LOG(INFO, TAG, "this is the multicast presence");
1181 OIC_LOG(INFO, TAG, "Stopping presence");
1182 response.result = OC_STACK_PRESENCE_STOPPED;
1186 // Ensure that a filter is actually applied.
1187 if (resourceTypeName && cbNode->filterResourceType)
1189 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1190 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1196 OIC_LOG(INFO, TAG, "Callback for presence");
1198 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1200 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1202 FindAndDeleteClientCB(cbNode);
1206 OCPayloadDestroy(response.payload);
1210 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1212 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1214 if(responseInfo->info.resourceUri &&
1215 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1217 HandlePresenceResponse(endPoint, responseInfo);
1221 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1222 responseInfo->info.tokenLength, NULL, NULL);
1224 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1225 responseInfo->info.tokenLength);
1229 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1230 if(responseInfo->result == CA_EMPTY)
1232 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1233 // We do not have a case for the client to receive a RESET
1234 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1236 //This is the case of receiving an ACK on a request to a slow resource!
1237 OIC_LOG(INFO, TAG, "This is a pure ACK");
1238 //TODO: should we inform the client
1239 // app that at least the request was received at the server?
1242 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1244 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1245 OIC_LOG(INFO, TAG, "Calling into application address space");
1247 OCClientResponse response =
1248 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1249 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1250 FixUpClientResponse(&response);
1251 response.resourceUri = responseInfo->info.resourceUri;
1252 memcpy(response.identity.id, responseInfo->info.identity.id,
1253 sizeof (response.identity.id));
1254 response.identity.id_length = responseInfo->info.identity.id_length;
1256 response.result = CAResponseToOCStackResult(responseInfo->result);
1257 cbNode->callBack(cbNode->context,
1258 cbNode->handle, &response);
1259 FindAndDeleteClientCB(cbNode);
1263 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1264 OIC_LOG(INFO, TAG, "Calling into application address space");
1266 OCClientResponse response =
1267 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1268 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1269 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1270 FixUpClientResponse(&response);
1271 response.resourceUri = responseInfo->info.resourceUri;
1272 memcpy(response.identity.id, responseInfo->info.identity.id,
1273 sizeof (response.identity.id));
1274 response.identity.id_length = responseInfo->info.identity.id_length;
1276 response.result = CAResponseToOCStackResult(responseInfo->result);
1278 if(responseInfo->info.payload &&
1279 responseInfo->info.payloadSize)
1281 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1282 // check the security resource
1283 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1285 type = PAYLOAD_TYPE_SECURITY;
1287 else if (cbNode->method == OC_REST_DISCOVER)
1289 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1290 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1292 type = PAYLOAD_TYPE_DISCOVERY;
1295 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1297 type = PAYLOAD_TYPE_DISCOVERY;
1300 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1302 type = PAYLOAD_TYPE_DEVICE;
1304 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1306 type = PAYLOAD_TYPE_PLATFORM;
1308 #ifdef ROUTING_GATEWAY
1309 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1311 type = PAYLOAD_TYPE_REPRESENTATION;
1314 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1316 type = PAYLOAD_TYPE_REPRESENTATION ;
1319 else if (strcmp(cbNode->requestUri, OC_KEEPALIVE_RESOURCE_URI) == 0)
1321 type = PAYLOAD_TYPE_REPRESENTATION;
1326 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1327 cbNode->method, cbNode->requestUri);
1331 else if (cbNode->method == OC_REST_GET ||
1332 cbNode->method == OC_REST_PUT ||
1333 cbNode->method == OC_REST_POST ||
1334 cbNode->method == OC_REST_OBSERVE ||
1335 cbNode->method == OC_REST_OBSERVE_ALL ||
1336 cbNode->method == OC_REST_DELETE)
1338 if (cbNode->requestUri)
1340 if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1342 type = PAYLOAD_TYPE_PLATFORM;
1344 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1346 type = PAYLOAD_TYPE_DEVICE;
1348 if (type == PAYLOAD_TYPE_INVALID)
1350 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1351 cbNode->method, cbNode->requestUri);
1352 type = PAYLOAD_TYPE_REPRESENTATION;
1357 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1358 type = PAYLOAD_TYPE_REPRESENTATION;
1363 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1364 cbNode->method, cbNode->requestUri);
1368 if(OC_STACK_OK != OCParsePayload(&response.payload,
1370 responseInfo->info.payload,
1371 responseInfo->info.payloadSize))
1373 OIC_LOG(ERROR, TAG, "Error converting payload");
1374 OCPayloadDestroy(response.payload);
1379 response.numRcvdVendorSpecificHeaderOptions = 0;
1380 if(responseInfo->info.numOptions > 0)
1383 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1384 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1387 uint32_t observationOption;
1388 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1389 for (observationOption=0, i=0;
1390 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1394 (observationOption << 8) | optionData[i];
1396 response.sequenceNumber = observationOption;
1397 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1402 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1405 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1407 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1408 OCPayloadDestroy(response.payload);
1412 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1414 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1415 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1419 if (cbNode->method == OC_REST_OBSERVE &&
1420 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1421 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1422 response.sequenceNumber <= cbNode->sequenceNumber)
1424 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1425 response.sequenceNumber);
1429 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1432 cbNode->sequenceNumber = response.sequenceNumber;
1434 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1436 FindAndDeleteClientCB(cbNode);
1440 // To keep discovery callbacks active.
1441 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1442 MILLISECONDS_PER_SECOND);
1446 //Need to send ACK when the response is CON
1447 if(responseInfo->info.type == CA_MSG_CONFIRM)
1449 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1450 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1453 OCPayloadDestroy(response.payload);
1460 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1461 if(responseInfo->result == CA_EMPTY)
1463 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1464 if(responseInfo->info.type == CA_MSG_RESET)
1466 OIC_LOG(INFO, TAG, "This is a RESET");
1467 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1468 OC_OBSERVER_NOT_INTERESTED);
1470 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1472 OIC_LOG(INFO, TAG, "This is a pure ACK");
1473 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1474 OC_OBSERVER_STILL_INTERESTED);
1477 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1479 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1480 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1481 OC_OBSERVER_FAILED_COMM);
1486 if(!cbNode && !observer)
1488 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1489 || myStackMode == OC_GATEWAY)
1491 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1492 if(responseInfo->result == CA_EMPTY)
1494 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1498 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1499 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1500 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1504 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1505 || myStackMode == OC_GATEWAY)
1507 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1508 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1510 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1511 responseInfo->info.messageId);
1513 if (responseInfo->info.type == CA_MSG_RESET)
1515 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1516 responseInfo->info.messageId);
1524 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1526 VERIFY_NON_NULL_NR(endPoint, FATAL);
1527 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1529 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1531 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1532 #ifdef ROUTING_GATEWAY
1533 bool needRIHandling = false;
1535 * Routing manager is going to update either of endpoint or response or both.
1536 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1537 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1540 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1542 if(ret != OC_STACK_OK || !needRIHandling)
1544 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1550 * Put source in sender endpoint so that the next packet from application can be routed to
1551 * proper destination and remove "RM" coap header option before passing request / response to
1552 * RI as this option will make no sense to either RI or application.
1554 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1555 (uint8_t *) &(responseInfo->info.numOptions),
1556 (CAEndpoint_t *) endPoint);
1559 OCHandleResponse(endPoint, responseInfo);
1561 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1565 * This function handles error response from CA
1566 * code shall be added to handle the errors
1568 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1570 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1572 if (NULL == endPoint)
1574 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1578 if (NULL == errorInfo)
1580 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1584 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1585 errorInfo->info.tokenLength, NULL, NULL);
1588 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1589 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1590 FixUpClientResponse(&response);
1591 response.resourceUri = errorInfo->info.resourceUri;
1592 memcpy(response.identity.id, errorInfo->info.identity.id,
1593 sizeof (response.identity.id));
1594 response.identity.id_length = errorInfo->info.identity.id_length;
1595 response.result = CAResultToOCStackResult(errorInfo->result);
1597 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1600 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1604 * This function sends out Direct Stack Responses. These are responses that are not coming
1605 * from the application entity handler. These responses have no payload and are usually ACKs,
1606 * RESETs or some error conditions that were caught by the stack.
1608 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1609 const CAResponseResult_t responseResult, const CAMessageType_t type,
1610 const uint8_t numOptions, const CAHeaderOption_t *options,
1611 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1612 CADataType_t dataType)
1614 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1615 CAResponseInfo_t respInfo = {
1616 .result = responseResult
1618 respInfo.info.messageId = coapID;
1619 respInfo.info.numOptions = numOptions;
1621 if (respInfo.info.numOptions)
1623 respInfo.info.options =
1624 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1625 memcpy (respInfo.info.options, options,
1626 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1630 respInfo.info.payload = NULL;
1631 respInfo.info.token = token;
1632 respInfo.info.tokenLength = tokenLength;
1633 respInfo.info.type = type;
1634 respInfo.info.resourceUri = OICStrdup (resourceUri);
1635 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1636 respInfo.info.dataType = dataType;
1638 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1639 // Add the destination to route option from the endpoint->routeData.
1640 bool doPost = false;
1641 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1642 if(OC_STACK_OK != result)
1644 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1649 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1650 CARequestInfo_t reqInfo = {.method = CA_POST };
1651 /* The following initialization is not done in a single initializer block as in
1652 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1653 * does not have designated initalizers. This is a work-around for now.
1655 reqInfo.info.type = CA_MSG_NONCONFIRM;
1656 reqInfo.info.messageId = coapID;
1657 reqInfo.info.tokenLength = tokenLength;
1658 reqInfo.info.token = token;
1659 reqInfo.info.numOptions = respInfo.info.numOptions;
1660 reqInfo.info.payload = NULL;
1661 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1662 if (reqInfo.info.numOptions)
1664 reqInfo.info.options =
1665 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1666 if (NULL == reqInfo.info.options)
1668 OIC_LOG(ERROR, TAG, "Calloc failed");
1669 return OC_STACK_NO_MEMORY;
1671 memcpy (reqInfo.info.options, respInfo.info.options,
1672 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1675 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1676 OICFree (reqInfo.info.resourceUri);
1677 OICFree (reqInfo.info.options);
1678 OICFree (respInfo.info.resourceUri);
1679 OICFree (respInfo.info.options);
1680 if (CA_STATUS_OK != caResult)
1682 OIC_LOG(ERROR, TAG, "CASendRequest error");
1683 return CAResultToOCResult(caResult);
1689 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1691 // resourceUri in the info field is cloned in the CA layer and
1692 // thus ownership is still here.
1693 OICFree (respInfo.info.resourceUri);
1694 OICFree (respInfo.info.options);
1695 if(CA_STATUS_OK != caResult)
1697 OIC_LOG(ERROR, TAG, "CASendResponse error");
1698 return CAResultToOCResult(caResult);
1701 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1705 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1707 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1708 OCStackResult result = OC_STACK_ERROR;
1709 if(!protocolRequest)
1711 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1712 return OC_STACK_INVALID_PARAM;
1715 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1716 protocolRequest->tokenLength);
1719 OIC_LOG(INFO, TAG, "This is a new Server Request");
1720 result = AddServerRequest(&request, protocolRequest->coapID,
1721 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1722 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1723 protocolRequest->observationOption, protocolRequest->qos,
1724 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1725 protocolRequest->payload, protocolRequest->requestToken,
1726 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1727 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1728 &protocolRequest->devAddr);
1729 if (OC_STACK_OK != result)
1731 OIC_LOG(ERROR, TAG, "Error adding server request");
1737 OIC_LOG(ERROR, TAG, "Out of Memory");
1738 return OC_STACK_NO_MEMORY;
1741 if(!protocolRequest->reqMorePacket)
1743 request->requestComplete = 1;
1748 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1751 if(request->requestComplete)
1753 OIC_LOG(INFO, TAG, "This Server Request is complete");
1754 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1755 OCResource *resource = NULL;
1756 result = DetermineResourceHandling (request, &resHandling, &resource);
1757 if (result == OC_STACK_OK)
1759 result = ProcessRequest(resHandling, resource, request);
1764 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1765 result = OC_STACK_CONTINUE;
1770 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1772 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1774 OCStackResult requestResult = OC_STACK_ERROR;
1776 if(myStackMode == OC_CLIENT)
1778 //TODO: should the client be responding to requests?
1782 OCServerProtocolRequest serverRequest = {0};
1784 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1786 char * uriWithoutQuery = NULL;
1787 char * query = NULL;
1789 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1791 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1793 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1796 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1797 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1799 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1801 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1802 OICFree(uriWithoutQuery);
1806 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1807 OICFree(uriWithoutQuery);
1814 if(strlen(query) < MAX_QUERY_LENGTH)
1816 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1821 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1827 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1829 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1830 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1831 if (!serverRequest.payload)
1833 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1836 memcpy (serverRequest.payload, requestInfo->info.payload,
1837 requestInfo->info.payloadSize);
1841 serverRequest.reqTotalSize = 0;
1844 switch (requestInfo->method)
1847 serverRequest.method = OC_REST_GET;
1850 serverRequest.method = OC_REST_PUT;
1853 serverRequest.method = OC_REST_POST;
1856 serverRequest.method = OC_REST_DELETE;
1859 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1860 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1861 requestInfo->info.type, requestInfo->info.numOptions,
1862 requestInfo->info.options, requestInfo->info.token,
1863 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1865 OICFree(serverRequest.payload);
1869 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1870 requestInfo->info.tokenLength);
1872 serverRequest.tokenLength = requestInfo->info.tokenLength;
1873 if (serverRequest.tokenLength) {
1875 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1877 if (!serverRequest.requestToken)
1879 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1880 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1881 requestInfo->info.type, requestInfo->info.numOptions,
1882 requestInfo->info.options, requestInfo->info.token,
1883 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1885 OICFree(serverRequest.payload);
1888 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1891 switch (requestInfo->info.acceptFormat)
1893 case CA_FORMAT_APPLICATION_CBOR:
1894 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1896 case CA_FORMAT_UNDEFINED:
1897 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1900 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1903 if (requestInfo->info.type == CA_MSG_CONFIRM)
1905 serverRequest.qos = OC_HIGH_QOS;
1909 serverRequest.qos = OC_LOW_QOS;
1911 // CA does not need the following field
1912 // Are we sure CA does not need them? how is it responding to multicast
1913 serverRequest.delayedResNeeded = 0;
1915 serverRequest.coapID = requestInfo->info.messageId;
1917 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1919 // copy vendor specific header options
1920 uint8_t tempNum = (requestInfo->info.numOptions);
1922 // Assume no observation requested and it is a pure GET.
1923 // If obs registration/de-registration requested it'll be fetched from the
1924 // options in GetObserveHeaderOption()
1925 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1927 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1928 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1931 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1932 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1933 requestInfo->info.type, requestInfo->info.numOptions,
1934 requestInfo->info.options, requestInfo->info.token,
1935 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1937 OICFree(serverRequest.payload);
1938 OICFree(serverRequest.requestToken);
1941 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
1942 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
1944 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
1945 sizeof(CAHeaderOption_t)*tempNum);
1948 requestResult = HandleStackRequests (&serverRequest);
1950 // Send ACK to client as precursor to slow response
1951 if (requestResult == OC_STACK_SLOW_RESOURCE)
1953 if (requestInfo->info.type == CA_MSG_CONFIRM)
1955 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
1956 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
1960 if (requestResult == OC_STACK_RESOURCE_ERROR
1961 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
1963 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
1965 else if(!OCResultToSuccess(requestResult))
1967 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
1969 CAResponseResult_t stackResponse =
1970 OCToCAStackResult(requestResult, serverRequest.method);
1972 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
1973 requestInfo->info.type, requestInfo->info.numOptions,
1974 requestInfo->info.options, requestInfo->info.token,
1975 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1978 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
1979 // The token is copied in there, and is thus still owned by this function.
1980 OICFree(serverRequest.payload);
1981 OICFree(serverRequest.requestToken);
1982 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
1985 //This function will be called back by CA layer when a request is received
1986 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1988 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
1991 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1997 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2001 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2002 #ifdef ROUTING_GATEWAY
2003 bool needRIHandling = false;
2004 bool isEmptyMsg = false;
2006 * Routing manager is going to update either of endpoint or request or both.
2007 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2008 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2009 * destination. It can also remove "RM" coap header option before passing request / response to
2010 * RI as this option will make no sense to either RI or application.
2012 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2013 &needRIHandling, &isEmptyMsg);
2014 if(OC_STACK_OK != ret || !needRIHandling)
2016 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2022 * Put source in sender endpoint so that the next packet from application can be routed to
2023 * proper destination and remove RM header option.
2025 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2026 (uint8_t *) &(requestInfo->info.numOptions),
2027 (CAEndpoint_t *) endPoint);
2029 #ifdef ROUTING_GATEWAY
2033 * In Gateways, the MSGType in route option is used to check if the actual
2034 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2035 * EMPTY response is sent in the form of POST request which need to be changed
2036 * to a EMPTY response by RM. This translation is done in this part of the code.
2038 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2039 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2040 .info.messageId = requestInfo->info.messageId,
2041 .info.type = CA_MSG_ACKNOWLEDGE};
2042 OCHandleResponse(endPoint, &respInfo);
2048 // Normal handling of the packet
2049 OCHandleRequests(endPoint, requestInfo);
2051 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2054 bool validatePlatformInfo(OCPlatformInfo info)
2057 if (!info.platformID)
2059 OIC_LOG(ERROR, TAG, "No platform ID found.");
2063 if (info.manufacturerName)
2065 size_t lenManufacturerName = strlen(info.manufacturerName);
2067 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2069 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2075 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2079 if (info.manufacturerUrl)
2081 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2083 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2090 //-----------------------------------------------------------------------------
2092 //-----------------------------------------------------------------------------
2094 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2097 !raInfo->username ||
2098 !raInfo->hostname ||
2099 !raInfo->xmpp_domain)
2102 return OC_STACK_INVALID_PARAM;
2104 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2105 gRASetInfo = (result == OC_STACK_OK)? true : false;
2111 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2115 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2118 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2120 if(stackState == OC_STACK_INITIALIZED)
2122 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2123 OCStop() between them are ignored.");
2127 #ifndef ROUTING_GATEWAY
2128 if (OC_GATEWAY == mode)
2130 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2131 return OC_STACK_INVALID_PARAM;
2138 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2139 return OC_STACK_ERROR;
2143 OCStackResult result = OC_STACK_ERROR;
2144 OIC_LOG(INFO, TAG, "Entering OCInit");
2147 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2148 || (mode == OC_GATEWAY)))
2150 OIC_LOG(ERROR, TAG, "Invalid mode");
2151 return OC_STACK_ERROR;
2155 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2157 caglobals.client = true;
2159 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2161 caglobals.server = true;
2164 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2165 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2167 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2169 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2170 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2172 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2175 defaultDeviceHandler = NULL;
2176 defaultDeviceHandlerCallbackParameter = NULL;
2178 result = InitializeScheduleResourceList();
2179 VERIFY_SUCCESS(result, OC_STACK_OK);
2181 result = CAResultToOCResult(CAInitialize());
2182 VERIFY_SUCCESS(result, OC_STACK_OK);
2184 result = CAResultToOCResult(OCSelectNetwork());
2185 VERIFY_SUCCESS(result, OC_STACK_OK);
2187 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2188 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2189 VERIFY_SUCCESS(result, OC_STACK_OK);
2191 switch (myStackMode)
2194 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2195 result = CAResultToOCResult(CAStartDiscoveryServer());
2196 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2199 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2200 result = CAResultToOCResult(CAStartListeningServer());
2201 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2203 case OC_CLIENT_SERVER:
2205 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2206 result = CAResultToOCResult(CAStartListeningServer());
2207 if(result == OC_STACK_OK)
2209 result = CAResultToOCResult(CAStartDiscoveryServer());
2213 VERIFY_SUCCESS(result, OC_STACK_OK);
2216 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2219 #ifdef WITH_PRESENCE
2220 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2221 #endif // WITH_PRESENCE
2223 //Update Stack state to initialized
2224 stackState = OC_STACK_INITIALIZED;
2226 // Initialize resource
2227 if(myStackMode != OC_CLIENT)
2229 result = initResources();
2232 // Initialize the SRM Policy Engine
2233 if(result == OC_STACK_OK)
2235 result = SRMInitPolicyEngine();
2236 // TODO after BeachHead delivery: consolidate into single SRMInit()
2238 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2239 RMSetStackMode(mode);
2240 #ifdef ROUTING_GATEWAY
2241 if (OC_GATEWAY == myStackMode)
2243 result = RMInitialize();
2249 if (result == OC_STACK_OK)
2251 result = InitializeKeepAlive(myStackMode);
2256 if(result != OC_STACK_OK)
2258 OIC_LOG(ERROR, TAG, "Stack initialization error");
2259 deleteAllResources();
2261 TerminateScheduleResourceList();
2262 stackState = OC_STACK_UNINITIALIZED;
2267 OCStackResult OCStop()
2269 OIC_LOG(INFO, TAG, "Entering OCStop");
2271 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2273 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2276 else if (stackState != OC_STACK_INITIALIZED)
2278 OIC_LOG(ERROR, TAG, "Stack not initialized");
2279 return OC_STACK_ERROR;
2282 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2284 #ifdef WITH_PRESENCE
2285 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2286 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2287 presenceResource.presenceTTL = 0;
2288 #endif // WITH_PRESENCE
2290 #ifdef ROUTING_GATEWAY
2291 if (OC_GATEWAY == myStackMode)
2298 TerminateKeepAlive(myStackMode);
2301 // Free memory dynamically allocated for resources
2302 deleteAllResources();
2304 DeletePlatformInfo();
2306 TerminateScheduleResourceList();
2307 // Remove all observers
2308 DeleteObserverList();
2309 // Remove all the client callbacks
2310 DeleteClientCBList();
2312 // De-init the SRM Policy Engine
2313 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2314 SRMDeInitPolicyEngine();
2317 stackState = OC_STACK_UNINITIALIZED;
2321 OCStackResult OCStartMulticastServer()
2323 if(stackState != OC_STACK_INITIALIZED)
2325 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2326 return OC_STACK_ERROR;
2328 CAResult_t ret = CAStartListeningServer();
2329 if (CA_STATUS_OK != ret)
2331 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2332 return OC_STACK_ERROR;
2337 OCStackResult OCStopMulticastServer()
2339 CAResult_t ret = CAStopListeningServer();
2340 if (CA_STATUS_OK != ret)
2342 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2343 return OC_STACK_ERROR;
2348 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2353 return CA_MSG_CONFIRM;
2358 return CA_MSG_NONCONFIRM;
2363 * A request uri consists of the following components in order:
2366 * CoAP over UDP prefix "coap://"
2367 * CoAP over TCP prefix "coap+tcp://"
2368 * CoAP over DTLS prefix "coaps://"
2369 * CoAP over TLS prefix "coaps+tcp://"
2371 * IPv6 address "[1234::5678]"
2372 * IPv4 address "192.168.1.1"
2373 * optional port ":5683"
2374 * resource uri "/oc/core..."
2376 * for PRESENCE requests, extract resource type.
2378 static OCStackResult ParseRequestUri(const char *fullUri,
2379 OCTransportAdapter adapter,
2380 OCTransportFlags flags,
2381 OCDevAddr **devAddr,
2383 char **resourceType)
2385 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2387 OCStackResult result = OC_STACK_OK;
2388 OCDevAddr *da = NULL;
2392 // provide defaults for all returned values
2399 *resourceUri = NULL;
2403 *resourceType = NULL;
2406 // delimit url prefix, if any
2407 const char *start = fullUri;
2408 char *slash2 = strstr(start, "//");
2413 char *slash = strchr(start, '/');
2416 return OC_STACK_INVALID_URI;
2419 // process url scheme
2420 size_t prefixLen = slash2 - fullUri;
2424 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2425 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2431 // TODO: this logic should come in with unit tests exercising the various strings
2432 // processs url prefix, if any
2433 size_t urlLen = slash - start;
2437 if (urlLen && devAddr)
2438 { // construct OCDevAddr
2439 if (start[0] == '[')
2441 char *close = strchr(++start, ']');
2442 if (!close || close > slash)
2444 return OC_STACK_INVALID_URI;
2447 if (close[1] == ':')
2454 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2458 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2460 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2464 char *dot = strchr(start, '.');
2465 if (dot && dot < slash)
2467 colon = strchr(start, ':');
2468 end = (colon && colon < slash) ? colon : slash;
2473 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2477 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2479 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2487 if (len >= sizeof(da->addr))
2489 return OC_STACK_INVALID_URI;
2491 // collect port, if any
2492 if (colon && colon < slash)
2494 for (colon++; colon < slash; colon++)
2497 if (c < '0' || c > '9')
2499 return OC_STACK_INVALID_URI;
2501 port = 10 * port + c - '0';
2506 if (len >= sizeof(da->addr))
2508 return OC_STACK_INVALID_URI;
2511 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2514 return OC_STACK_NO_MEMORY;
2516 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2518 da->adapter = adapter;
2520 if (!strncmp(fullUri, "coaps", 5))
2522 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2527 // process resource uri, if any
2529 { // request uri and query
2530 size_t ulen = strlen(slash); // resource uri length
2531 size_t tlen = 0; // resource type length
2534 static const char strPresence[] = "/oic/ad?rt=";
2535 static const size_t lenPresence = sizeof(strPresence) - 1;
2536 if (!strncmp(slash, strPresence, lenPresence))
2538 type = slash + lenPresence;
2539 tlen = ulen - lenPresence;
2544 *resourceUri = (char *)OICMalloc(ulen + 1);
2547 result = OC_STACK_NO_MEMORY;
2550 strcpy(*resourceUri, slash);
2553 if (type && resourceType)
2555 *resourceType = (char *)OICMalloc(tlen + 1);
2558 result = OC_STACK_NO_MEMORY;
2562 OICStrcpy(*resourceType, (tlen+1), type);
2569 // free all returned values
2576 OICFree(*resourceUri);
2580 OICFree(*resourceType);
2585 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2589 char uri[CA_MAX_URI_LENGTH];
2591 FormCanonicalPresenceUri(endpoint, uri, isMulticast);
2593 *requestUri = OICStrdup(uri);
2596 return OC_STACK_NO_MEMORY;
2603 * Discover or Perform requests on a specified resource
2605 OCStackResult OCDoResource(OCDoHandle *handle,
2607 const char *requestUri,
2608 const OCDevAddr *destination,
2610 OCConnectivityType connectivityType,
2611 OCQualityOfService qos,
2612 OCCallbackData *cbData,
2613 OCHeaderOption *options,
2616 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2618 // Validate input parameters
2619 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2620 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2622 OCStackResult result = OC_STACK_ERROR;
2623 CAResult_t caResult;
2624 CAToken_t token = NULL;
2625 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2626 ClientCB *clientCB = NULL;
2627 OCDoHandle resHandle = NULL;
2628 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2629 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2631 OCTransportAdapter adapter;
2632 OCTransportFlags flags;
2633 // the request contents are put here
2634 CARequestInfo_t requestInfo = {.method = CA_GET};
2635 // requestUri will be parsed into the following three variables
2636 OCDevAddr *devAddr = NULL;
2637 char *resourceUri = NULL;
2638 char *resourceType = NULL;
2641 * Support original behavior with address on resourceUri argument.
2643 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2644 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2648 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2649 if (result != OC_STACK_OK)
2651 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2655 else if (!checkProxyUri(options, numOptions))
2657 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2664 case OC_REST_OBSERVE:
2665 case OC_REST_OBSERVE_ALL:
2666 requestInfo.method = CA_GET;
2669 requestInfo.method = CA_PUT;
2672 requestInfo.method = CA_POST;
2674 case OC_REST_DELETE:
2675 requestInfo.method = CA_DELETE;
2677 case OC_REST_DISCOVER:
2679 #ifdef WITH_PRESENCE
2680 case OC_REST_PRESENCE:
2682 if (destination || devAddr)
2684 requestInfo.isMulticast = false;
2688 tmpDevAddr.adapter = adapter;
2689 tmpDevAddr.flags = flags;
2690 destination = &tmpDevAddr;
2691 requestInfo.isMulticast = true;
2693 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2694 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2695 // replacing method type with GET.
2696 requestInfo.method = CA_GET;
2699 result = OC_STACK_INVALID_METHOD;
2703 if (!devAddr && !destination)
2705 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2706 result = OC_STACK_INVALID_PARAM;
2710 /* If not original behavior, use destination argument */
2711 if (destination && !devAddr)
2713 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2716 result = OC_STACK_NO_MEMORY;
2719 *devAddr = *destination;
2722 resHandle = GenerateInvocationHandle();
2725 result = OC_STACK_NO_MEMORY;
2729 caResult = CAGenerateToken(&token, tokenLength);
2730 if (caResult != CA_STATUS_OK)
2732 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2733 result= OC_STACK_ERROR;
2737 // fill in request data
2738 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2739 requestInfo.info.token = token;
2740 requestInfo.info.tokenLength = tokenLength;
2742 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2744 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2745 options, numOptions, OC_OBSERVE_REGISTER);
2746 if (result != OC_STACK_OK)
2750 requestInfo.info.numOptions = numOptions + 1;
2754 requestInfo.info.numOptions = numOptions;
2755 requestInfo.info.options =
2756 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2757 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2758 numOptions * sizeof(CAHeaderOption_t));
2761 CopyDevAddrToEndpoint(devAddr, &endpoint);
2766 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2769 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2772 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2776 requestInfo.info.payload = NULL;
2777 requestInfo.info.payloadSize = 0;
2778 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2781 // prepare for response
2782 #ifdef WITH_PRESENCE
2783 if (method == OC_REST_PRESENCE)
2785 char *presenceUri = NULL;
2786 result = OCPreparePresence(&endpoint, &presenceUri,
2787 requestInfo.isMulticast);
2788 if (OC_STACK_OK != result)
2793 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2794 // Presence notification will form a canonical uri to
2795 // look for callbacks into the application.
2798 OICFree(resourceUri);
2800 resourceUri = presenceUri;
2804 // update resourceUri onto requestInfo after check presence uri
2805 requestInfo.info.resourceUri = resourceUri;
2807 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2808 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2809 method, devAddr, resourceUri, resourceType, ttl);
2810 if (OC_STACK_OK != result)
2815 devAddr = NULL; // Client CB list entry now owns it
2816 resourceUri = NULL; // Client CB list entry now owns it
2817 resourceType = NULL; // Client CB list entry now owns it
2819 #ifdef WITH_PRESENCE
2820 if (method == OC_REST_PRESENCE)
2822 if (requestInfo.isMulticast)
2824 OIC_LOG(ERROR, TAG, "AddClientCB for presence done.");
2829 OIC_LOG(ERROR, TAG, "this subscribe presence is unicast.");
2835 result = OCSendRequest(&endpoint, &requestInfo);
2836 if (OC_STACK_OK != result)
2843 *handle = resHandle;
2847 if (result != OC_STACK_OK)
2849 OIC_LOG(ERROR, TAG, "OCDoResource error");
2850 FindAndDeleteClientCB(clientCB);
2851 CADestroyToken(token);
2859 // This is the owner of the payload object, so we free it
2860 OCPayloadDestroy(payload);
2861 OICFree(requestInfo.info.payload);
2863 OICFree(resourceUri);
2864 OICFree(resourceType);
2865 OICFree(requestInfo.info.options);
2869 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2873 * This ftn is implemented one of two ways in the case of observation:
2875 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2876 * Remove the callback associated on client side.
2877 * When the next notification comes in from server,
2878 * reply with RESET message to server.
2879 * Keep in mind that the server will react to RESET only
2880 * if the last notification was sent as CON
2882 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2883 * and it is associated with an observe request
2884 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2885 * Send CON Observe request to server with
2886 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2887 * Remove the callback associated on client side.
2889 OCStackResult ret = OC_STACK_OK;
2890 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2891 CARequestInfo_t requestInfo = {.method = CA_GET};
2895 return OC_STACK_INVALID_PARAM;
2898 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2901 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2902 return OC_STACK_ERROR;
2905 switch (clientCB->method)
2907 case OC_REST_OBSERVE:
2908 case OC_REST_OBSERVE_ALL:
2910 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2912 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2914 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2916 FindAndDeleteClientCB(clientCB);
2920 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2922 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2923 requestInfo.info.token = clientCB->token;
2924 requestInfo.info.tokenLength = clientCB->tokenLength;
2926 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2927 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2929 return OC_STACK_ERROR;
2931 requestInfo.info.numOptions = numOptions + 1;
2932 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2935 ret = OCSendRequest(&endpoint, &requestInfo);
2937 if (requestInfo.info.options)
2939 OICFree (requestInfo.info.options);
2941 if (requestInfo.info.resourceUri)
2943 OICFree (requestInfo.info.resourceUri);
2948 case OC_REST_DISCOVER:
2949 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2950 clientCB->requestUri);
2951 FindAndDeleteClientCB(clientCB);
2954 #ifdef WITH_PRESENCE
2955 case OC_REST_PRESENCE:
2956 FindAndDeleteClientCB(clientCB);
2961 ret = OC_STACK_INVALID_METHOD;
2969 * @brief Register Persistent storage callback.
2970 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
2972 * OC_STACK_OK - No errors; Success
2973 * OC_STACK_INVALID_PARAM - Invalid parameter
2975 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
2977 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
2978 if(!persistentStorageHandler)
2980 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2981 return OC_STACK_INVALID_PARAM;
2985 if( !persistentStorageHandler->open ||
2986 !persistentStorageHandler->close ||
2987 !persistentStorageHandler->read ||
2988 !persistentStorageHandler->unlink ||
2989 !persistentStorageHandler->write)
2991 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
2992 return OC_STACK_INVALID_PARAM;
2995 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
2998 #ifdef WITH_PRESENCE
3000 OCStackResult OCProcessPresence()
3002 OCStackResult result = OC_STACK_OK;
3004 // the following line floods the log with messages that are irrelevant
3005 // to most purposes. Uncomment as needed.
3006 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3007 ClientCB* cbNode = NULL;
3008 OCClientResponse clientResponse;
3009 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3011 LL_FOREACH(cbList, cbNode)
3013 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3018 uint32_t now = GetTicks(0);
3019 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3020 cbNode->presence->TTLlevel);
3021 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3023 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3028 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3030 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3031 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3033 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3035 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3037 clientResponse.sequenceNumber = 0;
3038 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3039 clientResponse.devAddr = *cbNode->devAddr;
3040 FixUpClientResponse(&clientResponse);
3041 clientResponse.payload = NULL;
3043 // Increment the TTLLevel (going to a next state), so we don't keep
3044 // sending presence notification to client.
3045 cbNode->presence->TTLlevel++;
3046 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3047 cbNode->presence->TTLlevel);
3049 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3050 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3052 FindAndDeleteClientCB(cbNode);
3056 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3061 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3062 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3063 CARequestInfo_t requestInfo = {.method = CA_GET};
3065 OIC_LOG(DEBUG, TAG, "time to test server presence");
3067 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3069 requestData.type = CA_MSG_NONCONFIRM;
3070 requestData.token = cbNode->token;
3071 requestData.tokenLength = cbNode->tokenLength;
3072 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3073 requestInfo.method = CA_GET;
3074 requestInfo.info = requestData;
3076 result = OCSendRequest(&endpoint, &requestInfo);
3077 if (OC_STACK_OK != result)
3082 cbNode->presence->TTLlevel++;
3083 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3086 if (result != OC_STACK_OK)
3088 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3093 #endif // WITH_PRESENCE
3095 OCStackResult OCProcess()
3097 #ifdef WITH_PRESENCE
3098 OCProcessPresence();
3100 CAHandleRequestResponse();
3102 #ifdef ROUTING_GATEWAY
3112 #ifdef WITH_PRESENCE
3113 OCStackResult OCStartPresence(const uint32_t ttl)
3115 OIC_LOG(INFO, TAG, "Entering OCStartPresence");
3116 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3117 OCChangeResourceProperty(
3118 &(((OCResource *)presenceResource.handle)->resourceProperties),
3121 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3123 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3124 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3128 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3129 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3133 presenceResource.presenceTTL = ttl;
3135 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3137 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3139 presenceState = OC_PRESENCE_INITIALIZED;
3141 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3143 CAToken_t caToken = NULL;
3144 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3145 if (caResult != CA_STATUS_OK)
3147 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3148 CADestroyToken(caToken);
3149 return OC_STACK_ERROR;
3152 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3153 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3154 CADestroyToken(caToken);
3157 // Each time OCStartPresence is called
3158 // a different random 32-bit integer number is used
3159 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3161 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3162 OC_PRESENCE_TRIGGER_CREATE);
3165 OCStackResult OCStopPresence()
3167 OIC_LOG(INFO, TAG, "Entering OCStopPresence");
3168 OCStackResult result = OC_STACK_ERROR;
3170 if(presenceResource.handle)
3172 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3174 // make resource inactive
3175 result = OCChangeResourceProperty(
3176 &(((OCResource *) presenceResource.handle)->resourceProperties),
3180 if(result != OC_STACK_OK)
3183 "Changing the presence resource properties to ACTIVE not successful");
3187 return SendStopNotification();
3191 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3192 void* callbackParameter)
3194 defaultDeviceHandler = entityHandler;
3195 defaultDeviceHandlerCallbackParameter = callbackParameter;
3200 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3202 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3204 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3206 if (validatePlatformInfo(platformInfo))
3208 return SavePlatformInfo(platformInfo);
3212 return OC_STACK_INVALID_PARAM;
3217 return OC_STACK_ERROR;
3221 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3223 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3225 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3227 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3228 return OC_STACK_INVALID_PARAM;
3231 if (deviceInfo.types)
3233 OCStringLL *type = deviceInfo.types;
3234 OCResource *resource = findResource((OCResource *) deviceResource);
3237 return OC_STACK_INVALID_PARAM;
3242 OCBindResourceTypeToResource(deviceResource, type->value);
3246 return SaveDeviceInfo(deviceInfo);
3249 OCStackResult OCCreateResource(OCResourceHandle *handle,
3250 const char *resourceTypeName,
3251 const char *resourceInterfaceName,
3252 const char *uri, OCEntityHandler entityHandler,
3253 void* callbackParam,
3254 uint8_t resourceProperties)
3257 OCResource *pointer = NULL;
3258 OCStackResult result = OC_STACK_ERROR;
3260 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3262 if(myStackMode == OC_CLIENT)
3264 return OC_STACK_INVALID_PARAM;
3266 // Validate parameters
3267 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3269 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3270 return OC_STACK_INVALID_URI;
3272 // Is it presented during resource discovery?
3273 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3275 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3276 return OC_STACK_INVALID_PARAM;
3279 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3281 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3285 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3287 // Make sure resourceProperties bitmask has allowed properties specified
3288 if (resourceProperties
3289 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3290 OC_EXPLICIT_DISCOVERABLE
3299 OIC_LOG(ERROR, TAG, "Invalid property");
3300 return OC_STACK_INVALID_PARAM;
3303 // If the headResource is NULL, then no resources have been created...
3304 pointer = headResource;
3307 // At least one resources is in the resource list, so we need to search for
3308 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3311 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3313 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3314 return OC_STACK_INVALID_PARAM;
3316 pointer = pointer->next;
3319 // Create the pointer and insert it into the resource list
3320 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3323 result = OC_STACK_NO_MEMORY;
3326 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3328 insertResource(pointer);
3331 pointer->uri = OICStrdup(uri);
3334 result = OC_STACK_NO_MEMORY;
3338 // Set properties. Set OC_ACTIVE
3339 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3342 // Add the resourcetype to the resource
3343 result = BindResourceTypeToResource(pointer, resourceTypeName);
3344 if (result != OC_STACK_OK)
3346 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3350 // Add the resourceinterface to the resource
3351 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3352 if (result != OC_STACK_OK)
3354 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3358 // If an entity handler has been passed, attach it to the newly created
3359 // resource. Otherwise, set the default entity handler.
3362 pointer->entityHandler = entityHandler;
3363 pointer->entityHandlerCallbackParam = callbackParam;
3367 pointer->entityHandler = defaultResourceEHandler;
3368 pointer->entityHandlerCallbackParam = NULL;
3371 // Initialize a pointer indicating child resources in case of collection
3372 pointer->rsrcChildResourcesHead = NULL;
3375 result = OC_STACK_OK;
3377 #ifdef WITH_PRESENCE
3378 if (presenceResource.handle)
3380 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3381 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3385 if (result != OC_STACK_OK)
3387 // Deep delete of resource and other dynamic elements that it contains
3388 deleteResource(pointer);
3393 OCStackResult OCBindResource(
3394 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3396 OCResource *resource = NULL;
3397 OCChildResource *tempChildResource = NULL;
3398 OCChildResource *newChildResource = NULL;
3400 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3402 // Validate parameters
3403 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3404 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3405 // Container cannot contain itself
3406 if (collectionHandle == resourceHandle)
3408 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3409 return OC_STACK_INVALID_PARAM;
3412 // Use the handle to find the resource in the resource linked list
3413 resource = findResource((OCResource *) collectionHandle);
3416 OIC_LOG(ERROR, TAG, "Collection handle not found");
3417 return OC_STACK_INVALID_PARAM;
3420 // Look for an open slot to add add the child resource.
3421 // If found, add it and return success
3423 tempChildResource = resource->rsrcChildResourcesHead;
3425 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3427 // TODO: what if one of child resource was deregistered without unbinding?
3428 tempChildResource = tempChildResource->next;
3431 // Do memory allocation for child resource
3432 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3433 if(!newChildResource)
3435 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3436 return OC_STACK_ERROR;
3439 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3440 newChildResource->next = NULL;
3442 if(!resource->rsrcChildResourcesHead)
3444 resource->rsrcChildResourcesHead = newChildResource;
3447 tempChildResource->next = newChildResource;
3450 OIC_LOG(INFO, TAG, "resource bound");
3452 #ifdef WITH_PRESENCE
3453 if (presenceResource.handle)
3455 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3456 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3457 OC_PRESENCE_TRIGGER_CHANGE);
3464 OCStackResult OCUnBindResource(
3465 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3467 OCResource *resource = NULL;
3468 OCChildResource *tempChildResource = NULL;
3469 OCChildResource *tempLastChildResource = NULL;
3471 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3473 // Validate parameters
3474 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3475 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3476 // Container cannot contain itself
3477 if (collectionHandle == resourceHandle)
3479 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3480 return OC_STACK_INVALID_PARAM;
3483 // Use the handle to find the resource in the resource linked list
3484 resource = findResource((OCResource *) collectionHandle);
3487 OIC_LOG(ERROR, TAG, "Collection handle not found");
3488 return OC_STACK_INVALID_PARAM;
3491 // Look for an open slot to add add the child resource.
3492 // If found, add it and return success
3493 if(!resource->rsrcChildResourcesHead)
3495 OIC_LOG(INFO, TAG, "resource not found in collection");
3497 // Unable to add resourceHandle, so return error
3498 return OC_STACK_ERROR;
3502 tempChildResource = resource->rsrcChildResourcesHead;
3504 while (tempChildResource)
3506 if(tempChildResource->rsrcResource == resourceHandle)
3508 // if resource going to be unbinded is the head one.
3509 if( tempChildResource == resource->rsrcChildResourcesHead )
3511 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3512 OICFree(resource->rsrcChildResourcesHead);
3513 resource->rsrcChildResourcesHead = temp;
3518 OCChildResource *temp = tempChildResource->next;
3519 OICFree(tempChildResource);
3520 tempLastChildResource->next = temp;
3524 OIC_LOG(INFO, TAG, "resource unbound");
3526 // Send notification when resource is unbounded successfully.
3527 #ifdef WITH_PRESENCE
3528 if (presenceResource.handle)
3530 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3531 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3532 OC_PRESENCE_TRIGGER_CHANGE);
3535 tempChildResource = NULL;
3536 tempLastChildResource = NULL;
3542 tempLastChildResource = tempChildResource;
3543 tempChildResource = tempChildResource->next;
3546 OIC_LOG(INFO, TAG, "resource not found in collection");
3548 tempChildResource = NULL;
3549 tempLastChildResource = NULL;
3551 // Unable to add resourceHandle, so return error
3552 return OC_STACK_ERROR;
3555 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3557 if (!resourceItemName)
3561 // Per RFC 6690 only registered values must follow the first rule below.
3562 // At this point in time the only values registered begin with "core", and
3563 // all other values are specified as opaque strings where multiple values
3564 // are separated by a space.
3565 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3567 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3569 if (resourceItemName[index] != '.'
3570 && resourceItemName[index] != '-'
3571 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3572 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3580 for (size_t index = 0; resourceItemName[index]; ++index)
3582 if (resourceItemName[index] == ' '
3583 || resourceItemName[index] == '\t'
3584 || resourceItemName[index] == '\r'
3585 || resourceItemName[index] == '\n')
3595 OCStackResult BindResourceTypeToResource(OCResource* resource,
3596 const char *resourceTypeName)
3598 OCResourceType *pointer = NULL;
3600 OCStackResult result = OC_STACK_ERROR;
3602 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3604 if (!ValidateResourceTypeInterface(resourceTypeName))
3606 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3607 return OC_STACK_INVALID_PARAM;
3610 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3613 result = OC_STACK_NO_MEMORY;
3617 str = OICStrdup(resourceTypeName);
3620 result = OC_STACK_NO_MEMORY;
3623 pointer->resourcetypename = str;
3624 pointer->next = NULL;
3626 insertResourceType(resource, pointer);
3627 result = OC_STACK_OK;
3630 if (result != OC_STACK_OK)
3639 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3640 const char *resourceInterfaceName)
3642 OCResourceInterface *pointer = NULL;
3644 OCStackResult result = OC_STACK_ERROR;
3646 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3648 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3650 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3651 return OC_STACK_INVALID_PARAM;
3654 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3656 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3659 result = OC_STACK_NO_MEMORY;
3663 str = OICStrdup(resourceInterfaceName);
3666 result = OC_STACK_NO_MEMORY;
3669 pointer->name = str;
3671 // Bind the resourceinterface to the resource
3672 insertResourceInterface(resource, pointer);
3674 result = OC_STACK_OK;
3677 if (result != OC_STACK_OK)
3686 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3687 const char *resourceTypeName)
3690 OCStackResult result = OC_STACK_ERROR;
3691 OCResource *resource = NULL;
3693 resource = findResource((OCResource *) handle);
3696 OIC_LOG(ERROR, TAG, "Resource not found");
3697 return OC_STACK_ERROR;
3700 result = BindResourceTypeToResource(resource, resourceTypeName);
3702 #ifdef WITH_PRESENCE
3703 if(presenceResource.handle)
3705 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3706 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3713 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3714 const char *resourceInterfaceName)
3717 OCStackResult result = OC_STACK_ERROR;
3718 OCResource *resource = NULL;
3720 resource = findResource((OCResource *) handle);
3723 OIC_LOG(ERROR, TAG, "Resource not found");
3724 return OC_STACK_ERROR;
3727 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3729 #ifdef WITH_PRESENCE
3730 if (presenceResource.handle)
3732 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3733 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3740 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3742 OCResource *pointer = headResource;
3744 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3748 *numResources = *numResources + 1;
3749 pointer = pointer->next;
3754 OCResourceHandle OCGetResourceHandle(uint8_t index)
3756 OCResource *pointer = headResource;
3758 for( uint8_t i = 0; i < index && pointer; ++i)
3760 pointer = pointer->next;
3762 return (OCResourceHandle) pointer;
3765 OCStackResult OCDeleteResource(OCResourceHandle handle)
3769 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3770 return OC_STACK_INVALID_PARAM;
3773 OCResource *resource = findResource((OCResource *) handle);
3774 if (resource == NULL)
3776 OIC_LOG(ERROR, TAG, "Resource not found");
3777 return OC_STACK_NO_RESOURCE;
3780 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3782 OIC_LOG(ERROR, TAG, "Error deleting resource");
3783 return OC_STACK_ERROR;
3789 const char *OCGetResourceUri(OCResourceHandle handle)
3791 OCResource *resource = NULL;
3793 resource = findResource((OCResource *) handle);
3796 return resource->uri;
3798 return (const char *) NULL;
3801 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3803 OCResource *resource = NULL;
3805 resource = findResource((OCResource *) handle);
3808 return resource->resourceProperties;
3810 return (OCResourceProperty)-1;
3813 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3814 uint8_t *numResourceTypes)
3816 OCResource *resource = NULL;
3817 OCResourceType *pointer = NULL;
3819 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3820 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3822 *numResourceTypes = 0;
3824 resource = findResource((OCResource *) handle);
3827 pointer = resource->rsrcType;
3830 *numResourceTypes = *numResourceTypes + 1;
3831 pointer = pointer->next;
3837 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3839 OCResourceType *resourceType = NULL;
3841 resourceType = findResourceTypeAtIndex(handle, index);
3844 return resourceType->resourcetypename;
3846 return (const char *) NULL;
3849 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3850 uint8_t *numResourceInterfaces)
3852 OCResourceInterface *pointer = NULL;
3853 OCResource *resource = NULL;
3855 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3856 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3858 *numResourceInterfaces = 0;
3859 resource = findResource((OCResource *) handle);
3862 pointer = resource->rsrcInterface;
3865 *numResourceInterfaces = *numResourceInterfaces + 1;
3866 pointer = pointer->next;
3872 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3874 OCResourceInterface *resourceInterface = NULL;
3876 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3877 if (resourceInterface)
3879 return resourceInterface->name;
3881 return (const char *) NULL;
3884 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3887 OCResource *resource = NULL;
3888 OCChildResource *tempChildResource = NULL;
3891 resource = findResource((OCResource *) collectionHandle);
3897 tempChildResource = resource->rsrcChildResourcesHead;
3899 while(tempChildResource)
3903 return tempChildResource->rsrcResource;
3906 tempChildResource = tempChildResource->next;
3909 // In this case, the number of resource handles in the collection exceeds the index
3910 tempChildResource = NULL;
3914 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3915 OCEntityHandler entityHandler,
3916 void* callbackParam)
3918 OCResource *resource = NULL;
3920 // Validate parameters
3921 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3923 // Use the handle to find the resource in the resource linked list
3924 resource = findResource((OCResource *)handle);
3927 OIC_LOG(ERROR, TAG, "Resource not found");
3928 return OC_STACK_ERROR;
3932 resource->entityHandler = entityHandler;
3933 resource->entityHandlerCallbackParam = callbackParam;
3935 #ifdef WITH_PRESENCE
3936 if (presenceResource.handle)
3938 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3939 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3946 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3948 OCResource *resource = NULL;
3950 resource = findResource((OCResource *)handle);
3953 OIC_LOG(ERROR, TAG, "Resource not found");
3958 return resource->entityHandler;
3961 void incrementSequenceNumber(OCResource * resPtr)
3963 // Increment the sequence number
3964 resPtr->sequenceNum += 1;
3965 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
3967 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
3972 #ifdef WITH_PRESENCE
3973 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
3974 OCPresenceTrigger trigger)
3976 OIC_LOG(INFO, TAG, "SendPresenceNotification");
3977 OCResource *resPtr = NULL;
3978 OCStackResult result = OC_STACK_ERROR;
3979 OCMethod method = OC_REST_PRESENCE;
3980 uint32_t maxAge = 0;
3981 resPtr = findResource((OCResource *) presenceResource.handle);
3984 return OC_STACK_NO_RESOURCE;
3987 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
3989 maxAge = presenceResource.presenceTTL;
3991 result = SendAllObserverNotification(method, resPtr, maxAge,
3992 trigger, resourceType, OC_LOW_QOS);
3998 OCStackResult SendStopNotification()
4000 OIC_LOG(INFO, TAG, "SendStopNotification");
4001 OCResource *resPtr = NULL;
4002 OCStackResult result = OC_STACK_ERROR;
4003 OCMethod method = OC_REST_PRESENCE;
4004 resPtr = findResource((OCResource *) presenceResource.handle);
4007 return OC_STACK_NO_RESOURCE;
4010 // maxAge is 0. ResourceType is NULL.
4011 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4017 #endif // WITH_PRESENCE
4018 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4020 OCResource *resPtr = NULL;
4021 OCStackResult result = OC_STACK_ERROR;
4022 OCMethod method = OC_REST_NOMETHOD;
4023 uint32_t maxAge = 0;
4025 OIC_LOG(INFO, TAG, "Notifying all observers");
4026 #ifdef WITH_PRESENCE
4027 if(handle == presenceResource.handle)
4031 #endif // WITH_PRESENCE
4032 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4034 // Verify that the resource exists
4035 resPtr = findResource ((OCResource *) handle);
4038 return OC_STACK_NO_RESOURCE;
4042 //only increment in the case of regular observing (not presence)
4043 incrementSequenceNumber(resPtr);
4044 method = OC_REST_OBSERVE;
4045 maxAge = MAX_OBSERVE_AGE;
4046 #ifdef WITH_PRESENCE
4047 result = SendAllObserverNotification (method, resPtr, maxAge,
4048 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4050 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4057 OCNotifyListOfObservers (OCResourceHandle handle,
4058 OCObservationId *obsIdList,
4059 uint8_t numberOfIds,
4060 const OCRepPayload *payload,
4061 OCQualityOfService qos)
4063 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4065 OCResource *resPtr = NULL;
4066 //TODO: we should allow the server to define this
4067 uint32_t maxAge = MAX_OBSERVE_AGE;
4069 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4070 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4071 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4073 resPtr = findResource ((OCResource *) handle);
4074 if (NULL == resPtr || myStackMode == OC_CLIENT)
4076 return OC_STACK_NO_RESOURCE;
4080 incrementSequenceNumber(resPtr);
4082 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4083 payload, maxAge, qos));
4086 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4088 OCStackResult result = OC_STACK_ERROR;
4089 OCServerRequest *serverRequest = NULL;
4091 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4093 // Validate input parameters
4094 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4095 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4098 // Get pointer to request info
4099 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4102 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4103 result = serverRequest->ehResponseHandler(ehResponse);
4109 //#ifdef DIRECT_PAIRING
4110 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4112 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4113 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4115 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4119 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4122 const OCDPDev_t* OCGetDirectPairedDevices()
4124 return (const OCDPDev_t*)DPGetPairedDevices();
4127 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4128 OCDirectPairingCB resultCallback)
4130 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4131 if(NULL == peer || NULL == pinNumber)
4133 OIC_LOG(ERROR, TAG, "Invalid parameters");
4134 return OC_STACK_INVALID_PARAM;
4136 if (NULL == resultCallback)
4138 OIC_LOG(ERROR, TAG, "Invalid callback");
4139 return OC_STACK_INVALID_CALLBACK;
4142 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4143 pinNumber, (OCDirectPairingResultCB)resultCallback);
4145 //#endif // DIRECT_PAIRING
4147 //-----------------------------------------------------------------------------
4148 // Private internal function definitions
4149 //-----------------------------------------------------------------------------
4150 static OCDoHandle GenerateInvocationHandle()
4152 OCDoHandle handle = NULL;
4153 // Generate token here, it will be deleted when the transaction is deleted
4154 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4157 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4163 #ifdef WITH_PRESENCE
4164 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4165 OCResourceProperty resourceProperties, uint8_t enable)
4169 return OC_STACK_INVALID_PARAM;
4171 if (resourceProperties
4172 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4174 OIC_LOG(ERROR, TAG, "Invalid property");
4175 return OC_STACK_INVALID_PARAM;
4179 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4183 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4189 OCStackResult initResources()
4191 OCStackResult result = OC_STACK_OK;
4193 headResource = NULL;
4194 tailResource = NULL;
4195 // Init Virtual Resources
4196 #ifdef WITH_PRESENCE
4197 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4199 result = OCCreateResource(&presenceResource.handle,
4200 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4202 OC_RSRVD_PRESENCE_URI,
4206 //make resource inactive
4207 result = OCChangeResourceProperty(
4208 &(((OCResource *) presenceResource.handle)->resourceProperties),
4211 #ifndef WITH_ARDUINO
4212 if (result == OC_STACK_OK)
4214 result = SRMInitSecureResources();
4218 if(result == OC_STACK_OK)
4220 CreateResetProfile();
4221 result = OCCreateResource(&deviceResource,
4222 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4223 OC_RSRVD_INTERFACE_DEFAULT,
4224 OC_RSRVD_DEVICE_URI,
4228 if(result == OC_STACK_OK)
4230 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4231 OC_RSRVD_INTERFACE_READ);
4235 if(result == OC_STACK_OK)
4237 result = OCCreateResource(&platformResource,
4238 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4239 OC_RSRVD_INTERFACE_DEFAULT,
4240 OC_RSRVD_PLATFORM_URI,
4244 if(result == OC_STACK_OK)
4246 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4247 OC_RSRVD_INTERFACE_READ);
4254 void insertResource(OCResource *resource)
4258 headResource = resource;
4259 tailResource = resource;
4263 tailResource->next = resource;
4264 tailResource = resource;
4266 resource->next = NULL;
4269 OCResource *findResource(OCResource *resource)
4271 OCResource *pointer = headResource;
4275 if (pointer == resource)
4279 pointer = pointer->next;
4284 void deleteAllResources()
4286 OCResource *pointer = headResource;
4287 OCResource *temp = NULL;
4291 temp = pointer->next;
4292 #ifdef WITH_PRESENCE
4293 if (pointer != (OCResource *) presenceResource.handle)
4295 #endif // WITH_PRESENCE
4296 deleteResource(pointer);
4297 #ifdef WITH_PRESENCE
4299 #endif // WITH_PRESENCE
4302 memset(&platformResource, 0, sizeof(platformResource));
4303 memset(&deviceResource, 0, sizeof(deviceResource));
4305 memset(&brokerResource, 0, sizeof(brokerResource));
4308 SRMDeInitSecureResources();
4310 #ifdef WITH_PRESENCE
4311 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4312 // presence notification attributed to their deletion to be processed.
4313 deleteResource((OCResource *) presenceResource.handle);
4314 memset(&presenceResource, 0, sizeof(presenceResource));
4315 #endif // WITH_PRESENCE
4318 OCStackResult deleteResource(OCResource *resource)
4320 OCResource *prev = NULL;
4321 OCResource *temp = NULL;
4324 OIC_LOG(DEBUG,TAG,"resource is NULL");
4325 return OC_STACK_INVALID_PARAM;
4328 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4330 temp = headResource;
4333 if (temp == resource)
4335 // Invalidate all Resource Properties.
4336 resource->resourceProperties = (OCResourceProperty) 0;
4337 #ifdef WITH_PRESENCE
4338 if(resource != (OCResource *) presenceResource.handle)
4340 #endif // WITH_PRESENCE
4341 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4342 #ifdef WITH_PRESENCE
4345 if(presenceResource.handle)
4347 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4348 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4351 // Only resource in list.
4352 if (temp == headResource && temp == tailResource)
4354 headResource = NULL;
4355 tailResource = NULL;
4358 else if (temp == headResource)
4360 headResource = temp->next;
4363 else if (temp == tailResource)
4365 tailResource = prev;
4366 tailResource->next = NULL;
4370 prev->next = temp->next;
4373 deleteResourceElements(temp);
4384 return OC_STACK_ERROR;
4387 void deleteResourceElements(OCResource *resource)
4394 OICFree(resource->uri);
4395 deleteResourceType(resource->rsrcType);
4396 deleteResourceInterface(resource->rsrcInterface);
4399 void deleteResourceType(OCResourceType *resourceType)
4401 OCResourceType *pointer = resourceType;
4402 OCResourceType *next = NULL;
4406 next = pointer->next;
4407 OICFree(pointer->resourcetypename);
4413 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4415 OCResourceInterface *pointer = resourceInterface;
4416 OCResourceInterface *next = NULL;
4420 next = pointer->next;
4421 OICFree(pointer->name);
4427 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4429 OCResourceType *pointer = NULL;
4430 OCResourceType *previous = NULL;
4431 if (!resource || !resourceType)
4435 // resource type list is empty.
4436 else if (!resource->rsrcType)
4438 resource->rsrcType = resourceType;
4442 pointer = resource->rsrcType;
4446 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4448 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4449 OICFree(resourceType->resourcetypename);
4450 OICFree(resourceType);
4454 pointer = pointer->next;
4459 previous->next = resourceType;
4462 resourceType->next = NULL;
4464 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4467 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4469 OCResource *resource = NULL;
4470 OCResourceType *pointer = NULL;
4472 // Find the specified resource
4473 resource = findResource((OCResource *) handle);
4479 // Make sure a resource has a resourcetype
4480 if (!resource->rsrcType)
4485 // Iterate through the list
4486 pointer = resource->rsrcType;
4487 for(uint8_t i = 0; i< index && pointer; ++i)
4489 pointer = pointer->next;
4494 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4496 if(resourceTypeList && resourceTypeName)
4498 OCResourceType * rtPointer = resourceTypeList;
4499 while(resourceTypeName && rtPointer)
4501 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4502 if(rtPointer->resourcetypename &&
4503 strcmp(resourceTypeName, (const char *)
4504 (rtPointer->resourcetypename)) == 0)
4508 rtPointer = rtPointer->next;
4516 * Insert a new interface into interface linked list only if not already present.
4517 * If alredy present, 2nd arg is free'd.
4518 * Default interface will always be first if present.
4520 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4522 OCResourceInterface *pointer = NULL;
4523 OCResourceInterface *previous = NULL;
4525 newInterface->next = NULL;
4527 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4529 if (!*firstInterface)
4531 // If first interface is not oic.if.baseline, by default add it as first interface type.
4532 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4534 *firstInterface = newInterface;
4538 OCStackResult result = BindResourceInterfaceToResource(resource,
4539 OC_RSRVD_INTERFACE_DEFAULT);
4540 if (result != OC_STACK_OK)
4542 OICFree(newInterface->name);
4543 OICFree(newInterface);
4546 if (*firstInterface)
4548 (*firstInterface)->next = newInterface;
4552 // If once add oic.if.baseline, later too below code take care of freeing memory.
4553 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4555 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4557 OICFree(newInterface->name);
4558 OICFree(newInterface);
4561 // This code will not hit anymore, keeping
4564 newInterface->next = *firstInterface;
4565 *firstInterface = newInterface;
4570 pointer = *firstInterface;
4573 if (strcmp(newInterface->name, pointer->name) == 0)
4575 OICFree(newInterface->name);
4576 OICFree(newInterface);
4580 pointer = pointer->next;
4585 previous->next = newInterface;
4590 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4593 OCResource *resource = NULL;
4594 OCResourceInterface *pointer = NULL;
4596 // Find the specified resource
4597 resource = findResource((OCResource *) handle);
4603 // Make sure a resource has a resourceinterface
4604 if (!resource->rsrcInterface)
4609 // Iterate through the list
4610 pointer = resource->rsrcInterface;
4612 for (uint8_t i = 0; i < index && pointer; ++i)
4614 pointer = pointer->next;
4620 * This function splits the uri using the '?' delimiter.
4621 * "uriWithoutQuery" is the block of characters between the beginning
4622 * till the delimiter or '\0' which ever comes first.
4623 * "query" is whatever is to the right of the delimiter if present.
4624 * No delimiter sets the query to NULL.
4625 * If either are present, they will be malloc'ed into the params 2, 3.
4626 * The first param, *uri is left untouched.
4628 * NOTE: This function does not account for whitespace at the end of the uri NOR
4629 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4630 * part of the query.
4632 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4636 return OC_STACK_INVALID_URI;
4638 if(!query || !uriWithoutQuery)
4640 return OC_STACK_INVALID_PARAM;
4644 *uriWithoutQuery = NULL;
4646 size_t uriWithoutQueryLen = 0;
4647 size_t queryLen = 0;
4648 size_t uriLen = strlen(uri);
4650 char *pointerToDelimiter = strstr(uri, "?");
4652 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4653 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4655 if (uriWithoutQueryLen)
4657 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4658 if (!*uriWithoutQuery)
4662 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4666 *query = (char *) OICCalloc(queryLen + 1, 1);
4669 OICFree(*uriWithoutQuery);
4670 *uriWithoutQuery = NULL;
4673 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4679 return OC_STACK_NO_MEMORY;
4682 static const OicUuid_t* OCGetServerInstanceID(void)
4684 static bool generated = false;
4685 static OicUuid_t sid;
4691 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4693 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4700 const char* OCGetServerInstanceIDString(void)
4702 static bool generated = false;
4703 static char sidStr[UUID_STRING_SIZE];
4710 const OicUuid_t *sid = OCGetServerInstanceID();
4711 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4713 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4721 CAResult_t OCSelectNetwork()
4723 CAResult_t retResult = CA_STATUS_FAILED;
4724 CAResult_t caResult = CA_STATUS_OK;
4726 CATransportAdapter_t connTypes[] = {
4728 CA_ADAPTER_RFCOMM_BTEDR,
4729 CA_ADAPTER_GATT_BTLE,
4732 ,CA_ADAPTER_REMOTE_ACCESS
4739 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4741 for(int i = 0; i < numConnTypes; i++)
4743 // If CA status is not initialized, CASelectNetwork() will not be called.
4744 if (caResult != CA_STATUS_NOT_INITIALIZED)
4746 caResult = CASelectNetwork(connTypes[i]);
4747 if (caResult == CA_STATUS_OK)
4749 retResult = CA_STATUS_OK;
4754 if (retResult != CA_STATUS_OK)
4756 return caResult; // Returns error of appropriate transport that failed fatally.
4762 OCStackResult CAResultToOCResult(CAResult_t caResult)
4768 case CA_STATUS_INVALID_PARAM:
4769 return OC_STACK_INVALID_PARAM;
4770 case CA_ADAPTER_NOT_ENABLED:
4771 return OC_STACK_ADAPTER_NOT_ENABLED;
4772 case CA_SERVER_STARTED_ALREADY:
4774 case CA_SERVER_NOT_STARTED:
4775 return OC_STACK_ERROR;
4776 case CA_DESTINATION_NOT_REACHABLE:
4777 return OC_STACK_COMM_ERROR;
4778 case CA_SOCKET_OPERATION_FAILED:
4779 return OC_STACK_COMM_ERROR;
4780 case CA_SEND_FAILED:
4781 return OC_STACK_COMM_ERROR;
4782 case CA_RECEIVE_FAILED:
4783 return OC_STACK_COMM_ERROR;
4784 case CA_MEMORY_ALLOC_FAILED:
4785 return OC_STACK_NO_MEMORY;
4786 case CA_REQUEST_TIMEOUT:
4787 return OC_STACK_TIMEOUT;
4788 case CA_DESTINATION_DISCONNECTED:
4789 return OC_STACK_COMM_ERROR;
4790 case CA_STATUS_FAILED:
4791 return OC_STACK_ERROR;
4792 case CA_NOT_SUPPORTED:
4793 return OC_STACK_NOTIMPL;
4795 return OC_STACK_ERROR;
4799 bool OCResultToSuccess(OCStackResult ocResult)
4804 case OC_STACK_RESOURCE_CREATED:
4805 case OC_STACK_RESOURCE_DELETED:
4806 case OC_STACK_CONTINUE:
4807 case OC_STACK_RESOURCE_CHANGED:
4808 case OC_STACK_SLOW_RESOURCE:
4816 OCStackResult OCSetProxyURI(const char *uri)
4818 return CAResultToOCResult(CASetProxyUri(uri));
4822 #if defined(RD_CLIENT) || defined(RD_SERVER)
4823 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4825 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4827 OCResource *resource = NULL;
4829 resource = findResource((OCResource *) handle);
4832 OIC_LOG(ERROR, TAG, "Resource not found");
4833 return OC_STACK_ERROR;
4836 resource->ins = ins;
4841 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4845 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4849 OCResource *pointer = headResource;
4853 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4855 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4858 pointer = pointer->next;
4863 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4865 OCResource *resource = NULL;
4867 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4868 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4870 resource = findResource((OCResource *) handle);
4873 *ins = resource->ins;
4876 return OC_STACK_ERROR;
4879 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4880 void* optionData, size_t optionDataLength)
4884 OIC_LOG (INFO, TAG, "Header options are NULL");
4885 return OC_STACK_INVALID_PARAM;
4890 OIC_LOG (INFO, TAG, "optionData are NULL");
4891 return OC_STACK_INVALID_PARAM;
4896 OIC_LOG (INFO, TAG, "numOptions is NULL");
4897 return OC_STACK_INVALID_PARAM;
4900 if (*numOptions >= MAX_HEADER_OPTIONS)
4902 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4903 return OC_STACK_NO_MEMORY;
4906 ocHdrOpt += *numOptions;
4907 ocHdrOpt->protocolID = OC_COAP_ID;
4908 ocHdrOpt->optionID = optionID;
4909 ocHdrOpt->optionLength =
4910 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4911 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4912 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4917 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
4918 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
4920 if (!ocHdrOpt || !numOptions)
4922 OIC_LOG (INFO, TAG, "No options present");
4928 OIC_LOG (INFO, TAG, "optionData are NULL");
4929 return OC_STACK_INVALID_PARAM;
4932 if (!receivedDataLength)
4934 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
4935 return OC_STACK_INVALID_PARAM;
4938 for (uint8_t i = 0; i < numOptions; i++)
4940 if (ocHdrOpt[i].optionID == optionID)
4942 if (optionDataLength >= ocHdrOpt->optionLength)
4944 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
4945 *receivedDataLength = ocHdrOpt->optionLength;
4950 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
4951 return OC_STACK_ERROR;
4959 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
4961 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
4962 if (g_adapterHandler)
4964 g_adapterHandler(adapter, enabled);
4968 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
4970 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
4971 if (g_connectionHandler)
4973 g_connectionHandler(info, isConnected);
4977 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
4978 CAConnectionStateChangedCB connectionHandler)
4980 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
4981 g_adapterHandler = adapterHandler;
4982 g_connectionHandler = connectionHandler;
4985 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
4990 ret = GetDoxmDeviceID(&oicUuid);
4991 if (OC_STACK_OK == ret)
4993 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
4997 OIC_LOG(ERROR, TAG, "Device ID Get error");
5002 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5006 OIC_LOG(ERROR, TAG, "Set deviceId DOXM");
5008 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5009 for(int i=0;i < UUID_LENGTH; i++)
5011 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5013 ret = SetDoxmDeviceID(&oicUuid);