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 OCStackResult to CAResponseResult_t.
327 * @param caCode OCStackResult code.
328 * @param method OCMethod method the return code replies to.
329 * @return ::CA_CONTENT on OK, some other value upon failure.
331 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
334 * Convert OCTransportFlags_t to CATransportModifiers_t.
336 * @param ocConType OCTransportFlags_t input.
337 * @return CATransportFlags
339 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
342 * Convert CATransportFlags_t to OCTransportModifiers_t.
344 * @param caConType CATransportFlags_t input.
345 * @return OCTransportFlags
347 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
350 * Handle response from presence request.
352 * @param endPoint CA remote endpoint.
353 * @param responseInfo CA response info.
354 * @return ::OC_STACK_OK on success, some other value upon failure.
356 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
357 const CAResponseInfo_t *responseInfo);
360 * This function will be called back by CA layer when a response is received.
362 * @param endPoint CA remote endpoint.
363 * @param responseInfo CA response info.
365 static void HandleCAResponses(const CAEndpoint_t* endPoint,
366 const CAResponseInfo_t* responseInfo);
369 * This function will be called back by CA layer when a request is received.
371 * @param endPoint CA remote endpoint.
372 * @param requestInfo CA request info.
374 static void HandleCARequests(const CAEndpoint_t* endPoint,
375 const CARequestInfo_t* requestInfo);
378 * Extract query from a URI.
380 * @param uri Full URI with query.
381 * @param query Pointer to string that will contain query.
382 * @param newURI Pointer to string that will contain URI.
383 * @return ::OC_STACK_OK on success, some other value upon failure.
385 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
388 * Finds a resource type in an OCResourceType link-list.
390 * @param resourceTypeList The link-list to be searched through.
391 * @param resourceTypeName The key to search for.
393 * @return Resource type that matches the key (ie. resourceTypeName) or
394 * NULL if there is either an invalid parameter or this function was unable to find the key.
396 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
397 const char * resourceTypeName);
400 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
401 * TTL will be set to maxAge.
403 * @param cbNode Callback Node for which presence ttl is to be reset.
404 * @param maxAge New value of ttl in seconds.
406 * @return ::OC_STACK_OK on success, some other value upon failure.
408 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
411 * Ensure the accept header option is set appropriatly before sending the requests and routing
412 * header option is updated with destination.
414 * @param object CA remote endpoint.
415 * @param requestInfo CA request info.
417 * @return ::OC_STACK_OK on success, some other value upon failure.
419 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
422 * default adapter state change callback method
424 * @param adapter CA network adapter type.
425 * @param enabled current adapter state.
427 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
430 * default connection state change callback method
432 * @param info CAEndpoint which has address, port and etc.
433 * @param isConnected current connection state.
435 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
438 * Register network monitoring callback.
439 * Network status changes are delivered these callback.
440 * @param adapterHandler Adapter state monitoring callback.
441 * @param connectionHandler Connection state monitoring callback.
443 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
444 CAConnectionStateChangedCB connectionHandler);
446 //-----------------------------------------------------------------------------
447 // Internal functions
448 //-----------------------------------------------------------------------------
450 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
452 if (!options || 0 == numOptions)
454 OIC_LOG (INFO, TAG, "No options present");
458 for (uint8_t i = 0; i < numOptions; i++)
460 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
462 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
469 uint32_t GetTicks(uint32_t afterMilliSeconds)
474 // Guard against overflow of uint32_t
475 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
476 COAP_TICKS_PER_SECOND)
478 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
486 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
488 VERIFY_NON_NULL_NR(in, FATAL);
489 VERIFY_NON_NULL_NR(out, FATAL);
491 out->adapter = (OCTransportAdapter)in->adapter;
492 out->flags = CAToOCTransportFlags(in->flags);
493 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
494 out->port = in->port;
495 out->ifindex = in->ifindex;
496 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
497 /* This assert is to prevent accidental mismatch between address size macros defined in
498 * RI and CA and cause crash here. */
499 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
500 "Address size mismatch between RI and CA");
501 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
505 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
507 VERIFY_NON_NULL_NR(in, FATAL);
508 VERIFY_NON_NULL_NR(out, FATAL);
510 out->adapter = (CATransportAdapter_t)in->adapter;
511 out->flags = OCToCATransportFlags(in->flags);
512 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
513 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
514 /* This assert is to prevent accidental mismatch between address size macros defined in
515 * RI and CA and cause crash here. */
516 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
517 "Address size mismatch between RI and CA");
518 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
520 out->port = in->port;
521 out->ifindex = in->ifindex;
524 void FixUpClientResponse(OCClientResponse *cr)
526 VERIFY_NON_NULL_NR(cr, FATAL);
528 cr->addr = &cr->devAddr;
529 cr->connType = (OCConnectivityType)
530 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
533 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
535 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
536 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
538 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
539 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
540 if (OC_STACK_OK != rmResult)
542 OIC_LOG(ERROR, TAG, "Add destination option failed");
547 // OC stack prefer CBOR encoded payloads.
548 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
549 CAResult_t result = CASendRequest(object, requestInfo);
550 if(CA_STATUS_OK != result)
552 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
553 return CAResultToOCResult(result);
557 //-----------------------------------------------------------------------------
558 // Internal API function
559 //-----------------------------------------------------------------------------
561 // This internal function is called to update the stack with the status of
562 // observers and communication failures
563 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
565 OCStackResult result = OC_STACK_ERROR;
566 ResourceObserver * observer = NULL;
567 OCEntityHandlerRequest ehRequest = {0};
571 case OC_OBSERVER_NOT_INTERESTED:
572 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
573 observer = GetObserverUsingToken (token, tokenLength);
576 result = FormOCEntityHandlerRequest(&ehRequest,
577 (OCRequestHandle)NULL,
580 (OCResourceHandle)NULL,
581 NULL, PAYLOAD_TYPE_REPRESENTATION,
583 OC_OBSERVE_DEREGISTER,
586 if(result != OC_STACK_OK)
590 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
591 observer->resource->entityHandlerCallbackParam);
594 result = DeleteObserverUsingToken (token, tokenLength);
595 if(result == OC_STACK_OK)
597 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
601 result = OC_STACK_OK;
602 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
606 case OC_OBSERVER_STILL_INTERESTED:
607 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
608 observer = GetObserverUsingToken (token, tokenLength);
611 observer->forceHighQos = 0;
612 observer->failedCommCount = 0;
613 result = OC_STACK_OK;
617 result = OC_STACK_OBSERVER_NOT_FOUND;
621 case OC_OBSERVER_FAILED_COMM:
622 OIC_LOG(DEBUG, TAG, "observer is unreachable");
623 observer = GetObserverUsingToken (token, tokenLength);
626 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
628 result = FormOCEntityHandlerRequest(&ehRequest,
629 (OCRequestHandle)NULL,
632 (OCResourceHandle)NULL,
633 NULL, PAYLOAD_TYPE_REPRESENTATION,
635 OC_OBSERVE_DEREGISTER,
638 if(result != OC_STACK_OK)
640 return OC_STACK_ERROR;
642 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
643 observer->resource->entityHandlerCallbackParam);
645 result = DeleteObserverUsingToken (token, tokenLength);
646 if(result == OC_STACK_OK)
648 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
652 result = OC_STACK_OK;
653 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
658 observer->failedCommCount++;
659 result = OC_STACK_CONTINUE;
661 observer->forceHighQos = 1;
662 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
666 OIC_LOG(ERROR, TAG, "Unknown status");
667 result = OC_STACK_ERROR;
673 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
675 OCStackResult ret = OC_STACK_ERROR;
679 case CA_ADAPTER_NOT_ENABLED:
680 case CA_SERVER_NOT_STARTED:
681 ret = OC_STACK_ADAPTER_NOT_ENABLED;
683 case CA_MEMORY_ALLOC_FAILED:
684 ret = OC_STACK_NO_MEMORY;
686 case CA_STATUS_INVALID_PARAM:
687 ret = OC_STACK_INVALID_PARAM;
695 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
697 OCStackResult ret = OC_STACK_ERROR;
701 ret = OC_STACK_RESOURCE_CREATED;
704 ret = OC_STACK_RESOURCE_DELETED;
707 ret = OC_STACK_RESOURCE_CHANGED;
714 ret = OC_STACK_INVALID_QUERY;
716 case CA_UNAUTHORIZED_REQ:
717 ret = OC_STACK_UNAUTHORIZED_REQ;
720 ret = OC_STACK_INVALID_OPTION;
723 ret = OC_STACK_NO_RESOURCE;
725 case CA_RETRANSMIT_TIMEOUT:
726 ret = OC_STACK_COMM_ERROR;
728 case CA_REQUEST_ENTITY_TOO_LARGE:
729 ret = OC_STACK_TOO_LARGE_REQ;
737 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
739 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
748 // This Response Code is like HTTP 204 "No Content" but only used in
749 // response to POST and PUT requests.
753 // This Response Code is like HTTP 200 "OK" but only used in response to
758 // This should not happen but,
759 // give it a value just in case but output an error
761 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
765 case OC_STACK_RESOURCE_CREATED:
768 case OC_STACK_RESOURCE_DELETED:
771 case OC_STACK_RESOURCE_CHANGED:
774 case OC_STACK_INVALID_QUERY:
777 case OC_STACK_INVALID_OPTION:
780 case OC_STACK_NO_RESOURCE:
783 case OC_STACK_COMM_ERROR:
784 ret = CA_RETRANSMIT_TIMEOUT;
786 case OC_STACK_UNAUTHORIZED_REQ:
787 ret = CA_UNAUTHORIZED_REQ;
795 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
797 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
799 // supply default behavior.
800 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
802 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
804 if ((caFlags & OC_MASK_SCOPE) == 0)
806 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
811 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
813 return (OCTransportFlags)caFlags;
816 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
818 uint32_t lowerBound = 0;
819 uint32_t higherBound = 0;
821 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
823 return OC_STACK_INVALID_PARAM;
826 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
828 cbNode->presence->TTL = maxAgeSeconds;
830 for (int index = 0; index < PresenceTimeOutSize; index++)
832 // Guard against overflow
833 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
836 lowerBound = GetTicks((PresenceTimeOut[index] *
837 cbNode->presence->TTL *
838 MILLISECONDS_PER_SECOND)/100);
842 lowerBound = GetTicks(UINT32_MAX);
845 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
848 higherBound = GetTicks((PresenceTimeOut[index + 1] *
849 cbNode->presence->TTL *
850 MILLISECONDS_PER_SECOND)/100);
854 higherBound = GetTicks(UINT32_MAX);
857 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
859 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
860 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
861 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
864 cbNode->presence->TTLlevel = 0;
866 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
870 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
872 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
874 return OC_RSRVD_TRIGGER_CREATE;
876 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
878 return OC_RSRVD_TRIGGER_CHANGE;
882 return OC_RSRVD_TRIGGER_DELETE;
886 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
890 return OC_PRESENCE_TRIGGER_CREATE;
892 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
894 return OC_PRESENCE_TRIGGER_CREATE;
896 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
898 return OC_PRESENCE_TRIGGER_CHANGE;
902 return OC_PRESENCE_TRIGGER_DELETE;
907 * Encode an address string to match RFC 6874.
909 * @param outputAddress a char array to be written with the encoded string.
911 * @param outputSize size of outputAddress buffer.
913 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
914 * containing a valid IPv6 address string.
916 * @return OC_STACK_OK if encoding succeeded.
917 * Else an error occured.
919 OCStackResult encodeAddressForRFC6874(char *outputAddress,
921 const char *inputAddress)
923 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
924 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
926 size_t inputLength = strnlen(inputAddress, outputSize);
928 // inputSize includes the null terminator
929 size_t inputSize = inputLength + 1;
931 if (inputSize > outputSize)
933 OIC_LOG_V(ERROR, TAG,
934 "encodeAddressForRFC6874 failed: "
935 "outputSize (%zu) < inputSize (%zu)",
936 outputSize, inputSize);
938 return OC_STACK_ERROR;
941 char* percentChar = strchr(inputAddress, '%');
943 // If there is no '%' character, then no change is required to the string.
944 if (NULL == percentChar)
946 OICStrcpy(outputAddress, outputSize, inputAddress);
950 const char* addressPart = &inputAddress[0];
951 const char* scopeIdPart = percentChar + 1;
953 // Sanity check to make sure this string doesn't have more '%' characters
954 if (NULL != strchr(scopeIdPart, '%'))
956 return OC_STACK_ERROR;
959 // If no string follows the first '%', then the input was invalid.
960 if (scopeIdPart[0] == '\0')
962 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
963 return OC_STACK_ERROR;
966 // Check to see if the string is already encoded
967 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
969 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
970 return OC_STACK_ERROR;
973 // Fail if we don't have room for encoded string's two additional chars
974 if (outputSize < (inputSize + 2))
976 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
977 return OC_STACK_ERROR;
980 // Restore the null terminator with an escaped '%' character, per RFC 6874
981 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
982 strcat(outputAddress, "%25");
983 strcat(outputAddress, scopeIdPart);
989 * The cononical presence allows constructed URIs to be string compared.
991 * requestUri must be a char array of size CA_MAX_URI_LENGTH
993 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
994 char *presenceUri, bool isMulticast)
996 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
997 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
998 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1002 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1003 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1006 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1007 if (ep->adapter == CA_ADAPTER_IP)
1009 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1011 if ('\0' == ep->addr[0]) // multicast
1013 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1017 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1019 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
1020 sizeof(addressEncoded),
1023 if (OC_STACK_OK != result)
1028 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1029 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1034 if ('\0' == ep->addr[0]) // multicast
1036 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1037 ep->port = OC_MULTICAST_PORT;
1039 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1040 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1044 // might work for other adapters (untested, but better than nothing)
1045 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1046 OC_RSRVD_PRESENCE_URI);
1050 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1051 const CAResponseInfo_t *responseInfo)
1053 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1054 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1056 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1057 ClientCB * cbNode = NULL;
1058 char *resourceTypeName = NULL;
1059 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1060 OCStackResult result = OC_STACK_ERROR;
1061 uint32_t maxAge = 0;
1063 char presenceUri[CA_MAX_URI_LENGTH];
1065 int presenceSubscribe = 0;
1066 int multicastPresenceSubscribe = 0;
1068 if (responseInfo->result != CA_CONTENT)
1070 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1071 return OC_STACK_ERROR;
1074 response.payload = NULL;
1075 response.result = OC_STACK_OK;
1077 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1078 FixUpClientResponse(&response);
1080 if (responseInfo->info.payload)
1082 result = OCParsePayload(&response.payload,
1083 PAYLOAD_TYPE_PRESENCE,
1084 responseInfo->info.payload,
1085 responseInfo->info.payloadSize);
1087 if(result != OC_STACK_OK)
1089 OIC_LOG(ERROR, TAG, "Presence parse failed");
1092 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1094 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1095 result = OC_STACK_ERROR;
1098 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1099 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1100 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1103 // check for unicast presence
1104 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri,
1105 responseInfo->isMulticast);
1106 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1108 return OC_STACK_INVALID_URI;
1110 OIC_LOG(ERROR, TAG, "check for unicast presence");
1111 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1114 presenceSubscribe = 1;
1118 // check for multicast presence
1119 OIC_LOG(ERROR, TAG, "check for multicast presence");
1120 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1123 multicastPresenceSubscribe = 1;
1127 if (!presenceSubscribe && !multicastPresenceSubscribe)
1129 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1133 if (presenceSubscribe)
1135 if(cbNode->sequenceNumber == response.sequenceNumber)
1137 OIC_LOG(INFO, TAG, "No presence change");
1138 ResetPresenceTTL(cbNode, maxAge);
1139 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1145 OIC_LOG(INFO, TAG, "Stopping presence");
1146 response.result = OC_STACK_PRESENCE_STOPPED;
1147 if(cbNode->presence)
1149 OICFree(cbNode->presence->timeOut);
1150 OICFree(cbNode->presence);
1151 cbNode->presence = NULL;
1156 if(!cbNode->presence)
1158 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1160 if(!(cbNode->presence))
1162 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1163 result = OC_STACK_NO_MEMORY;
1167 VERIFY_NON_NULL_V(cbNode->presence);
1168 cbNode->presence->timeOut = NULL;
1169 cbNode->presence->timeOut = (uint32_t *)
1170 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1171 if(!(cbNode->presence->timeOut)){
1173 "Could not allocate memory for cbNode->presence->timeOut");
1174 OICFree(cbNode->presence);
1175 result = OC_STACK_NO_MEMORY;
1180 ResetPresenceTTL(cbNode, maxAge);
1182 cbNode->sequenceNumber = response.sequenceNumber;
1184 // Ensure that a filter is actually applied.
1185 if( resourceTypeName && cbNode->filterResourceType)
1187 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1196 // This is the multicast case
1197 OCMulticastNode* mcNode = NULL;
1198 mcNode = GetMCPresenceNode(presenceUri);
1202 if(mcNode->nonce == response.sequenceNumber)
1204 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1207 mcNode->nonce = response.sequenceNumber;
1211 OIC_LOG(INFO, TAG, "Stopping presence");
1212 response.result = OC_STACK_PRESENCE_STOPPED;
1217 char* uri = OICStrdup(presenceUri);
1221 "No Memory for URI to store in the presence node");
1222 result = OC_STACK_NO_MEMORY;
1226 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1227 if(result == OC_STACK_NO_MEMORY)
1230 "No Memory for Multicast Presence Node");
1234 // presence node now owns uri
1239 // Ensure that a filter is actually applied.
1240 if(resourceTypeName && cbNode->filterResourceType)
1242 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1243 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1249 OIC_LOG(INFO, TAG, "Callback for presence");
1251 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1253 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1255 FindAndDeleteClientCB(cbNode);
1259 OCPayloadDestroy(response.payload);
1263 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1265 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1267 if(responseInfo->info.resourceUri &&
1268 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1270 HandlePresenceResponse(endPoint, responseInfo);
1274 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1275 responseInfo->info.tokenLength, NULL, NULL);
1277 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1278 responseInfo->info.tokenLength);
1282 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1283 if(responseInfo->result == CA_EMPTY)
1285 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1286 // We do not have a case for the client to receive a RESET
1287 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1289 //This is the case of receiving an ACK on a request to a slow resource!
1290 OIC_LOG(INFO, TAG, "This is a pure ACK");
1291 //TODO: should we inform the client
1292 // app that at least the request was received at the server?
1295 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1297 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1298 OIC_LOG(INFO, TAG, "Calling into application address space");
1300 OCClientResponse response =
1301 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1302 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1303 FixUpClientResponse(&response);
1304 response.resourceUri = responseInfo->info.resourceUri;
1305 memcpy(response.identity.id, responseInfo->info.identity.id,
1306 sizeof (response.identity.id));
1307 response.identity.id_length = responseInfo->info.identity.id_length;
1309 response.result = CAResponseToOCStackResult(responseInfo->result);
1310 cbNode->callBack(cbNode->context,
1311 cbNode->handle, &response);
1312 FindAndDeleteClientCB(cbNode);
1316 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1317 OIC_LOG(INFO, TAG, "Calling into application address space");
1319 OCClientResponse response =
1320 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1321 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1322 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1323 FixUpClientResponse(&response);
1324 response.resourceUri = responseInfo->info.resourceUri;
1325 memcpy(response.identity.id, responseInfo->info.identity.id,
1326 sizeof (response.identity.id));
1327 response.identity.id_length = responseInfo->info.identity.id_length;
1329 response.result = CAResponseToOCStackResult(responseInfo->result);
1331 if(responseInfo->info.payload &&
1332 responseInfo->info.payloadSize)
1334 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1335 // check the security resource
1336 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1338 type = PAYLOAD_TYPE_SECURITY;
1340 else if (cbNode->method == OC_REST_DISCOVER)
1342 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1343 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1345 type = PAYLOAD_TYPE_DISCOVERY;
1348 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1350 type = PAYLOAD_TYPE_DISCOVERY;
1353 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1355 type = PAYLOAD_TYPE_DEVICE;
1357 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1359 type = PAYLOAD_TYPE_PLATFORM;
1361 #ifdef ROUTING_GATEWAY
1362 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1364 type = PAYLOAD_TYPE_REPRESENTATION;
1367 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1369 type = PAYLOAD_TYPE_REPRESENTATION ;
1372 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1374 type = PAYLOAD_TYPE_REPRESENTATION;
1379 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1380 cbNode->method, cbNode->requestUri);
1384 else if (cbNode->method == OC_REST_GET ||
1385 cbNode->method == OC_REST_PUT ||
1386 cbNode->method == OC_REST_POST ||
1387 cbNode->method == OC_REST_OBSERVE ||
1388 cbNode->method == OC_REST_OBSERVE_ALL ||
1389 cbNode->method == OC_REST_DELETE)
1391 if (cbNode->requestUri)
1393 if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1395 type = PAYLOAD_TYPE_PLATFORM;
1397 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1399 type = PAYLOAD_TYPE_DEVICE;
1401 if (type == PAYLOAD_TYPE_INVALID)
1403 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1404 cbNode->method, cbNode->requestUri);
1405 type = PAYLOAD_TYPE_REPRESENTATION;
1410 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1411 type = PAYLOAD_TYPE_REPRESENTATION;
1416 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1417 cbNode->method, cbNode->requestUri);
1421 if(OC_STACK_OK != OCParsePayload(&response.payload,
1423 responseInfo->info.payload,
1424 responseInfo->info.payloadSize))
1426 OIC_LOG(ERROR, TAG, "Error converting payload");
1427 OCPayloadDestroy(response.payload);
1432 response.numRcvdVendorSpecificHeaderOptions = 0;
1433 if(responseInfo->info.numOptions > 0)
1436 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1437 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1440 uint32_t observationOption;
1441 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1442 for (observationOption=0, i=0;
1443 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1447 (observationOption << 8) | optionData[i];
1449 response.sequenceNumber = observationOption;
1450 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1455 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1458 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1460 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1461 OCPayloadDestroy(response.payload);
1465 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1467 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1468 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1472 if (cbNode->method == OC_REST_OBSERVE &&
1473 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1474 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1475 response.sequenceNumber <= cbNode->sequenceNumber)
1477 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1478 response.sequenceNumber);
1482 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1485 cbNode->sequenceNumber = response.sequenceNumber;
1487 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1489 FindAndDeleteClientCB(cbNode);
1493 // To keep discovery callbacks active.
1494 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1495 MILLISECONDS_PER_SECOND);
1499 //Need to send ACK when the response is CON
1500 if(responseInfo->info.type == CA_MSG_CONFIRM)
1502 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1503 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1506 OCPayloadDestroy(response.payload);
1513 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1514 if(responseInfo->result == CA_EMPTY)
1516 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1517 if(responseInfo->info.type == CA_MSG_RESET)
1519 OIC_LOG(INFO, TAG, "This is a RESET");
1520 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1521 OC_OBSERVER_NOT_INTERESTED);
1523 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1525 OIC_LOG(INFO, TAG, "This is a pure ACK");
1526 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1527 OC_OBSERVER_STILL_INTERESTED);
1530 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1532 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1533 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1534 OC_OBSERVER_FAILED_COMM);
1539 if(!cbNode && !observer)
1541 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1542 || myStackMode == OC_GATEWAY)
1544 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1545 if(responseInfo->result == CA_EMPTY)
1547 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1551 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1552 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1553 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1557 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1558 || myStackMode == OC_GATEWAY)
1560 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1561 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1563 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1564 responseInfo->info.messageId);
1566 if (responseInfo->info.type == CA_MSG_RESET)
1568 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1569 responseInfo->info.messageId);
1577 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1579 VERIFY_NON_NULL_NR(endPoint, FATAL);
1580 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1582 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1584 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1585 #ifdef ROUTING_GATEWAY
1586 bool needRIHandling = false;
1588 * Routing manager is going to update either of endpoint or response or both.
1589 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1590 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1593 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1595 if(ret != OC_STACK_OK || !needRIHandling)
1597 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1603 * Put source in sender endpoint so that the next packet from application can be routed to
1604 * proper destination and remove "RM" coap header option before passing request / response to
1605 * RI as this option will make no sense to either RI or application.
1607 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1608 (uint8_t *) &(responseInfo->info.numOptions),
1609 (CAEndpoint_t *) endPoint);
1612 OCHandleResponse(endPoint, responseInfo);
1614 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1618 * This function handles error response from CA
1619 * code shall be added to handle the errors
1621 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1623 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1625 if (NULL == endPoint)
1627 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1631 if (NULL == errorInfo)
1633 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1637 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1638 errorInfo->info.tokenLength, NULL, NULL);
1641 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1642 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1643 FixUpClientResponse(&response);
1644 response.resourceUri = errorInfo->info.resourceUri;
1645 memcpy(response.identity.id, errorInfo->info.identity.id,
1646 sizeof (response.identity.id));
1647 response.identity.id_length = errorInfo->info.identity.id_length;
1648 response.result = CAResultToOCStackResult(errorInfo->result);
1650 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1653 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1657 * This function sends out Direct Stack Responses. These are responses that are not coming
1658 * from the application entity handler. These responses have no payload and are usually ACKs,
1659 * RESETs or some error conditions that were caught by the stack.
1661 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1662 const CAResponseResult_t responseResult, const CAMessageType_t type,
1663 const uint8_t numOptions, const CAHeaderOption_t *options,
1664 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1665 CADataType_t dataType)
1667 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1668 CAResponseInfo_t respInfo = {
1669 .result = responseResult
1671 respInfo.info.messageId = coapID;
1672 respInfo.info.numOptions = numOptions;
1674 if (respInfo.info.numOptions)
1676 respInfo.info.options =
1677 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1678 memcpy (respInfo.info.options, options,
1679 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1683 respInfo.info.payload = NULL;
1684 respInfo.info.token = token;
1685 respInfo.info.tokenLength = tokenLength;
1686 respInfo.info.type = type;
1687 respInfo.info.resourceUri = OICStrdup (resourceUri);
1688 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1689 respInfo.info.dataType = dataType;
1691 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1692 // Add the destination to route option from the endpoint->routeData.
1693 bool doPost = false;
1694 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1695 if(OC_STACK_OK != result)
1697 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1702 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1703 CARequestInfo_t reqInfo = {.method = CA_POST };
1704 /* The following initialization is not done in a single initializer block as in
1705 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1706 * does not have designated initalizers. This is a work-around for now.
1708 reqInfo.info.type = CA_MSG_NONCONFIRM;
1709 reqInfo.info.messageId = coapID;
1710 reqInfo.info.tokenLength = tokenLength;
1711 reqInfo.info.token = token;
1712 reqInfo.info.numOptions = respInfo.info.numOptions;
1713 reqInfo.info.payload = NULL;
1714 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1715 if (reqInfo.info.numOptions)
1717 reqInfo.info.options =
1718 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1719 if (NULL == reqInfo.info.options)
1721 OIC_LOG(ERROR, TAG, "Calloc failed");
1722 return OC_STACK_NO_MEMORY;
1724 memcpy (reqInfo.info.options, respInfo.info.options,
1725 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1728 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1729 OICFree (reqInfo.info.resourceUri);
1730 OICFree (reqInfo.info.options);
1731 OICFree (respInfo.info.resourceUri);
1732 OICFree (respInfo.info.options);
1733 if (CA_STATUS_OK != caResult)
1735 OIC_LOG(ERROR, TAG, "CASendRequest error");
1736 return CAResultToOCResult(caResult);
1742 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1744 // resourceUri in the info field is cloned in the CA layer and
1745 // thus ownership is still here.
1746 OICFree (respInfo.info.resourceUri);
1747 OICFree (respInfo.info.options);
1748 if(CA_STATUS_OK != caResult)
1750 OIC_LOG(ERROR, TAG, "CASendResponse error");
1751 return CAResultToOCResult(caResult);
1754 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1758 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1760 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1761 OCStackResult result = OC_STACK_ERROR;
1762 if(!protocolRequest)
1764 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1765 return OC_STACK_INVALID_PARAM;
1768 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1769 protocolRequest->tokenLength);
1772 OIC_LOG(INFO, TAG, "This is a new Server Request");
1773 result = AddServerRequest(&request, protocolRequest->coapID,
1774 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1775 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1776 protocolRequest->observationOption, protocolRequest->qos,
1777 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1778 protocolRequest->payload, protocolRequest->requestToken,
1779 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1780 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1781 &protocolRequest->devAddr);
1782 if (OC_STACK_OK != result)
1784 OIC_LOG(ERROR, TAG, "Error adding server request");
1790 OIC_LOG(ERROR, TAG, "Out of Memory");
1791 return OC_STACK_NO_MEMORY;
1794 if(!protocolRequest->reqMorePacket)
1796 request->requestComplete = 1;
1801 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1804 if(request->requestComplete)
1806 OIC_LOG(INFO, TAG, "This Server Request is complete");
1807 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1808 OCResource *resource = NULL;
1809 result = DetermineResourceHandling (request, &resHandling, &resource);
1810 if (result == OC_STACK_OK)
1812 result = ProcessRequest(resHandling, resource, request);
1817 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1818 result = OC_STACK_CONTINUE;
1823 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1825 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1828 if (requestInfo->info.resourceUri &&
1829 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1831 HandleKeepAliveRequest(endPoint, requestInfo);
1836 OCStackResult requestResult = OC_STACK_ERROR;
1838 if(myStackMode == OC_CLIENT)
1840 //TODO: should the client be responding to requests?
1844 OCServerProtocolRequest serverRequest = {0};
1846 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1848 char * uriWithoutQuery = NULL;
1849 char * query = NULL;
1851 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1853 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1855 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1858 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1859 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1861 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1863 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1864 OICFree(uriWithoutQuery);
1868 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1869 OICFree(uriWithoutQuery);
1876 if(strlen(query) < MAX_QUERY_LENGTH)
1878 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1883 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1889 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1891 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1892 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1893 if (!serverRequest.payload)
1895 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1898 memcpy (serverRequest.payload, requestInfo->info.payload,
1899 requestInfo->info.payloadSize);
1903 serverRequest.reqTotalSize = 0;
1906 switch (requestInfo->method)
1909 serverRequest.method = OC_REST_GET;
1912 serverRequest.method = OC_REST_PUT;
1915 serverRequest.method = OC_REST_POST;
1918 serverRequest.method = OC_REST_DELETE;
1921 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1922 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1923 requestInfo->info.type, requestInfo->info.numOptions,
1924 requestInfo->info.options, requestInfo->info.token,
1925 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1927 OICFree(serverRequest.payload);
1931 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1932 requestInfo->info.tokenLength);
1934 serverRequest.tokenLength = requestInfo->info.tokenLength;
1935 if (serverRequest.tokenLength) {
1937 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1939 if (!serverRequest.requestToken)
1941 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1942 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1943 requestInfo->info.type, requestInfo->info.numOptions,
1944 requestInfo->info.options, requestInfo->info.token,
1945 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1947 OICFree(serverRequest.payload);
1950 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1953 switch (requestInfo->info.acceptFormat)
1955 case CA_FORMAT_APPLICATION_CBOR:
1956 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1958 case CA_FORMAT_UNDEFINED:
1959 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1962 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1965 if (requestInfo->info.type == CA_MSG_CONFIRM)
1967 serverRequest.qos = OC_HIGH_QOS;
1971 serverRequest.qos = OC_LOW_QOS;
1973 // CA does not need the following field
1974 // Are we sure CA does not need them? how is it responding to multicast
1975 serverRequest.delayedResNeeded = 0;
1977 serverRequest.coapID = requestInfo->info.messageId;
1979 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1981 // copy vendor specific header options
1982 uint8_t tempNum = (requestInfo->info.numOptions);
1984 // Assume no observation requested and it is a pure GET.
1985 // If obs registration/de-registration requested it'll be fetched from the
1986 // options in GetObserveHeaderOption()
1987 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1989 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1990 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1993 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
1994 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
1995 requestInfo->info.type, requestInfo->info.numOptions,
1996 requestInfo->info.options, requestInfo->info.token,
1997 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1999 OICFree(serverRequest.payload);
2000 OICFree(serverRequest.requestToken);
2003 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2004 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
2006 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2007 sizeof(CAHeaderOption_t)*tempNum);
2010 requestResult = HandleStackRequests (&serverRequest);
2012 // Send ACK to client as precursor to slow response
2013 if (requestResult == OC_STACK_SLOW_RESOURCE)
2015 if (requestInfo->info.type == CA_MSG_CONFIRM)
2017 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2018 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2022 if (requestResult == OC_STACK_RESOURCE_ERROR
2023 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2025 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2027 else if(!OCResultToSuccess(requestResult))
2029 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2031 CAResponseResult_t stackResponse =
2032 OCToCAStackResult(requestResult, serverRequest.method);
2034 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2035 requestInfo->info.type, requestInfo->info.numOptions,
2036 requestInfo->info.options, requestInfo->info.token,
2037 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2040 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2041 // The token is copied in there, and is thus still owned by this function.
2042 OICFree(serverRequest.payload);
2043 OICFree(serverRequest.requestToken);
2044 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2047 //This function will be called back by CA layer when a request is received
2048 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2050 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2053 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2059 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2063 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2064 #ifdef ROUTING_GATEWAY
2065 bool needRIHandling = false;
2066 bool isEmptyMsg = false;
2068 * Routing manager is going to update either of endpoint or request or both.
2069 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2070 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2071 * destination. It can also remove "RM" coap header option before passing request / response to
2072 * RI as this option will make no sense to either RI or application.
2074 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2075 &needRIHandling, &isEmptyMsg);
2076 if(OC_STACK_OK != ret || !needRIHandling)
2078 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2084 * Put source in sender endpoint so that the next packet from application can be routed to
2085 * proper destination and remove RM header option.
2087 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2088 (uint8_t *) &(requestInfo->info.numOptions),
2089 (CAEndpoint_t *) endPoint);
2091 #ifdef ROUTING_GATEWAY
2095 * In Gateways, the MSGType in route option is used to check if the actual
2096 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2097 * EMPTY response is sent in the form of POST request which need to be changed
2098 * to a EMPTY response by RM. This translation is done in this part of the code.
2100 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2101 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2102 .info.messageId = requestInfo->info.messageId,
2103 .info.type = CA_MSG_ACKNOWLEDGE};
2104 OCHandleResponse(endPoint, &respInfo);
2110 // Normal handling of the packet
2111 OCHandleRequests(endPoint, requestInfo);
2113 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2116 bool validatePlatformInfo(OCPlatformInfo info)
2119 if (!info.platformID)
2121 OIC_LOG(ERROR, TAG, "No platform ID found.");
2125 if (info.manufacturerName)
2127 size_t lenManufacturerName = strlen(info.manufacturerName);
2129 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2131 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2137 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2141 if (info.manufacturerUrl)
2143 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2145 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2152 //-----------------------------------------------------------------------------
2154 //-----------------------------------------------------------------------------
2156 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2159 !raInfo->username ||
2160 !raInfo->hostname ||
2161 !raInfo->xmpp_domain)
2164 return OC_STACK_INVALID_PARAM;
2166 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2167 gRASetInfo = (result == OC_STACK_OK)? true : false;
2173 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2177 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2180 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2182 if(stackState == OC_STACK_INITIALIZED)
2184 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2185 OCStop() between them are ignored.");
2189 #ifndef ROUTING_GATEWAY
2190 if (OC_GATEWAY == mode)
2192 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2193 return OC_STACK_INVALID_PARAM;
2200 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2201 return OC_STACK_ERROR;
2205 OCStackResult result = OC_STACK_ERROR;
2206 OIC_LOG(INFO, TAG, "Entering OCInit");
2209 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2210 || (mode == OC_GATEWAY)))
2212 OIC_LOG(ERROR, TAG, "Invalid mode");
2213 return OC_STACK_ERROR;
2217 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2219 caglobals.client = true;
2221 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2223 caglobals.server = true;
2226 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2227 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2229 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2231 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2232 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2234 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2237 defaultDeviceHandler = NULL;
2238 defaultDeviceHandlerCallbackParameter = NULL;
2240 result = InitializeScheduleResourceList();
2241 VERIFY_SUCCESS(result, OC_STACK_OK);
2243 result = CAResultToOCResult(CAInitialize());
2244 VERIFY_SUCCESS(result, OC_STACK_OK);
2246 result = CAResultToOCResult(OCSelectNetwork());
2247 VERIFY_SUCCESS(result, OC_STACK_OK);
2249 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2250 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2251 VERIFY_SUCCESS(result, OC_STACK_OK);
2253 switch (myStackMode)
2256 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2257 result = CAResultToOCResult(CAStartDiscoveryServer());
2258 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2261 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2262 result = CAResultToOCResult(CAStartListeningServer());
2263 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2265 case OC_CLIENT_SERVER:
2267 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2268 result = CAResultToOCResult(CAStartListeningServer());
2269 if(result == OC_STACK_OK)
2271 result = CAResultToOCResult(CAStartDiscoveryServer());
2275 VERIFY_SUCCESS(result, OC_STACK_OK);
2278 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2281 #ifdef WITH_PRESENCE
2282 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2283 #endif // WITH_PRESENCE
2285 //Update Stack state to initialized
2286 stackState = OC_STACK_INITIALIZED;
2288 // Initialize resource
2289 if(myStackMode != OC_CLIENT)
2291 result = initResources();
2294 // Initialize the SRM Policy Engine
2295 if(result == OC_STACK_OK)
2297 result = SRMInitPolicyEngine();
2298 // TODO after BeachHead delivery: consolidate into single SRMInit()
2300 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2301 RMSetStackMode(mode);
2302 #ifdef ROUTING_GATEWAY
2303 if (OC_GATEWAY == myStackMode)
2305 result = RMInitialize();
2311 if (result == OC_STACK_OK)
2313 result = InitializeKeepAlive(myStackMode);
2318 if(result != OC_STACK_OK)
2320 OIC_LOG(ERROR, TAG, "Stack initialization error");
2321 deleteAllResources();
2323 TerminateScheduleResourceList();
2324 stackState = OC_STACK_UNINITIALIZED;
2329 OCStackResult OCStop()
2331 OIC_LOG(INFO, TAG, "Entering OCStop");
2333 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2335 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2338 else if (stackState != OC_STACK_INITIALIZED)
2340 OIC_LOG(ERROR, TAG, "Stack not initialized");
2341 return OC_STACK_ERROR;
2344 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2346 #ifdef WITH_PRESENCE
2347 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2348 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2349 presenceResource.presenceTTL = 0;
2350 #endif // WITH_PRESENCE
2352 #ifdef ROUTING_GATEWAY
2353 if (OC_GATEWAY == myStackMode)
2360 TerminateKeepAlive(myStackMode);
2363 // Free memory dynamically allocated for resources
2364 deleteAllResources();
2366 DeletePlatformInfo();
2368 TerminateScheduleResourceList();
2369 // Remove all observers
2370 DeleteObserverList();
2371 // Remove all the client callbacks
2372 DeleteClientCBList();
2374 // De-init the SRM Policy Engine
2375 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2376 SRMDeInitPolicyEngine();
2379 stackState = OC_STACK_UNINITIALIZED;
2383 OCStackResult OCStartMulticastServer()
2385 if(stackState != OC_STACK_INITIALIZED)
2387 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2388 return OC_STACK_ERROR;
2390 CAResult_t ret = CAStartListeningServer();
2391 if (CA_STATUS_OK != ret)
2393 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2394 return OC_STACK_ERROR;
2399 OCStackResult OCStopMulticastServer()
2401 CAResult_t ret = CAStopListeningServer();
2402 if (CA_STATUS_OK != ret)
2404 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2405 return OC_STACK_ERROR;
2410 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2415 return CA_MSG_CONFIRM;
2420 return CA_MSG_NONCONFIRM;
2425 * A request uri consists of the following components in order:
2428 * CoAP over UDP prefix "coap://"
2429 * CoAP over TCP prefix "coap+tcp://"
2430 * CoAP over DTLS prefix "coaps://"
2431 * CoAP over TLS prefix "coaps+tcp://"
2433 * IPv6 address "[1234::5678]"
2434 * IPv4 address "192.168.1.1"
2435 * optional port ":5683"
2436 * resource uri "/oc/core..."
2438 * for PRESENCE requests, extract resource type.
2440 static OCStackResult ParseRequestUri(const char *fullUri,
2441 OCTransportAdapter adapter,
2442 OCTransportFlags flags,
2443 OCDevAddr **devAddr,
2445 char **resourceType)
2447 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2449 OCStackResult result = OC_STACK_OK;
2450 OCDevAddr *da = NULL;
2454 // provide defaults for all returned values
2461 *resourceUri = NULL;
2465 *resourceType = NULL;
2468 // delimit url prefix, if any
2469 const char *start = fullUri;
2470 char *slash2 = strstr(start, "//");
2475 char *slash = strchr(start, '/');
2478 return OC_STACK_INVALID_URI;
2481 // process url scheme
2482 size_t prefixLen = slash2 - fullUri;
2486 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2487 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2493 // TODO: this logic should come in with unit tests exercising the various strings
2494 // processs url prefix, if any
2495 size_t urlLen = slash - start;
2499 if (urlLen && devAddr)
2500 { // construct OCDevAddr
2501 if (start[0] == '[')
2503 char *close = strchr(++start, ']');
2504 if (!close || close > slash)
2506 return OC_STACK_INVALID_URI;
2509 if (close[1] == ':')
2516 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2520 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2522 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2526 char *dot = strchr(start, '.');
2527 if (dot && dot < slash)
2529 colon = strchr(start, ':');
2530 end = (colon && colon < slash) ? colon : slash;
2535 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2539 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2541 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2549 if (len >= sizeof(da->addr))
2551 return OC_STACK_INVALID_URI;
2553 // collect port, if any
2554 if (colon && colon < slash)
2556 for (colon++; colon < slash; colon++)
2559 if (c < '0' || c > '9')
2561 return OC_STACK_INVALID_URI;
2563 port = 10 * port + c - '0';
2568 if (len >= sizeof(da->addr))
2570 return OC_STACK_INVALID_URI;
2573 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2576 return OC_STACK_NO_MEMORY;
2578 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2580 da->adapter = adapter;
2582 if (!strncmp(fullUri, "coaps", 5))
2584 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2589 // process resource uri, if any
2591 { // request uri and query
2592 size_t ulen = strlen(slash); // resource uri length
2593 size_t tlen = 0; // resource type length
2596 static const char strPresence[] = "/oic/ad?rt=";
2597 static const size_t lenPresence = sizeof(strPresence) - 1;
2598 if (!strncmp(slash, strPresence, lenPresence))
2600 type = slash + lenPresence;
2601 tlen = ulen - lenPresence;
2606 *resourceUri = (char *)OICMalloc(ulen + 1);
2609 result = OC_STACK_NO_MEMORY;
2612 strcpy(*resourceUri, slash);
2615 if (type && resourceType)
2617 *resourceType = (char *)OICMalloc(tlen + 1);
2620 result = OC_STACK_NO_MEMORY;
2624 OICStrcpy(*resourceType, (tlen+1), type);
2631 // free all returned values
2638 OICFree(*resourceUri);
2642 OICFree(*resourceType);
2647 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2652 char uri[CA_MAX_URI_LENGTH];
2654 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2656 *requestUri = OICStrdup(uri);
2659 return OC_STACK_NO_MEMORY;
2666 * Discover or Perform requests on a specified resource
2668 OCStackResult OCDoResource(OCDoHandle *handle,
2670 const char *requestUri,
2671 const OCDevAddr *destination,
2673 OCConnectivityType connectivityType,
2674 OCQualityOfService qos,
2675 OCCallbackData *cbData,
2676 OCHeaderOption *options,
2679 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2681 // Validate input parameters
2682 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2683 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2685 OCStackResult result = OC_STACK_ERROR;
2686 CAResult_t caResult;
2687 CAToken_t token = NULL;
2688 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2689 ClientCB *clientCB = NULL;
2690 OCDoHandle resHandle = NULL;
2691 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2692 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2694 OCTransportAdapter adapter;
2695 OCTransportFlags flags;
2696 // the request contents are put here
2697 CARequestInfo_t requestInfo = {.method = CA_GET};
2698 // requestUri will be parsed into the following three variables
2699 OCDevAddr *devAddr = NULL;
2700 char *resourceUri = NULL;
2701 char *resourceType = NULL;
2704 * Support original behavior with address on resourceUri argument.
2706 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2707 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2711 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2712 if (result != OC_STACK_OK)
2714 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2718 else if (!checkProxyUri(options, numOptions))
2720 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2727 case OC_REST_OBSERVE:
2728 case OC_REST_OBSERVE_ALL:
2729 requestInfo.method = CA_GET;
2732 requestInfo.method = CA_PUT;
2735 requestInfo.method = CA_POST;
2737 case OC_REST_DELETE:
2738 requestInfo.method = CA_DELETE;
2740 case OC_REST_DISCOVER:
2742 #ifdef WITH_PRESENCE
2743 case OC_REST_PRESENCE:
2745 if (destination || devAddr)
2747 requestInfo.isMulticast = false;
2751 tmpDevAddr.adapter = adapter;
2752 tmpDevAddr.flags = flags;
2753 destination = &tmpDevAddr;
2754 requestInfo.isMulticast = true;
2756 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2757 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2758 // replacing method type with GET.
2759 requestInfo.method = CA_GET;
2762 result = OC_STACK_INVALID_METHOD;
2766 if (!devAddr && !destination)
2768 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2769 result = OC_STACK_INVALID_PARAM;
2773 /* If not original behavior, use destination argument */
2774 if (destination && !devAddr)
2776 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2779 result = OC_STACK_NO_MEMORY;
2782 *devAddr = *destination;
2785 resHandle = GenerateInvocationHandle();
2788 result = OC_STACK_NO_MEMORY;
2792 caResult = CAGenerateToken(&token, tokenLength);
2793 if (caResult != CA_STATUS_OK)
2795 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2796 result= OC_STACK_ERROR;
2800 // fill in request data
2801 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2802 requestInfo.info.token = token;
2803 requestInfo.info.tokenLength = tokenLength;
2804 requestInfo.info.resourceUri = resourceUri;
2806 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2808 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2809 options, numOptions, OC_OBSERVE_REGISTER);
2810 if (result != OC_STACK_OK)
2814 requestInfo.info.numOptions = numOptions + 1;
2818 requestInfo.info.numOptions = numOptions;
2819 requestInfo.info.options =
2820 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2821 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2822 numOptions * sizeof(CAHeaderOption_t));
2825 CopyDevAddrToEndpoint(devAddr, &endpoint);
2830 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2833 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2836 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2840 requestInfo.info.payload = NULL;
2841 requestInfo.info.payloadSize = 0;
2842 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2845 // prepare for response
2846 #ifdef WITH_PRESENCE
2847 if (method == OC_REST_PRESENCE)
2849 char *presenceUri = NULL;
2850 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2851 requestInfo.isMulticast);
2852 if (OC_STACK_OK != result)
2857 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2858 // Presence notification will form a canonical uri to
2859 // look for callbacks into the application.
2860 resourceUri = presenceUri;
2864 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2865 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2866 method, devAddr, resourceUri, resourceType, ttl);
2867 if (OC_STACK_OK != result)
2872 devAddr = NULL; // Client CB list entry now owns it
2873 resourceUri = NULL; // Client CB list entry now owns it
2874 resourceType = NULL; // Client CB list entry now owns it
2877 result = OCSendRequest(&endpoint, &requestInfo);
2878 if (OC_STACK_OK != result)
2885 *handle = resHandle;
2889 if (result != OC_STACK_OK)
2891 OIC_LOG(ERROR, TAG, "OCDoResource error");
2892 FindAndDeleteClientCB(clientCB);
2893 CADestroyToken(token);
2901 // This is the owner of the payload object, so we free it
2902 OCPayloadDestroy(payload);
2903 OICFree(requestInfo.info.payload);
2905 OICFree(resourceUri);
2906 OICFree(resourceType);
2907 OICFree(requestInfo.info.options);
2911 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2915 * This ftn is implemented one of two ways in the case of observation:
2917 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2918 * Remove the callback associated on client side.
2919 * When the next notification comes in from server,
2920 * reply with RESET message to server.
2921 * Keep in mind that the server will react to RESET only
2922 * if the last notification was sent as CON
2924 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2925 * and it is associated with an observe request
2926 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2927 * Send CON Observe request to server with
2928 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2929 * Remove the callback associated on client side.
2931 OCStackResult ret = OC_STACK_OK;
2932 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2933 CARequestInfo_t requestInfo = {.method = CA_GET};
2937 return OC_STACK_INVALID_PARAM;
2940 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2943 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2944 return OC_STACK_ERROR;
2947 switch (clientCB->method)
2949 case OC_REST_OBSERVE:
2950 case OC_REST_OBSERVE_ALL:
2952 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2954 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2956 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2958 FindAndDeleteClientCB(clientCB);
2962 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2964 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2965 requestInfo.info.token = clientCB->token;
2966 requestInfo.info.tokenLength = clientCB->tokenLength;
2968 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2969 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2971 return OC_STACK_ERROR;
2973 requestInfo.info.numOptions = numOptions + 1;
2974 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2977 ret = OCSendRequest(&endpoint, &requestInfo);
2979 if (requestInfo.info.options)
2981 OICFree (requestInfo.info.options);
2983 if (requestInfo.info.resourceUri)
2985 OICFree (requestInfo.info.resourceUri);
2990 case OC_REST_DISCOVER:
2991 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2992 clientCB->requestUri);
2993 FindAndDeleteClientCB(clientCB);
2996 #ifdef WITH_PRESENCE
2997 case OC_REST_PRESENCE:
2998 FindAndDeleteClientCB(clientCB);
3003 ret = OC_STACK_INVALID_METHOD;
3011 * @brief Register Persistent storage callback.
3012 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3014 * OC_STACK_OK - No errors; Success
3015 * OC_STACK_INVALID_PARAM - Invalid parameter
3017 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3019 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3020 if(!persistentStorageHandler)
3022 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3023 return OC_STACK_INVALID_PARAM;
3027 if( !persistentStorageHandler->open ||
3028 !persistentStorageHandler->close ||
3029 !persistentStorageHandler->read ||
3030 !persistentStorageHandler->unlink ||
3031 !persistentStorageHandler->write)
3033 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3034 return OC_STACK_INVALID_PARAM;
3037 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3040 #ifdef WITH_PRESENCE
3042 OCStackResult OCProcessPresence()
3044 OCStackResult result = OC_STACK_OK;
3046 // the following line floods the log with messages that are irrelevant
3047 // to most purposes. Uncomment as needed.
3048 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3049 ClientCB* cbNode = NULL;
3050 OCClientResponse clientResponse;
3051 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3053 LL_FOREACH(cbList, cbNode)
3055 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3060 uint32_t now = GetTicks(0);
3061 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3062 cbNode->presence->TTLlevel);
3063 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3065 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3070 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3072 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3073 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3075 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3077 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3079 clientResponse.sequenceNumber = 0;
3080 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3081 clientResponse.devAddr = *cbNode->devAddr;
3082 FixUpClientResponse(&clientResponse);
3083 clientResponse.payload = NULL;
3085 // Increment the TTLLevel (going to a next state), so we don't keep
3086 // sending presence notification to client.
3087 cbNode->presence->TTLlevel++;
3088 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3089 cbNode->presence->TTLlevel);
3091 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3092 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3094 FindAndDeleteClientCB(cbNode);
3098 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3103 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3104 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3105 CARequestInfo_t requestInfo = {.method = CA_GET};
3107 OIC_LOG(DEBUG, TAG, "time to test server presence");
3109 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3111 requestData.type = CA_MSG_NONCONFIRM;
3112 requestData.token = cbNode->token;
3113 requestData.tokenLength = cbNode->tokenLength;
3114 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3115 requestInfo.method = CA_GET;
3116 requestInfo.info = requestData;
3118 result = OCSendRequest(&endpoint, &requestInfo);
3119 if (OC_STACK_OK != result)
3124 cbNode->presence->TTLlevel++;
3125 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3128 if (result != OC_STACK_OK)
3130 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3135 #endif // WITH_PRESENCE
3137 OCStackResult OCProcess()
3139 #ifdef WITH_PRESENCE
3140 OCProcessPresence();
3142 CAHandleRequestResponse();
3144 #ifdef ROUTING_GATEWAY
3154 #ifdef WITH_PRESENCE
3155 OCStackResult OCStartPresence(const uint32_t ttl)
3157 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3158 OCChangeResourceProperty(
3159 &(((OCResource *)presenceResource.handle)->resourceProperties),
3162 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3164 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3165 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3169 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3170 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3174 presenceResource.presenceTTL = ttl;
3176 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3178 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3180 presenceState = OC_PRESENCE_INITIALIZED;
3182 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3184 CAToken_t caToken = NULL;
3185 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3186 if (caResult != CA_STATUS_OK)
3188 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3189 CADestroyToken(caToken);
3190 return OC_STACK_ERROR;
3193 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3194 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3195 CADestroyToken(caToken);
3198 // Each time OCStartPresence is called
3199 // a different random 32-bit integer number is used
3200 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3202 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3203 OC_PRESENCE_TRIGGER_CREATE);
3206 OCStackResult OCStopPresence()
3208 OCStackResult result = OC_STACK_ERROR;
3210 if(presenceResource.handle)
3212 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3214 // make resource inactive
3215 result = OCChangeResourceProperty(
3216 &(((OCResource *) presenceResource.handle)->resourceProperties),
3220 if(result != OC_STACK_OK)
3223 "Changing the presence resource properties to ACTIVE not successful");
3227 return SendStopNotification();
3231 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3232 void* callbackParameter)
3234 defaultDeviceHandler = entityHandler;
3235 defaultDeviceHandlerCallbackParameter = callbackParameter;
3240 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3242 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3244 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3246 if (validatePlatformInfo(platformInfo))
3248 return SavePlatformInfo(platformInfo);
3252 return OC_STACK_INVALID_PARAM;
3257 return OC_STACK_ERROR;
3261 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3263 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3265 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3267 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3268 return OC_STACK_INVALID_PARAM;
3271 if (deviceInfo.types)
3273 OCStringLL *type = deviceInfo.types;
3274 OCResource *resource = findResource((OCResource *) deviceResource);
3277 return OC_STACK_INVALID_PARAM;
3282 OCBindResourceTypeToResource(deviceResource, type->value);
3286 return SaveDeviceInfo(deviceInfo);
3289 OCStackResult OCCreateResource(OCResourceHandle *handle,
3290 const char *resourceTypeName,
3291 const char *resourceInterfaceName,
3292 const char *uri, OCEntityHandler entityHandler,
3293 void* callbackParam,
3294 uint8_t resourceProperties)
3297 OCResource *pointer = NULL;
3298 OCStackResult result = OC_STACK_ERROR;
3300 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3302 if(myStackMode == OC_CLIENT)
3304 return OC_STACK_INVALID_PARAM;
3306 // Validate parameters
3307 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3309 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3310 return OC_STACK_INVALID_URI;
3312 // Is it presented during resource discovery?
3313 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3315 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3316 return OC_STACK_INVALID_PARAM;
3319 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3321 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3325 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3327 // Make sure resourceProperties bitmask has allowed properties specified
3328 if (resourceProperties
3329 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3330 OC_EXPLICIT_DISCOVERABLE
3339 OIC_LOG(ERROR, TAG, "Invalid property");
3340 return OC_STACK_INVALID_PARAM;
3343 // If the headResource is NULL, then no resources have been created...
3344 pointer = headResource;
3347 // At least one resources is in the resource list, so we need to search for
3348 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3351 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3353 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3354 return OC_STACK_INVALID_PARAM;
3356 pointer = pointer->next;
3359 // Create the pointer and insert it into the resource list
3360 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3363 result = OC_STACK_NO_MEMORY;
3366 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3368 insertResource(pointer);
3371 pointer->uri = OICStrdup(uri);
3374 result = OC_STACK_NO_MEMORY;
3378 // Set properties. Set OC_ACTIVE
3379 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3382 // Add the resourcetype to the resource
3383 result = BindResourceTypeToResource(pointer, resourceTypeName);
3384 if (result != OC_STACK_OK)
3386 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3390 // Add the resourceinterface to the resource
3391 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3392 if (result != OC_STACK_OK)
3394 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3398 // If an entity handler has been passed, attach it to the newly created
3399 // resource. Otherwise, set the default entity handler.
3402 pointer->entityHandler = entityHandler;
3403 pointer->entityHandlerCallbackParam = callbackParam;
3407 pointer->entityHandler = defaultResourceEHandler;
3408 pointer->entityHandlerCallbackParam = NULL;
3411 // Initialize a pointer indicating child resources in case of collection
3412 pointer->rsrcChildResourcesHead = NULL;
3415 result = OC_STACK_OK;
3417 #ifdef WITH_PRESENCE
3418 if (presenceResource.handle)
3420 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3421 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3425 if (result != OC_STACK_OK)
3427 // Deep delete of resource and other dynamic elements that it contains
3428 deleteResource(pointer);
3433 OCStackResult OCBindResource(
3434 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3436 OCResource *resource = NULL;
3437 OCChildResource *tempChildResource = NULL;
3438 OCChildResource *newChildResource = NULL;
3440 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3442 // Validate parameters
3443 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3444 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3445 // Container cannot contain itself
3446 if (collectionHandle == resourceHandle)
3448 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3449 return OC_STACK_INVALID_PARAM;
3452 // Use the handle to find the resource in the resource linked list
3453 resource = findResource((OCResource *) collectionHandle);
3456 OIC_LOG(ERROR, TAG, "Collection handle not found");
3457 return OC_STACK_INVALID_PARAM;
3460 // Look for an open slot to add add the child resource.
3461 // If found, add it and return success
3463 tempChildResource = resource->rsrcChildResourcesHead;
3465 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3467 // TODO: what if one of child resource was deregistered without unbinding?
3468 tempChildResource = tempChildResource->next;
3471 // Do memory allocation for child resource
3472 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3473 if(!newChildResource)
3475 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3476 return OC_STACK_ERROR;
3479 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3480 newChildResource->next = NULL;
3482 if(!resource->rsrcChildResourcesHead)
3484 resource->rsrcChildResourcesHead = newChildResource;
3487 tempChildResource->next = newChildResource;
3490 OIC_LOG(INFO, TAG, "resource bound");
3492 #ifdef WITH_PRESENCE
3493 if (presenceResource.handle)
3495 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3496 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3497 OC_PRESENCE_TRIGGER_CHANGE);
3504 OCStackResult OCUnBindResource(
3505 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3507 OCResource *resource = NULL;
3508 OCChildResource *tempChildResource = NULL;
3509 OCChildResource *tempLastChildResource = NULL;
3511 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3513 // Validate parameters
3514 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3515 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3516 // Container cannot contain itself
3517 if (collectionHandle == resourceHandle)
3519 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3520 return OC_STACK_INVALID_PARAM;
3523 // Use the handle to find the resource in the resource linked list
3524 resource = findResource((OCResource *) collectionHandle);
3527 OIC_LOG(ERROR, TAG, "Collection handle not found");
3528 return OC_STACK_INVALID_PARAM;
3531 // Look for an open slot to add add the child resource.
3532 // If found, add it and return success
3533 if(!resource->rsrcChildResourcesHead)
3535 OIC_LOG(INFO, TAG, "resource not found in collection");
3537 // Unable to add resourceHandle, so return error
3538 return OC_STACK_ERROR;
3542 tempChildResource = resource->rsrcChildResourcesHead;
3544 while (tempChildResource)
3546 if(tempChildResource->rsrcResource == resourceHandle)
3548 // if resource going to be unbinded is the head one.
3549 if( tempChildResource == resource->rsrcChildResourcesHead )
3551 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3552 OICFree(resource->rsrcChildResourcesHead);
3553 resource->rsrcChildResourcesHead = temp;
3558 OCChildResource *temp = tempChildResource->next;
3559 OICFree(tempChildResource);
3560 tempLastChildResource->next = temp;
3564 OIC_LOG(INFO, TAG, "resource unbound");
3566 // Send notification when resource is unbounded successfully.
3567 #ifdef WITH_PRESENCE
3568 if (presenceResource.handle)
3570 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3571 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3572 OC_PRESENCE_TRIGGER_CHANGE);
3575 tempChildResource = NULL;
3576 tempLastChildResource = NULL;
3582 tempLastChildResource = tempChildResource;
3583 tempChildResource = tempChildResource->next;
3586 OIC_LOG(INFO, TAG, "resource not found in collection");
3588 tempChildResource = NULL;
3589 tempLastChildResource = NULL;
3591 // Unable to add resourceHandle, so return error
3592 return OC_STACK_ERROR;
3595 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3597 if (!resourceItemName)
3601 // Per RFC 6690 only registered values must follow the first rule below.
3602 // At this point in time the only values registered begin with "core", and
3603 // all other values are specified as opaque strings where multiple values
3604 // are separated by a space.
3605 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3607 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3609 if (resourceItemName[index] != '.'
3610 && resourceItemName[index] != '-'
3611 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3612 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3620 for (size_t index = 0; resourceItemName[index]; ++index)
3622 if (resourceItemName[index] == ' '
3623 || resourceItemName[index] == '\t'
3624 || resourceItemName[index] == '\r'
3625 || resourceItemName[index] == '\n')
3635 OCStackResult BindResourceTypeToResource(OCResource* resource,
3636 const char *resourceTypeName)
3638 OCResourceType *pointer = NULL;
3640 OCStackResult result = OC_STACK_ERROR;
3642 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3644 if (!ValidateResourceTypeInterface(resourceTypeName))
3646 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3647 return OC_STACK_INVALID_PARAM;
3650 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3653 result = OC_STACK_NO_MEMORY;
3657 str = OICStrdup(resourceTypeName);
3660 result = OC_STACK_NO_MEMORY;
3663 pointer->resourcetypename = str;
3664 pointer->next = NULL;
3666 insertResourceType(resource, pointer);
3667 result = OC_STACK_OK;
3670 if (result != OC_STACK_OK)
3679 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3680 const char *resourceInterfaceName)
3682 OCResourceInterface *pointer = NULL;
3684 OCStackResult result = OC_STACK_ERROR;
3686 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3688 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3690 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3691 return OC_STACK_INVALID_PARAM;
3694 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3696 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3699 result = OC_STACK_NO_MEMORY;
3703 str = OICStrdup(resourceInterfaceName);
3706 result = OC_STACK_NO_MEMORY;
3709 pointer->name = str;
3711 // Bind the resourceinterface to the resource
3712 insertResourceInterface(resource, pointer);
3714 result = OC_STACK_OK;
3717 if (result != OC_STACK_OK)
3726 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3727 const char *resourceTypeName)
3730 OCStackResult result = OC_STACK_ERROR;
3731 OCResource *resource = NULL;
3733 resource = findResource((OCResource *) handle);
3736 OIC_LOG(ERROR, TAG, "Resource not found");
3737 return OC_STACK_ERROR;
3740 result = BindResourceTypeToResource(resource, resourceTypeName);
3742 #ifdef WITH_PRESENCE
3743 if(presenceResource.handle)
3745 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3746 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3753 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3754 const char *resourceInterfaceName)
3757 OCStackResult result = OC_STACK_ERROR;
3758 OCResource *resource = NULL;
3760 resource = findResource((OCResource *) handle);
3763 OIC_LOG(ERROR, TAG, "Resource not found");
3764 return OC_STACK_ERROR;
3767 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3769 #ifdef WITH_PRESENCE
3770 if (presenceResource.handle)
3772 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3773 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3780 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3782 OCResource *pointer = headResource;
3784 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3788 *numResources = *numResources + 1;
3789 pointer = pointer->next;
3794 OCResourceHandle OCGetResourceHandle(uint8_t index)
3796 OCResource *pointer = headResource;
3798 for( uint8_t i = 0; i < index && pointer; ++i)
3800 pointer = pointer->next;
3802 return (OCResourceHandle) pointer;
3805 OCStackResult OCDeleteResource(OCResourceHandle handle)
3809 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3810 return OC_STACK_INVALID_PARAM;
3813 OCResource *resource = findResource((OCResource *) handle);
3814 if (resource == NULL)
3816 OIC_LOG(ERROR, TAG, "Resource not found");
3817 return OC_STACK_NO_RESOURCE;
3820 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3822 OIC_LOG(ERROR, TAG, "Error deleting resource");
3823 return OC_STACK_ERROR;
3829 const char *OCGetResourceUri(OCResourceHandle handle)
3831 OCResource *resource = NULL;
3833 resource = findResource((OCResource *) handle);
3836 return resource->uri;
3838 return (const char *) NULL;
3841 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3843 OCResource *resource = NULL;
3845 resource = findResource((OCResource *) handle);
3848 return resource->resourceProperties;
3850 return (OCResourceProperty)-1;
3853 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3854 uint8_t *numResourceTypes)
3856 OCResource *resource = NULL;
3857 OCResourceType *pointer = NULL;
3859 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3860 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3862 *numResourceTypes = 0;
3864 resource = findResource((OCResource *) handle);
3867 pointer = resource->rsrcType;
3870 *numResourceTypes = *numResourceTypes + 1;
3871 pointer = pointer->next;
3877 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3879 OCResourceType *resourceType = NULL;
3881 resourceType = findResourceTypeAtIndex(handle, index);
3884 return resourceType->resourcetypename;
3886 return (const char *) NULL;
3889 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3890 uint8_t *numResourceInterfaces)
3892 OCResourceInterface *pointer = NULL;
3893 OCResource *resource = NULL;
3895 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3896 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3898 *numResourceInterfaces = 0;
3899 resource = findResource((OCResource *) handle);
3902 pointer = resource->rsrcInterface;
3905 *numResourceInterfaces = *numResourceInterfaces + 1;
3906 pointer = pointer->next;
3912 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3914 OCResourceInterface *resourceInterface = NULL;
3916 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3917 if (resourceInterface)
3919 return resourceInterface->name;
3921 return (const char *) NULL;
3924 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3927 OCResource *resource = NULL;
3928 OCChildResource *tempChildResource = NULL;
3931 resource = findResource((OCResource *) collectionHandle);
3937 tempChildResource = resource->rsrcChildResourcesHead;
3939 while(tempChildResource)
3943 return tempChildResource->rsrcResource;
3946 tempChildResource = tempChildResource->next;
3949 // In this case, the number of resource handles in the collection exceeds the index
3950 tempChildResource = NULL;
3954 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3955 OCEntityHandler entityHandler,
3956 void* callbackParam)
3958 OCResource *resource = NULL;
3960 // Validate parameters
3961 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3963 // Use the handle to find the resource in the resource linked list
3964 resource = findResource((OCResource *)handle);
3967 OIC_LOG(ERROR, TAG, "Resource not found");
3968 return OC_STACK_ERROR;
3972 resource->entityHandler = entityHandler;
3973 resource->entityHandlerCallbackParam = callbackParam;
3975 #ifdef WITH_PRESENCE
3976 if (presenceResource.handle)
3978 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3979 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3986 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3988 OCResource *resource = NULL;
3990 resource = findResource((OCResource *)handle);
3993 OIC_LOG(ERROR, TAG, "Resource not found");
3998 return resource->entityHandler;
4001 void incrementSequenceNumber(OCResource * resPtr)
4003 // Increment the sequence number
4004 resPtr->sequenceNum += 1;
4005 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4007 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4012 #ifdef WITH_PRESENCE
4013 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4014 OCPresenceTrigger trigger)
4016 OCResource *resPtr = NULL;
4017 OCStackResult result = OC_STACK_ERROR;
4018 OCMethod method = OC_REST_PRESENCE;
4019 uint32_t maxAge = 0;
4020 resPtr = findResource((OCResource *) presenceResource.handle);
4023 return OC_STACK_NO_RESOURCE;
4026 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4028 maxAge = presenceResource.presenceTTL;
4030 result = SendAllObserverNotification(method, resPtr, maxAge,
4031 trigger, resourceType, OC_LOW_QOS);
4037 OCStackResult SendStopNotification()
4039 OCResource *resPtr = NULL;
4040 OCStackResult result = OC_STACK_ERROR;
4041 OCMethod method = OC_REST_PRESENCE;
4042 resPtr = findResource((OCResource *) presenceResource.handle);
4045 return OC_STACK_NO_RESOURCE;
4048 // maxAge is 0. ResourceType is NULL.
4049 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4055 #endif // WITH_PRESENCE
4056 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4058 OCResource *resPtr = NULL;
4059 OCStackResult result = OC_STACK_ERROR;
4060 OCMethod method = OC_REST_NOMETHOD;
4061 uint32_t maxAge = 0;
4063 OIC_LOG(INFO, TAG, "Notifying all observers");
4064 #ifdef WITH_PRESENCE
4065 if(handle == presenceResource.handle)
4069 #endif // WITH_PRESENCE
4070 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4072 // Verify that the resource exists
4073 resPtr = findResource ((OCResource *) handle);
4076 return OC_STACK_NO_RESOURCE;
4080 //only increment in the case of regular observing (not presence)
4081 incrementSequenceNumber(resPtr);
4082 method = OC_REST_OBSERVE;
4083 maxAge = MAX_OBSERVE_AGE;
4084 #ifdef WITH_PRESENCE
4085 result = SendAllObserverNotification (method, resPtr, maxAge,
4086 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4088 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4095 OCNotifyListOfObservers (OCResourceHandle handle,
4096 OCObservationId *obsIdList,
4097 uint8_t numberOfIds,
4098 const OCRepPayload *payload,
4099 OCQualityOfService qos)
4101 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4103 OCResource *resPtr = NULL;
4104 //TODO: we should allow the server to define this
4105 uint32_t maxAge = MAX_OBSERVE_AGE;
4107 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4108 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4109 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4111 resPtr = findResource ((OCResource *) handle);
4112 if (NULL == resPtr || myStackMode == OC_CLIENT)
4114 return OC_STACK_NO_RESOURCE;
4118 incrementSequenceNumber(resPtr);
4120 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4121 payload, maxAge, qos));
4124 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4126 OCStackResult result = OC_STACK_ERROR;
4127 OCServerRequest *serverRequest = NULL;
4129 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4131 // Validate input parameters
4132 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4133 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4136 // Get pointer to request info
4137 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4140 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4141 result = serverRequest->ehResponseHandler(ehResponse);
4147 //#ifdef DIRECT_PAIRING
4148 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4150 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4151 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4153 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4157 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4160 const OCDPDev_t* OCGetDirectPairedDevices()
4162 return (const OCDPDev_t*)DPGetPairedDevices();
4165 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4166 OCDirectPairingCB resultCallback)
4168 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4169 if(NULL == peer || NULL == pinNumber)
4171 OIC_LOG(ERROR, TAG, "Invalid parameters");
4172 return OC_STACK_INVALID_PARAM;
4174 if (NULL == resultCallback)
4176 OIC_LOG(ERROR, TAG, "Invalid callback");
4177 return OC_STACK_INVALID_CALLBACK;
4180 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4181 pinNumber, (OCDirectPairingResultCB)resultCallback);
4183 //#endif // DIRECT_PAIRING
4185 //-----------------------------------------------------------------------------
4186 // Private internal function definitions
4187 //-----------------------------------------------------------------------------
4188 static OCDoHandle GenerateInvocationHandle()
4190 OCDoHandle handle = NULL;
4191 // Generate token here, it will be deleted when the transaction is deleted
4192 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4195 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4201 #ifdef WITH_PRESENCE
4202 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4203 OCResourceProperty resourceProperties, uint8_t enable)
4207 return OC_STACK_INVALID_PARAM;
4209 if (resourceProperties
4210 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4212 OIC_LOG(ERROR, TAG, "Invalid property");
4213 return OC_STACK_INVALID_PARAM;
4217 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4221 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4227 OCStackResult initResources()
4229 OCStackResult result = OC_STACK_OK;
4231 headResource = NULL;
4232 tailResource = NULL;
4233 // Init Virtual Resources
4234 #ifdef WITH_PRESENCE
4235 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4237 result = OCCreateResource(&presenceResource.handle,
4238 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4240 OC_RSRVD_PRESENCE_URI,
4244 //make resource inactive
4245 result = OCChangeResourceProperty(
4246 &(((OCResource *) presenceResource.handle)->resourceProperties),
4249 #ifndef WITH_ARDUINO
4250 if (result == OC_STACK_OK)
4252 result = SRMInitSecureResources();
4256 if(result == OC_STACK_OK)
4258 CreateResetProfile();
4259 result = OCCreateResource(&deviceResource,
4260 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4261 OC_RSRVD_INTERFACE_DEFAULT,
4262 OC_RSRVD_DEVICE_URI,
4266 if(result == OC_STACK_OK)
4268 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4269 OC_RSRVD_INTERFACE_READ);
4273 if(result == OC_STACK_OK)
4275 result = OCCreateResource(&platformResource,
4276 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4277 OC_RSRVD_INTERFACE_DEFAULT,
4278 OC_RSRVD_PLATFORM_URI,
4282 if(result == OC_STACK_OK)
4284 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4285 OC_RSRVD_INTERFACE_READ);
4292 void insertResource(OCResource *resource)
4296 headResource = resource;
4297 tailResource = resource;
4301 tailResource->next = resource;
4302 tailResource = resource;
4304 resource->next = NULL;
4307 OCResource *findResource(OCResource *resource)
4309 OCResource *pointer = headResource;
4313 if (pointer == resource)
4317 pointer = pointer->next;
4322 void deleteAllResources()
4324 OCResource *pointer = headResource;
4325 OCResource *temp = NULL;
4329 temp = pointer->next;
4330 #ifdef WITH_PRESENCE
4331 if (pointer != (OCResource *) presenceResource.handle)
4333 #endif // WITH_PRESENCE
4334 deleteResource(pointer);
4335 #ifdef WITH_PRESENCE
4337 #endif // WITH_PRESENCE
4340 memset(&platformResource, 0, sizeof(platformResource));
4341 memset(&deviceResource, 0, sizeof(deviceResource));
4343 memset(&brokerResource, 0, sizeof(brokerResource));
4346 SRMDeInitSecureResources();
4348 #ifdef WITH_PRESENCE
4349 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4350 // presence notification attributed to their deletion to be processed.
4351 deleteResource((OCResource *) presenceResource.handle);
4352 memset(&presenceResource, 0, sizeof(presenceResource));
4353 #endif // WITH_PRESENCE
4356 OCStackResult deleteResource(OCResource *resource)
4358 OCResource *prev = NULL;
4359 OCResource *temp = NULL;
4362 OIC_LOG(DEBUG,TAG,"resource is NULL");
4363 return OC_STACK_INVALID_PARAM;
4366 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4368 temp = headResource;
4371 if (temp == resource)
4373 // Invalidate all Resource Properties.
4374 resource->resourceProperties = (OCResourceProperty) 0;
4375 #ifdef WITH_PRESENCE
4376 if(resource != (OCResource *) presenceResource.handle)
4378 #endif // WITH_PRESENCE
4379 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4380 #ifdef WITH_PRESENCE
4383 if(presenceResource.handle)
4385 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4386 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4389 // Only resource in list.
4390 if (temp == headResource && temp == tailResource)
4392 headResource = NULL;
4393 tailResource = NULL;
4396 else if (temp == headResource)
4398 headResource = temp->next;
4401 else if (temp == tailResource)
4403 tailResource = prev;
4404 tailResource->next = NULL;
4408 prev->next = temp->next;
4411 deleteResourceElements(temp);
4422 return OC_STACK_ERROR;
4425 void deleteResourceElements(OCResource *resource)
4432 OICFree(resource->uri);
4433 deleteResourceType(resource->rsrcType);
4434 deleteResourceInterface(resource->rsrcInterface);
4437 void deleteResourceType(OCResourceType *resourceType)
4439 OCResourceType *pointer = resourceType;
4440 OCResourceType *next = NULL;
4444 next = pointer->next;
4445 OICFree(pointer->resourcetypename);
4451 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4453 OCResourceInterface *pointer = resourceInterface;
4454 OCResourceInterface *next = NULL;
4458 next = pointer->next;
4459 OICFree(pointer->name);
4465 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4467 OCResourceType *pointer = NULL;
4468 OCResourceType *previous = NULL;
4469 if (!resource || !resourceType)
4473 // resource type list is empty.
4474 else if (!resource->rsrcType)
4476 resource->rsrcType = resourceType;
4480 pointer = resource->rsrcType;
4484 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4486 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4487 OICFree(resourceType->resourcetypename);
4488 OICFree(resourceType);
4492 pointer = pointer->next;
4497 previous->next = resourceType;
4500 resourceType->next = NULL;
4502 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4505 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4507 OCResource *resource = NULL;
4508 OCResourceType *pointer = NULL;
4510 // Find the specified resource
4511 resource = findResource((OCResource *) handle);
4517 // Make sure a resource has a resourcetype
4518 if (!resource->rsrcType)
4523 // Iterate through the list
4524 pointer = resource->rsrcType;
4525 for(uint8_t i = 0; i< index && pointer; ++i)
4527 pointer = pointer->next;
4532 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4534 if(resourceTypeList && resourceTypeName)
4536 OCResourceType * rtPointer = resourceTypeList;
4537 while(resourceTypeName && rtPointer)
4539 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4540 if(rtPointer->resourcetypename &&
4541 strcmp(resourceTypeName, (const char *)
4542 (rtPointer->resourcetypename)) == 0)
4546 rtPointer = rtPointer->next;
4554 * Insert a new interface into interface linked list only if not already present.
4555 * If alredy present, 2nd arg is free'd.
4556 * Default interface will always be first if present.
4558 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4560 OCResourceInterface *pointer = NULL;
4561 OCResourceInterface *previous = NULL;
4563 newInterface->next = NULL;
4565 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4567 if (!*firstInterface)
4569 // If first interface is not oic.if.baseline, by default add it as first interface type.
4570 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4572 *firstInterface = newInterface;
4576 OCStackResult result = BindResourceInterfaceToResource(resource,
4577 OC_RSRVD_INTERFACE_DEFAULT);
4578 if (result != OC_STACK_OK)
4580 OICFree(newInterface->name);
4581 OICFree(newInterface);
4584 if (*firstInterface)
4586 (*firstInterface)->next = newInterface;
4590 // If once add oic.if.baseline, later too below code take care of freeing memory.
4591 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4593 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4595 OICFree(newInterface->name);
4596 OICFree(newInterface);
4599 // This code will not hit anymore, keeping
4602 newInterface->next = *firstInterface;
4603 *firstInterface = newInterface;
4608 pointer = *firstInterface;
4611 if (strcmp(newInterface->name, pointer->name) == 0)
4613 OICFree(newInterface->name);
4614 OICFree(newInterface);
4618 pointer = pointer->next;
4623 previous->next = newInterface;
4628 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4631 OCResource *resource = NULL;
4632 OCResourceInterface *pointer = NULL;
4634 // Find the specified resource
4635 resource = findResource((OCResource *) handle);
4641 // Make sure a resource has a resourceinterface
4642 if (!resource->rsrcInterface)
4647 // Iterate through the list
4648 pointer = resource->rsrcInterface;
4650 for (uint8_t i = 0; i < index && pointer; ++i)
4652 pointer = pointer->next;
4658 * This function splits the uri using the '?' delimiter.
4659 * "uriWithoutQuery" is the block of characters between the beginning
4660 * till the delimiter or '\0' which ever comes first.
4661 * "query" is whatever is to the right of the delimiter if present.
4662 * No delimiter sets the query to NULL.
4663 * If either are present, they will be malloc'ed into the params 2, 3.
4664 * The first param, *uri is left untouched.
4666 * NOTE: This function does not account for whitespace at the end of the uri NOR
4667 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4668 * part of the query.
4670 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4674 return OC_STACK_INVALID_URI;
4676 if(!query || !uriWithoutQuery)
4678 return OC_STACK_INVALID_PARAM;
4682 *uriWithoutQuery = NULL;
4684 size_t uriWithoutQueryLen = 0;
4685 size_t queryLen = 0;
4686 size_t uriLen = strlen(uri);
4688 char *pointerToDelimiter = strstr(uri, "?");
4690 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4691 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4693 if (uriWithoutQueryLen)
4695 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4696 if (!*uriWithoutQuery)
4700 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4704 *query = (char *) OICCalloc(queryLen + 1, 1);
4707 OICFree(*uriWithoutQuery);
4708 *uriWithoutQuery = NULL;
4711 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4717 return OC_STACK_NO_MEMORY;
4720 static const OicUuid_t* OCGetServerInstanceID(void)
4722 static bool generated = false;
4723 static OicUuid_t sid;
4729 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4731 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4738 const char* OCGetServerInstanceIDString(void)
4740 static bool generated = false;
4741 static char sidStr[UUID_STRING_SIZE];
4748 const OicUuid_t *sid = OCGetServerInstanceID();
4749 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4751 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4759 CAResult_t OCSelectNetwork()
4761 CAResult_t retResult = CA_STATUS_FAILED;
4762 CAResult_t caResult = CA_STATUS_OK;
4764 CATransportAdapter_t connTypes[] = {
4766 CA_ADAPTER_RFCOMM_BTEDR,
4767 CA_ADAPTER_GATT_BTLE,
4770 ,CA_ADAPTER_REMOTE_ACCESS
4777 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4779 for(int i = 0; i < numConnTypes; i++)
4781 // If CA status is not initialized, CASelectNetwork() will not be called.
4782 if (caResult != CA_STATUS_NOT_INITIALIZED)
4784 caResult = CASelectNetwork(connTypes[i]);
4785 if (caResult == CA_STATUS_OK)
4787 retResult = CA_STATUS_OK;
4792 if (retResult != CA_STATUS_OK)
4794 return caResult; // Returns error of appropriate transport that failed fatally.
4800 OCStackResult CAResultToOCResult(CAResult_t caResult)
4806 case CA_STATUS_INVALID_PARAM:
4807 return OC_STACK_INVALID_PARAM;
4808 case CA_ADAPTER_NOT_ENABLED:
4809 return OC_STACK_ADAPTER_NOT_ENABLED;
4810 case CA_SERVER_STARTED_ALREADY:
4812 case CA_SERVER_NOT_STARTED:
4813 return OC_STACK_ERROR;
4814 case CA_DESTINATION_NOT_REACHABLE:
4815 return OC_STACK_COMM_ERROR;
4816 case CA_SOCKET_OPERATION_FAILED:
4817 return OC_STACK_COMM_ERROR;
4818 case CA_SEND_FAILED:
4819 return OC_STACK_COMM_ERROR;
4820 case CA_RECEIVE_FAILED:
4821 return OC_STACK_COMM_ERROR;
4822 case CA_MEMORY_ALLOC_FAILED:
4823 return OC_STACK_NO_MEMORY;
4824 case CA_REQUEST_TIMEOUT:
4825 return OC_STACK_TIMEOUT;
4826 case CA_DESTINATION_DISCONNECTED:
4827 return OC_STACK_COMM_ERROR;
4828 case CA_STATUS_FAILED:
4829 return OC_STACK_ERROR;
4830 case CA_NOT_SUPPORTED:
4831 return OC_STACK_NOTIMPL;
4833 return OC_STACK_ERROR;
4837 bool OCResultToSuccess(OCStackResult ocResult)
4842 case OC_STACK_RESOURCE_CREATED:
4843 case OC_STACK_RESOURCE_DELETED:
4844 case OC_STACK_CONTINUE:
4845 case OC_STACK_RESOURCE_CHANGED:
4846 case OC_STACK_SLOW_RESOURCE:
4854 OCStackResult OCSetProxyURI(const char *uri)
4856 return CAResultToOCResult(CASetProxyUri(uri));
4860 #if defined(RD_CLIENT) || defined(RD_SERVER)
4861 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4863 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4865 OCResource *resource = NULL;
4867 resource = findResource((OCResource *) handle);
4870 OIC_LOG(ERROR, TAG, "Resource not found");
4871 return OC_STACK_ERROR;
4874 resource->ins = ins;
4879 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4883 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4887 OCResource *pointer = headResource;
4891 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4893 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4896 pointer = pointer->next;
4901 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4903 OCResource *resource = NULL;
4905 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4906 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4908 resource = findResource((OCResource *) handle);
4911 *ins = resource->ins;
4914 return OC_STACK_ERROR;
4917 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4918 void* optionData, size_t optionDataLength)
4922 OIC_LOG (INFO, TAG, "Header options are NULL");
4923 return OC_STACK_INVALID_PARAM;
4928 OIC_LOG (INFO, TAG, "optionData are NULL");
4929 return OC_STACK_INVALID_PARAM;
4934 OIC_LOG (INFO, TAG, "numOptions is NULL");
4935 return OC_STACK_INVALID_PARAM;
4938 if (*numOptions >= MAX_HEADER_OPTIONS)
4940 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4941 return OC_STACK_NO_MEMORY;
4944 ocHdrOpt += *numOptions;
4945 ocHdrOpt->protocolID = OC_COAP_ID;
4946 ocHdrOpt->optionID = optionID;
4947 ocHdrOpt->optionLength =
4948 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4949 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4950 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4955 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
4956 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
4958 if (!ocHdrOpt || !numOptions)
4960 OIC_LOG (INFO, TAG, "No options present");
4966 OIC_LOG (INFO, TAG, "optionData are NULL");
4967 return OC_STACK_INVALID_PARAM;
4970 if (!receivedDataLength)
4972 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
4973 return OC_STACK_INVALID_PARAM;
4976 for (uint8_t i = 0; i < numOptions; i++)
4978 if (ocHdrOpt[i].optionID == optionID)
4980 if (optionDataLength >= ocHdrOpt->optionLength)
4982 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
4983 *receivedDataLength = ocHdrOpt->optionLength;
4988 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
4989 return OC_STACK_ERROR;
4997 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
4999 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5000 if (g_adapterHandler)
5002 g_adapterHandler(adapter, enabled);
5006 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5008 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5009 if (g_connectionHandler)
5011 g_connectionHandler(info, isConnected);
5015 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5016 CAConnectionStateChangedCB connectionHandler)
5018 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5019 g_adapterHandler = adapterHandler;
5020 g_connectionHandler = connectionHandler;
5023 OCStackResult OCGetDeviceId(OCUUIdentity *deviceId)
5028 ret = GetDoxmDeviceID(&oicUuid);
5029 if (OC_STACK_OK == ret)
5031 memcpy(deviceId, &oicUuid, UUID_IDENTITY_SIZE);
5035 OIC_LOG(ERROR, TAG, "Device ID Get error");
5040 OCStackResult OCSetDeviceId(const OCUUIdentity *deviceId)
5044 OIC_LOG(ERROR, TAG, "Set deviceId DOXM");
5046 memcpy(&oicUuid, deviceId, UUID_LENGTH);
5047 for(int i=0;i < UUID_LENGTH; i++)
5049 OIC_LOG_V(INFO, TAG, "Set Device Id %x", oicUuid.id[i]);
5051 ret = SetDoxmDeviceID(&oicUuid);