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"
63 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
64 #include "routingutility.h"
65 #ifdef ROUTING_GATEWAY
66 #include "routingmanager.h"
71 #include "oickeepalive.h"
74 //#ifdef DIRECT_PAIRING
75 #include "directpairing.h"
78 #ifdef HAVE_ARDUINO_TIME_H
81 #ifdef HAVE_SYS_TIME_H
84 #include <coap/coap.h>
86 #ifdef HAVE_ARPA_INET_H
87 #include <arpa/inet.h>
91 #define UINT32_MAX (0xFFFFFFFFUL)
94 //-----------------------------------------------------------------------------
96 //-----------------------------------------------------------------------------
99 OC_STACK_UNINITIALIZED = 0,
100 OC_STACK_INITIALIZED,
101 OC_STACK_UNINIT_IN_PROGRESS
107 OC_PRESENCE_UNINITIALIZED = 0,
108 OC_PRESENCE_INITIALIZED
112 //-----------------------------------------------------------------------------
114 //-----------------------------------------------------------------------------
115 static OCStackState stackState = OC_STACK_UNINITIALIZED;
117 OCResource *headResource = NULL;
118 static OCResource *tailResource = NULL;
119 static OCResourceHandle platformResource = {0};
120 static OCResourceHandle deviceResource = {0};
122 static OCResourceHandle brokerResource = {0};
126 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
127 static PresenceResource presenceResource = {0};
128 static uint8_t PresenceTimeOutSize = 0;
129 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
132 static OCMode myStackMode;
134 //TODO: revisit this design
135 static bool gRASetInfo = false;
137 OCDeviceEntityHandler defaultDeviceHandler;
138 void* defaultDeviceHandlerCallbackParameter = NULL;
139 static const char COAP_TCP_SCHEME[] = "coap+tcp:";
140 static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
141 static const char CORESPEC[] = "core";
143 CAAdapterStateChangedCB g_adapterHandler = NULL;
144 CAConnectionStateChangedCB g_connectionHandler = NULL;
146 //-----------------------------------------------------------------------------
148 //-----------------------------------------------------------------------------
149 #define TAG "OIC_RI_STACK"
150 #define VERIFY_SUCCESS(op, successCode) { if ((op) != (successCode)) \
151 {OIC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} }
152 #define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
153 TAG, #arg " is NULL"); return (retVal); } }
154 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OIC_LOG((logLevel), \
155 TAG, #arg " is NULL"); return; } }
156 #define VERIFY_NON_NULL_V(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL");\
159 //TODO: we should allow the server to define this
160 #define MAX_OBSERVE_AGE (0x2FFFFUL)
162 #define MILLISECONDS_PER_SECOND (1000)
164 //-----------------------------------------------------------------------------
165 // Private internal function prototypes
166 //-----------------------------------------------------------------------------
169 * Generate handle of OCDoResource invocation for callback management.
171 * @return Generated OCDoResource handle.
173 static OCDoHandle GenerateInvocationHandle();
176 * Initialize resource data structures, variables, etc.
178 * @return ::OC_STACK_OK on success, some other value upon failure.
180 static OCStackResult initResources();
183 * Add a resource to the end of the linked list of resources.
185 * @param resource Resource to be added
187 static void insertResource(OCResource *resource);
190 * Find a resource in the linked list of resources.
192 * @param resource Resource to be found.
193 * @return Pointer to resource that was found in the linked list or NULL if the resource was not
196 static OCResource *findResource(OCResource *resource);
199 * Insert a resource type into a resource's resource type linked list.
200 * If resource type already exists, it will not be inserted and the
201 * resourceType will be free'd.
202 * resourceType->next should be null to avoid memory leaks.
203 * Function returns silently for null args.
205 * @param resource Resource where resource type is to be inserted.
206 * @param resourceType Resource type to be inserted.
208 static void insertResourceType(OCResource *resource,
209 OCResourceType *resourceType);
212 * Get a resource type at the specified index within a resource.
214 * @param handle Handle of resource.
215 * @param index Index of resource type.
217 * @return Pointer to resource type if found, NULL otherwise.
219 static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle,
223 * Insert a resource interface into a resource's resource interface linked list.
224 * If resource interface already exists, it will not be inserted and the
225 * resourceInterface will be free'd.
226 * resourceInterface->next should be null to avoid memory leaks.
228 * @param resource Resource where resource interface is to be inserted.
229 * @param resourceInterface Resource interface to be inserted.
231 static void insertResourceInterface(OCResource *resource,
232 OCResourceInterface *resourceInterface);
235 * Get a resource interface at the specified index within a resource.
237 * @param handle Handle of resource.
238 * @param index Index of resource interface.
240 * @return Pointer to resource interface if found, NULL otherwise.
242 static OCResourceInterface *findResourceInterfaceAtIndex(
243 OCResourceHandle handle, uint8_t index);
246 * Delete all of the dynamically allocated elements that were created for the resource type.
248 * @param resourceType Specified resource type.
250 static void deleteResourceType(OCResourceType *resourceType);
253 * Delete all of the dynamically allocated elements that were created for the resource interface.
255 * @param resourceInterface Specified resource interface.
257 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
260 * Delete all of the dynamically allocated elements that were created for the resource.
262 * @param resource Specified resource.
264 static void deleteResourceElements(OCResource *resource);
267 * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface
270 * @param handle Handle of resource to be deleted.
272 * @return ::OC_STACK_OK on success, some other value upon failure.
274 static OCStackResult deleteResource(OCResource *resource);
277 * Delete all of the resources in the resource list.
279 static void deleteAllResources();
282 * Increment resource sequence number. Handles rollover.
284 * @param resPtr Pointer to resource.
286 static void incrementSequenceNumber(OCResource * resPtr);
289 * Attempts to initialize every network interface that the CA Layer might have compiled in.
291 * Note: At least one interface must succeed to initialize. If all calls to @ref CASelectNetwork
292 * return something other than @ref CA_STATUS_OK, then this function fails.
294 * @return ::CA_STATUS_OK on success, some other value upon failure.
296 static CAResult_t OCSelectNetwork();
299 * Get the CoAP ticks after the specified number of milli-seconds.
301 * @param afterMilliSeconds Milli-seconds.
305 static uint32_t GetTicks(uint32_t afterMilliSeconds);
308 * Convert CAResult_t to OCStackResult.
310 * @param caResult CAResult_t code.
311 * @return ::OC_STACK_OK on success, some other value upon failure.
313 static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
316 * Convert CAResponseResult_t to OCStackResult.
318 * @param caCode CAResponseResult_t code.
319 * @return ::OC_STACK_OK on success, some other value upon failure.
321 static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
324 * Convert OCStackResult to CAResponseResult_t.
326 * @param caCode OCStackResult code.
327 * @param method OCMethod method the return code replies to.
328 * @return ::CA_CONTENT on OK, some other value upon failure.
330 static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method);
333 * Convert OCTransportFlags_t to CATransportModifiers_t.
335 * @param ocConType OCTransportFlags_t input.
336 * @return CATransportFlags
338 static CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocConType);
341 * Convert CATransportFlags_t to OCTransportModifiers_t.
343 * @param caConType CATransportFlags_t input.
344 * @return OCTransportFlags
346 static OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caConType);
349 * Handle response from presence request.
351 * @param endPoint CA remote endpoint.
352 * @param responseInfo CA response info.
353 * @return ::OC_STACK_OK on success, some other value upon failure.
355 static OCStackResult HandlePresenceResponse(const CAEndpoint_t *endPoint,
356 const CAResponseInfo_t *responseInfo);
359 * This function will be called back by CA layer when a response is received.
361 * @param endPoint CA remote endpoint.
362 * @param responseInfo CA response info.
364 static void HandleCAResponses(const CAEndpoint_t* endPoint,
365 const CAResponseInfo_t* responseInfo);
368 * This function will be called back by CA layer when a request is received.
370 * @param endPoint CA remote endpoint.
371 * @param requestInfo CA request info.
373 static void HandleCARequests(const CAEndpoint_t* endPoint,
374 const CARequestInfo_t* requestInfo);
377 * Extract query from a URI.
379 * @param uri Full URI with query.
380 * @param query Pointer to string that will contain query.
381 * @param newURI Pointer to string that will contain URI.
382 * @return ::OC_STACK_OK on success, some other value upon failure.
384 static OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
387 * Finds a resource type in an OCResourceType link-list.
389 * @param resourceTypeList The link-list to be searched through.
390 * @param resourceTypeName The key to search for.
392 * @return Resource type that matches the key (ie. resourceTypeName) or
393 * NULL if there is either an invalid parameter or this function was unable to find the key.
395 static OCResourceType *findResourceType(OCResourceType * resourceTypeList,
396 const char * resourceTypeName);
399 * Reset presence TTL for a ClientCB struct. ttlLevel will be set to 0.
400 * TTL will be set to maxAge.
402 * @param cbNode Callback Node for which presence ttl is to be reset.
403 * @param maxAge New value of ttl in seconds.
405 * @return ::OC_STACK_OK on success, some other value upon failure.
407 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds);
410 * Ensure the accept header option is set appropriatly before sending the requests and routing
411 * header option is updated with destination.
413 * @param object CA remote endpoint.
414 * @param requestInfo CA request info.
416 * @return ::OC_STACK_OK on success, some other value upon failure.
418 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo);
421 * default adapter state change callback method
423 * @param adapter CA network adapter type.
424 * @param enabled current adapter state.
426 static void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled);
429 * default connection state change callback method
431 * @param info CAEndpoint which has address, port and etc.
432 * @param isConnected current connection state.
434 static void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected);
437 * Register network monitoring callback.
438 * Network status changes are delivered these callback.
439 * @param adapterHandler Adapter state monitoring callback.
440 * @param connectionHandler Connection state monitoring callback.
442 static void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
443 CAConnectionStateChangedCB connectionHandler);
445 //-----------------------------------------------------------------------------
446 // Internal functions
447 //-----------------------------------------------------------------------------
449 bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
451 if (!options || 0 == numOptions)
453 OIC_LOG (INFO, TAG, "No options present");
457 for (uint8_t i = 0; i < numOptions; i++)
459 if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
461 OIC_LOG(DEBUG, TAG, "Proxy URI is present");
468 uint32_t GetTicks(uint32_t afterMilliSeconds)
473 // Guard against overflow of uint32_t
474 if (afterMilliSeconds <= ((UINT32_MAX - (uint32_t)now) * MILLISECONDS_PER_SECOND) /
475 COAP_TICKS_PER_SECOND)
477 return now + (afterMilliSeconds * COAP_TICKS_PER_SECOND)/MILLISECONDS_PER_SECOND;
485 void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
487 VERIFY_NON_NULL_NR(in, FATAL);
488 VERIFY_NON_NULL_NR(out, FATAL);
490 out->adapter = (OCTransportAdapter)in->adapter;
491 out->flags = CAToOCTransportFlags(in->flags);
492 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
493 out->port = in->port;
494 out->ifindex = in->ifindex;
495 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
496 /* This assert is to prevent accidental mismatch between address size macros defined in
497 * RI and CA and cause crash here. */
498 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
499 "Address size mismatch between RI and CA");
500 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
504 void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
506 VERIFY_NON_NULL_NR(in, FATAL);
507 VERIFY_NON_NULL_NR(out, FATAL);
509 out->adapter = (CATransportAdapter_t)in->adapter;
510 out->flags = OCToCATransportFlags(in->flags);
511 OICStrcpy(out->addr, sizeof(out->addr), in->addr);
512 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
513 /* This assert is to prevent accidental mismatch between address size macros defined in
514 * RI and CA and cause crash here. */
515 OC_STATIC_ASSERT(MAX_ADDR_STR_SIZE_CA == MAX_ADDR_STR_SIZE,
516 "Address size mismatch between RI and CA");
517 memcpy(out->routeData, in->routeData, sizeof(in->routeData));
519 out->port = in->port;
520 out->ifindex = in->ifindex;
523 void FixUpClientResponse(OCClientResponse *cr)
525 VERIFY_NON_NULL_NR(cr, FATAL);
527 cr->addr = &cr->devAddr;
528 cr->connType = (OCConnectivityType)
529 ((cr->devAddr.adapter << CT_ADAPTER_SHIFT) | (cr->devAddr.flags & CT_MASK_FLAGS));
532 static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *requestInfo)
534 VERIFY_NON_NULL(object, FATAL, OC_STACK_INVALID_PARAM);
535 VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
537 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
538 OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
539 if (OC_STACK_OK != rmResult)
541 OIC_LOG(ERROR, TAG, "Add destination option failed");
546 // OC stack prefer CBOR encoded payloads.
547 requestInfo->info.acceptFormat = CA_FORMAT_APPLICATION_CBOR;
548 CAResult_t result = CASendRequest(object, requestInfo);
549 if(CA_STATUS_OK != result)
551 OIC_LOG_V(ERROR, TAG, "CASendRequest failed with CA error %u", result);
552 return CAResultToOCResult(result);
556 //-----------------------------------------------------------------------------
557 // Internal API function
558 //-----------------------------------------------------------------------------
560 // This internal function is called to update the stack with the status of
561 // observers and communication failures
562 OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t status)
564 OCStackResult result = OC_STACK_ERROR;
565 ResourceObserver * observer = NULL;
566 OCEntityHandlerRequest ehRequest = {0};
570 case OC_OBSERVER_NOT_INTERESTED:
571 OIC_LOG(DEBUG, TAG, "observer not interested in our notifications");
572 observer = GetObserverUsingToken (token, tokenLength);
575 result = FormOCEntityHandlerRequest(&ehRequest,
576 (OCRequestHandle)NULL,
579 (OCResourceHandle)NULL,
580 NULL, PAYLOAD_TYPE_REPRESENTATION,
582 OC_OBSERVE_DEREGISTER,
585 if(result != OC_STACK_OK)
589 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
590 observer->resource->entityHandlerCallbackParam);
593 result = DeleteObserverUsingToken (token, tokenLength);
594 if(result == OC_STACK_OK)
596 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
600 result = OC_STACK_OK;
601 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
605 case OC_OBSERVER_STILL_INTERESTED:
606 OIC_LOG(DEBUG, TAG, "observer still interested, reset the failedCount");
607 observer = GetObserverUsingToken (token, tokenLength);
610 observer->forceHighQos = 0;
611 observer->failedCommCount = 0;
612 result = OC_STACK_OK;
616 result = OC_STACK_OBSERVER_NOT_FOUND;
620 case OC_OBSERVER_FAILED_COMM:
621 OIC_LOG(DEBUG, TAG, "observer is unreachable");
622 observer = GetObserverUsingToken (token, tokenLength);
625 if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM)
627 result = FormOCEntityHandlerRequest(&ehRequest,
628 (OCRequestHandle)NULL,
631 (OCResourceHandle)NULL,
632 NULL, PAYLOAD_TYPE_REPRESENTATION,
634 OC_OBSERVE_DEREGISTER,
637 if(result != OC_STACK_OK)
639 return OC_STACK_ERROR;
641 observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest,
642 observer->resource->entityHandlerCallbackParam);
644 result = DeleteObserverUsingToken (token, tokenLength);
645 if(result == OC_STACK_OK)
647 OIC_LOG(DEBUG, TAG, "Removed observer successfully");
651 result = OC_STACK_OK;
652 OIC_LOG(DEBUG, TAG, "Observer Removal failed");
657 observer->failedCommCount++;
658 result = OC_STACK_CONTINUE;
660 observer->forceHighQos = 1;
661 OIC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount);
665 OIC_LOG(ERROR, TAG, "Unknown status");
666 result = OC_STACK_ERROR;
672 static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
674 OCStackResult ret = OC_STACK_ERROR;
678 case CA_ADAPTER_NOT_ENABLED:
679 case CA_SERVER_NOT_STARTED:
680 ret = OC_STACK_ADAPTER_NOT_ENABLED;
682 case CA_MEMORY_ALLOC_FAILED:
683 ret = OC_STACK_NO_MEMORY;
685 case CA_STATUS_INVALID_PARAM:
686 ret = OC_STACK_INVALID_PARAM;
694 OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
696 OCStackResult ret = OC_STACK_ERROR;
700 ret = OC_STACK_RESOURCE_CREATED;
703 ret = OC_STACK_RESOURCE_DELETED;
706 ret = OC_STACK_RESOURCE_CHANGED;
713 ret = OC_STACK_INVALID_QUERY;
715 case CA_UNAUTHORIZED_REQ:
716 ret = OC_STACK_UNAUTHORIZED_REQ;
719 ret = OC_STACK_INVALID_OPTION;
722 ret = OC_STACK_NO_RESOURCE;
724 case CA_RETRANSMIT_TIMEOUT:
725 ret = OC_STACK_COMM_ERROR;
727 case CA_REQUEST_ENTITY_TOO_LARGE:
728 ret = OC_STACK_TOO_LARGE_REQ;
736 CAResponseResult_t OCToCAStackResult(OCStackResult ocCode, OCMethod method)
738 CAResponseResult_t ret = CA_INTERNAL_SERVER_ERROR;
747 // This Response Code is like HTTP 204 "No Content" but only used in
748 // response to POST and PUT requests.
752 // This Response Code is like HTTP 200 "OK" but only used in response to
757 // This should not happen but,
758 // give it a value just in case but output an error
760 OIC_LOG_V(ERROR, TAG, "Unexpected OC_STACK_OK return code for method [%d].",
764 case OC_STACK_RESOURCE_CREATED:
767 case OC_STACK_RESOURCE_DELETED:
770 case OC_STACK_RESOURCE_CHANGED:
773 case OC_STACK_INVALID_QUERY:
776 case OC_STACK_INVALID_OPTION:
779 case OC_STACK_NO_RESOURCE:
782 case OC_STACK_COMM_ERROR:
783 ret = CA_RETRANSMIT_TIMEOUT;
785 case OC_STACK_UNAUTHORIZED_REQ:
786 ret = CA_UNAUTHORIZED_REQ;
794 CATransportFlags_t OCToCATransportFlags(OCTransportFlags ocFlags)
796 CATransportFlags_t caFlags = (CATransportFlags_t)ocFlags;
798 // supply default behavior.
799 if ((caFlags & (CA_IPV6|CA_IPV4)) == 0)
801 caFlags = (CATransportFlags_t)(caFlags|CA_IPV6|CA_IPV4);
803 if ((caFlags & OC_MASK_SCOPE) == 0)
805 caFlags = (CATransportFlags_t)(caFlags|OC_SCOPE_LINK);
810 OCTransportFlags CAToOCTransportFlags(CATransportFlags_t caFlags)
812 return (OCTransportFlags)caFlags;
815 static OCStackResult ResetPresenceTTL(ClientCB *cbNode, uint32_t maxAgeSeconds)
817 uint32_t lowerBound = 0;
818 uint32_t higherBound = 0;
820 if (!cbNode || !cbNode->presence || !cbNode->presence->timeOut)
822 return OC_STACK_INVALID_PARAM;
825 OIC_LOG_V(INFO, TAG, "Update presence TTL, time is %u", GetTicks(0));
827 cbNode->presence->TTL = maxAgeSeconds;
829 for (int index = 0; index < PresenceTimeOutSize; index++)
831 // Guard against overflow
832 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index]))
835 lowerBound = GetTicks((PresenceTimeOut[index] *
836 cbNode->presence->TTL *
837 MILLISECONDS_PER_SECOND)/100);
841 lowerBound = GetTicks(UINT32_MAX);
844 if (cbNode->presence->TTL < (UINT32_MAX/(MILLISECONDS_PER_SECOND*PresenceTimeOut[index+1]))
847 higherBound = GetTicks((PresenceTimeOut[index + 1] *
848 cbNode->presence->TTL *
849 MILLISECONDS_PER_SECOND)/100);
853 higherBound = GetTicks(UINT32_MAX);
856 cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound);
858 OIC_LOG_V(DEBUG, TAG, "lowerBound timeout %d", lowerBound);
859 OIC_LOG_V(DEBUG, TAG, "higherBound timeout %d", higherBound);
860 OIC_LOG_V(DEBUG, TAG, "timeOut entry %d", cbNode->presence->timeOut[index]);
863 cbNode->presence->TTLlevel = 0;
865 OIC_LOG_V(DEBUG, TAG, "this TTL level %d", cbNode->presence->TTLlevel);
869 const char *convertTriggerEnumToString(OCPresenceTrigger trigger)
871 if (trigger == OC_PRESENCE_TRIGGER_CREATE)
873 return OC_RSRVD_TRIGGER_CREATE;
875 else if (trigger == OC_PRESENCE_TRIGGER_CHANGE)
877 return OC_RSRVD_TRIGGER_CHANGE;
881 return OC_RSRVD_TRIGGER_DELETE;
885 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr)
889 return OC_PRESENCE_TRIGGER_CREATE;
891 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CREATE) == 0)
893 return OC_PRESENCE_TRIGGER_CREATE;
895 else if(strcmp(triggerStr, OC_RSRVD_TRIGGER_CHANGE) == 0)
897 return OC_PRESENCE_TRIGGER_CHANGE;
901 return OC_PRESENCE_TRIGGER_DELETE;
906 * Encode an address string to match RFC 6874.
908 * @param outputAddress a char array to be written with the encoded string.
910 * @param outputSize size of outputAddress buffer.
912 * @param inputAddress a char array of size <= CA_MAX_URI_LENGTH
913 * containing a valid IPv6 address string.
915 * @return OC_STACK_OK if encoding succeeded.
916 * Else an error occured.
918 OCStackResult encodeAddressForRFC6874(char *outputAddress,
920 const char *inputAddress)
922 VERIFY_NON_NULL(inputAddress, FATAL, OC_STACK_INVALID_PARAM);
923 VERIFY_NON_NULL(outputAddress, FATAL, OC_STACK_INVALID_PARAM);
925 size_t inputLength = strnlen(inputAddress, outputSize);
927 // inputSize includes the null terminator
928 size_t inputSize = inputLength + 1;
930 if (inputSize > outputSize)
932 OIC_LOG_V(ERROR, TAG,
933 "encodeAddressForRFC6874 failed: "
934 "outputSize (%zu) < inputSize (%zu)",
935 outputSize, inputSize);
937 return OC_STACK_ERROR;
940 char* percentChar = strchr(inputAddress, '%');
942 // If there is no '%' character, then no change is required to the string.
943 if (NULL == percentChar)
945 OICStrcpy(outputAddress, outputSize, inputAddress);
949 const char* addressPart = &inputAddress[0];
950 const char* scopeIdPart = percentChar + 1;
952 // Sanity check to make sure this string doesn't have more '%' characters
953 if (NULL != strchr(scopeIdPart, '%'))
955 return OC_STACK_ERROR;
958 // If no string follows the first '%', then the input was invalid.
959 if (scopeIdPart[0] == '\0')
961 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Invalid input string: no scope ID!");
962 return OC_STACK_ERROR;
965 // Check to see if the string is already encoded
966 if ((scopeIdPart[0] == '2') && (scopeIdPart[1] == '5'))
968 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: Input string is already encoded");
969 return OC_STACK_ERROR;
972 // Fail if we don't have room for encoded string's two additional chars
973 if (outputSize < (inputSize + 2))
975 OIC_LOG(ERROR, TAG, "encodeAddressForRFC6874 failed: encoded output will not fit!");
976 return OC_STACK_ERROR;
979 // Restore the null terminator with an escaped '%' character, per RFC 6874
980 OICStrcpy(outputAddress, scopeIdPart - addressPart, addressPart);
981 strcat(outputAddress, "%25");
982 strcat(outputAddress, scopeIdPart);
988 * The cononical presence allows constructed URIs to be string compared.
990 * requestUri must be a char array of size CA_MAX_URI_LENGTH
992 static int FormCanonicalPresenceUri(const CAEndpoint_t *endpoint, char *resourceUri,
993 char *presenceUri, bool isMulticast)
995 VERIFY_NON_NULL(endpoint , FATAL, OC_STACK_INVALID_PARAM);
996 VERIFY_NON_NULL(resourceUri, FATAL, OC_STACK_INVALID_PARAM);
997 VERIFY_NON_NULL(presenceUri, FATAL, OC_STACK_INVALID_PARAM);
1001 OIC_LOG(DEBUG, TAG, "Make Multicast Presence URI");
1002 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "%s", OC_RSRVD_PRESENCE_URI);
1005 CAEndpoint_t *ep = (CAEndpoint_t *)endpoint;
1006 if (ep->adapter == CA_ADAPTER_IP)
1008 if ((ep->flags & CA_IPV6) && !(ep->flags & CA_IPV4))
1010 if ('\0' == ep->addr[0]) // multicast
1012 return snprintf(presenceUri, CA_MAX_URI_LENGTH, OC_RSRVD_PRESENCE_URI);
1016 char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1018 OCStackResult result = encodeAddressForRFC6874(addressEncoded,
1019 sizeof(addressEncoded),
1022 if (OC_STACK_OK != result)
1027 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://[%s]:%u%s",
1028 addressEncoded, ep->port, OC_RSRVD_PRESENCE_URI);
1033 if ('\0' == ep->addr[0]) // multicast
1035 OICStrcpy(ep->addr, sizeof(ep->addr), OC_MULTICAST_IP);
1036 ep->port = OC_MULTICAST_PORT;
1038 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s:%u%s",
1039 ep->addr, ep->port, OC_RSRVD_PRESENCE_URI);
1043 // might work for other adapters (untested, but better than nothing)
1044 return snprintf(presenceUri, CA_MAX_URI_LENGTH, "coap://%s%s", ep->addr,
1045 OC_RSRVD_PRESENCE_URI);
1049 OCStackResult HandlePresenceResponse(const CAEndpoint_t *endpoint,
1050 const CAResponseInfo_t *responseInfo)
1052 VERIFY_NON_NULL(endpoint, FATAL, OC_STACK_INVALID_PARAM);
1053 VERIFY_NON_NULL(responseInfo, FATAL, OC_STACK_INVALID_PARAM);
1055 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
1056 ClientCB * cbNode = NULL;
1057 char *resourceTypeName = NULL;
1058 OCClientResponse response = {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1059 OCStackResult result = OC_STACK_ERROR;
1060 uint32_t maxAge = 0;
1062 char presenceUri[CA_MAX_URI_LENGTH];
1064 int presenceSubscribe = 0;
1065 int multicastPresenceSubscribe = 0;
1067 if (responseInfo->result != CA_CONTENT)
1069 OIC_LOG_V(ERROR, TAG, "HandlePresenceResponse failed %d", responseInfo->result);
1070 return OC_STACK_ERROR;
1073 response.payload = NULL;
1074 response.result = OC_STACK_OK;
1076 CopyEndpointToDevAddr(endpoint, &response.devAddr);
1077 FixUpClientResponse(&response);
1079 if (responseInfo->info.payload)
1081 result = OCParsePayload(&response.payload,
1082 PAYLOAD_TYPE_PRESENCE,
1083 responseInfo->info.payload,
1084 responseInfo->info.payloadSize);
1086 if(result != OC_STACK_OK)
1088 OIC_LOG(ERROR, TAG, "Presence parse failed");
1091 if(!response.payload || response.payload->type != PAYLOAD_TYPE_PRESENCE)
1093 OIC_LOG(ERROR, TAG, "Presence payload was wrong type");
1094 result = OC_STACK_ERROR;
1097 response.sequenceNumber = ((OCPresencePayload*)response.payload)->sequenceNumber;
1098 resourceTypeName = ((OCPresencePayload*)response.payload)->resourceType;
1099 maxAge = ((OCPresencePayload*)response.payload)->maxAge;
1102 // check for unicast presence
1103 uriLen = FormCanonicalPresenceUri(endpoint, OC_RSRVD_PRESENCE_URI, presenceUri,
1104 responseInfo->isMulticast);
1105 if (uriLen < 0 || (size_t)uriLen >= sizeof (presenceUri))
1107 return OC_STACK_INVALID_URI;
1109 OIC_LOG(ERROR, TAG, "check for unicast presence");
1110 cbNode = GetClientCB(NULL, 0, NULL, presenceUri);
1113 presenceSubscribe = 1;
1117 // check for multicast presence
1118 OIC_LOG(ERROR, TAG, "check for multicast presence");
1119 cbNode = GetClientCB(NULL, 0, NULL, OC_RSRVD_PRESENCE_URI);
1122 multicastPresenceSubscribe = 1;
1126 if (!presenceSubscribe && !multicastPresenceSubscribe)
1128 OIC_LOG(ERROR, TAG, "Received a presence notification, but no callback, ignoring");
1132 if (presenceSubscribe)
1134 if(cbNode->sequenceNumber == response.sequenceNumber)
1136 OIC_LOG(INFO, TAG, "No presence change");
1137 ResetPresenceTTL(cbNode, maxAge);
1138 OIC_LOG_V(INFO, TAG, "ResetPresenceTTL - TTLlevel:%d\n", cbNode->presence->TTLlevel);
1144 OIC_LOG(INFO, TAG, "Stopping presence");
1145 response.result = OC_STACK_PRESENCE_STOPPED;
1146 if(cbNode->presence)
1148 OICFree(cbNode->presence->timeOut);
1149 OICFree(cbNode->presence);
1150 cbNode->presence = NULL;
1155 if(!cbNode->presence)
1157 cbNode->presence = (OCPresence *)OICMalloc(sizeof (OCPresence));
1159 if(!(cbNode->presence))
1161 OIC_LOG(ERROR, TAG, "Could not allocate memory for cbNode->presence");
1162 result = OC_STACK_NO_MEMORY;
1166 VERIFY_NON_NULL_V(cbNode->presence);
1167 cbNode->presence->timeOut = NULL;
1168 cbNode->presence->timeOut = (uint32_t *)
1169 OICMalloc(PresenceTimeOutSize * sizeof(uint32_t));
1170 if(!(cbNode->presence->timeOut)){
1172 "Could not allocate memory for cbNode->presence->timeOut");
1173 OICFree(cbNode->presence);
1174 result = OC_STACK_NO_MEMORY;
1179 ResetPresenceTTL(cbNode, maxAge);
1181 cbNode->sequenceNumber = response.sequenceNumber;
1183 // Ensure that a filter is actually applied.
1184 if( resourceTypeName && cbNode->filterResourceType)
1186 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1195 // This is the multicast case
1196 OCMulticastNode* mcNode = NULL;
1197 mcNode = GetMCPresenceNode(presenceUri);
1201 if(mcNode->nonce == response.sequenceNumber)
1203 OIC_LOG(INFO, TAG, "No presence change (Multicast)");
1206 mcNode->nonce = response.sequenceNumber;
1210 OIC_LOG(INFO, TAG, "Stopping presence");
1211 response.result = OC_STACK_PRESENCE_STOPPED;
1216 char* uri = OICStrdup(presenceUri);
1220 "No Memory for URI to store in the presence node");
1221 result = OC_STACK_NO_MEMORY;
1225 result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
1226 if(result == OC_STACK_NO_MEMORY)
1229 "No Memory for Multicast Presence Node");
1233 // presence node now owns uri
1238 // Ensure that a filter is actually applied.
1239 if(resourceTypeName && cbNode->filterResourceType)
1241 OIC_LOG_V(INFO, TAG, "find resource type : %s", resourceTypeName);
1242 if(!findResourceType(cbNode->filterResourceType, resourceTypeName))
1248 OIC_LOG(INFO, TAG, "Callback for presence");
1250 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &response);
1252 if (cbResult == OC_STACK_DELETE_TRANSACTION)
1254 FindAndDeleteClientCB(cbNode);
1258 OCPayloadDestroy(response.payload);
1262 void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1264 OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
1266 if(responseInfo->info.resourceUri &&
1267 strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
1269 HandlePresenceResponse(endPoint, responseInfo);
1273 ClientCB *cbNode = GetClientCB(responseInfo->info.token,
1274 responseInfo->info.tokenLength, NULL, NULL);
1276 ResourceObserver * observer = GetObserverUsingToken (responseInfo->info.token,
1277 responseInfo->info.tokenLength);
1281 OIC_LOG(INFO, TAG, "There is a cbNode associated with the response token");
1282 if(responseInfo->result == CA_EMPTY)
1284 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1285 // We do not have a case for the client to receive a RESET
1286 if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1288 //This is the case of receiving an ACK on a request to a slow resource!
1289 OIC_LOG(INFO, TAG, "This is a pure ACK");
1290 //TODO: should we inform the client
1291 // app that at least the request was received at the server?
1294 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1296 OIC_LOG(INFO, TAG, "Receiving A Timeout for this token");
1297 OIC_LOG(INFO, TAG, "Calling into application address space");
1299 OCClientResponse response =
1300 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1301 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1302 FixUpClientResponse(&response);
1303 response.resourceUri = responseInfo->info.resourceUri;
1304 memcpy(response.identity.id, responseInfo->info.identity.id,
1305 sizeof (response.identity.id));
1306 response.identity.id_length = responseInfo->info.identity.id_length;
1308 response.result = CAResponseToOCStackResult(responseInfo->result);
1309 cbNode->callBack(cbNode->context,
1310 cbNode->handle, &response);
1311 FindAndDeleteClientCB(cbNode);
1315 OIC_LOG(INFO, TAG, "This is a regular response, A client call back is found");
1316 OIC_LOG(INFO, TAG, "Calling into application address space");
1318 OCClientResponse response =
1319 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
1320 response.sequenceNumber = MAX_SEQUENCE_NUMBER + 1;
1321 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1322 FixUpClientResponse(&response);
1323 response.resourceUri = responseInfo->info.resourceUri;
1324 memcpy(response.identity.id, responseInfo->info.identity.id,
1325 sizeof (response.identity.id));
1326 response.identity.id_length = responseInfo->info.identity.id_length;
1328 response.result = CAResponseToOCStackResult(responseInfo->result);
1330 if(responseInfo->info.payload &&
1331 responseInfo->info.payloadSize)
1333 OCPayloadType type = PAYLOAD_TYPE_INVALID;
1334 // check the security resource
1335 if (SRMIsSecurityResourceURI(cbNode->requestUri))
1337 type = PAYLOAD_TYPE_SECURITY;
1339 else if (cbNode->method == OC_REST_DISCOVER)
1341 if (strncmp(OC_RSRVD_WELL_KNOWN_URI,cbNode->requestUri,
1342 sizeof(OC_RSRVD_WELL_KNOWN_URI) - 1) == 0)
1344 type = PAYLOAD_TYPE_DISCOVERY;
1347 else if (strcmp(cbNode->requestUri, OC_RSRVD_WELL_KNOWN_MQ_URI) == 0)
1349 type = PAYLOAD_TYPE_DISCOVERY;
1352 else if (strcmp(cbNode->requestUri, OC_RSRVD_DEVICE_URI) == 0)
1354 type = PAYLOAD_TYPE_DEVICE;
1356 else if (strcmp(cbNode->requestUri, OC_RSRVD_PLATFORM_URI) == 0)
1358 type = PAYLOAD_TYPE_PLATFORM;
1360 #ifdef ROUTING_GATEWAY
1361 else if (strcmp(cbNode->requestUri, OC_RSRVD_GATEWAY_URI) == 0)
1363 type = PAYLOAD_TYPE_REPRESENTATION;
1366 else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
1368 type = PAYLOAD_TYPE_RD;
1371 else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
1373 type = PAYLOAD_TYPE_REPRESENTATION;
1378 OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
1379 cbNode->method, cbNode->requestUri);
1383 else if (cbNode->method == OC_REST_GET ||
1384 cbNode->method == OC_REST_PUT ||
1385 cbNode->method == OC_REST_POST ||
1386 cbNode->method == OC_REST_OBSERVE ||
1387 cbNode->method == OC_REST_OBSERVE_ALL ||
1388 cbNode->method == OC_REST_DELETE)
1390 if (cbNode->requestUri)
1392 char targetUri[MAX_URI_LENGTH];
1393 snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
1394 OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
1395 if (strcmp(targetUri, cbNode->requestUri) == 0)
1397 type = PAYLOAD_TYPE_RD;
1399 else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
1401 type = PAYLOAD_TYPE_PLATFORM;
1403 else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
1405 type = PAYLOAD_TYPE_DEVICE;
1407 if (type == PAYLOAD_TYPE_INVALID)
1409 OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
1410 cbNode->method, cbNode->requestUri);
1411 type = PAYLOAD_TYPE_REPRESENTATION;
1416 OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
1417 type = PAYLOAD_TYPE_REPRESENTATION;
1422 OIC_LOG_V(ERROR, TAG, "Unknown Payload type: %d %s",
1423 cbNode->method, cbNode->requestUri);
1427 if(OC_STACK_OK != OCParsePayload(&response.payload,
1429 responseInfo->info.payload,
1430 responseInfo->info.payloadSize))
1432 OIC_LOG(ERROR, TAG, "Error converting payload");
1433 OCPayloadDestroy(response.payload);
1438 response.numRcvdVendorSpecificHeaderOptions = 0;
1439 if(responseInfo->info.numOptions > 0)
1442 //First option always with option ID is COAP_OPTION_OBSERVE if it is available.
1443 if(responseInfo->info.options[0].optionID == COAP_OPTION_OBSERVE)
1446 uint32_t observationOption;
1447 uint8_t* optionData = (uint8_t*)responseInfo->info.options[0].optionData;
1448 for (observationOption=0, i=0;
1449 i<sizeof(uint32_t) && i<responseInfo->info.options[0].optionLength;
1453 (observationOption << 8) | optionData[i];
1455 response.sequenceNumber = observationOption;
1456 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions - 1;
1461 response.numRcvdVendorSpecificHeaderOptions = responseInfo->info.numOptions;
1464 if(response.numRcvdVendorSpecificHeaderOptions > MAX_HEADER_OPTIONS)
1466 OIC_LOG(ERROR, TAG, "#header options are more than MAX_HEADER_OPTIONS");
1467 OCPayloadDestroy(response.payload);
1471 for (uint8_t i = start; i < responseInfo->info.numOptions; i++)
1473 memcpy (&(response.rcvdVendorSpecificHeaderOptions[i-start]),
1474 &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
1478 if (cbNode->method == OC_REST_OBSERVE &&
1479 response.sequenceNumber > OC_OFFSET_SEQUENCE_NUMBER &&
1480 cbNode->sequenceNumber <= MAX_SEQUENCE_NUMBER &&
1481 response.sequenceNumber <= cbNode->sequenceNumber)
1483 OIC_LOG_V(INFO, TAG, "Received stale notification. Number :%d",
1484 response.sequenceNumber);
1488 OCStackApplicationResult appFeedback = cbNode->callBack(cbNode->context,
1491 cbNode->sequenceNumber = response.sequenceNumber;
1493 if (appFeedback == OC_STACK_DELETE_TRANSACTION)
1495 FindAndDeleteClientCB(cbNode);
1499 // To keep discovery callbacks active.
1500 cbNode->TTL = GetTicks(MAX_CB_TIMEOUT_SECONDS *
1501 MILLISECONDS_PER_SECOND);
1505 //Need to send ACK when the response is CON
1506 if(responseInfo->info.type == CA_MSG_CONFIRM)
1508 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1509 CA_MSG_ACKNOWLEDGE, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1512 OCPayloadDestroy(response.payload);
1519 OIC_LOG(INFO, TAG, "There is an observer associated with the response token");
1520 if(responseInfo->result == CA_EMPTY)
1522 OIC_LOG(INFO, TAG, "Receiving A ACK/RESET for this token");
1523 if(responseInfo->info.type == CA_MSG_RESET)
1525 OIC_LOG(INFO, TAG, "This is a RESET");
1526 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1527 OC_OBSERVER_NOT_INTERESTED);
1529 else if(responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1531 OIC_LOG(INFO, TAG, "This is a pure ACK");
1532 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1533 OC_OBSERVER_STILL_INTERESTED);
1536 else if(responseInfo->result == CA_RETRANSMIT_TIMEOUT)
1538 OIC_LOG(INFO, TAG, "Receiving Time Out for an observer");
1539 OCStackFeedBack(responseInfo->info.token, responseInfo->info.tokenLength,
1540 OC_OBSERVER_FAILED_COMM);
1545 if(!cbNode && !observer)
1547 if(myStackMode == OC_CLIENT || myStackMode == OC_CLIENT_SERVER
1548 || myStackMode == OC_GATEWAY)
1550 OIC_LOG(INFO, TAG, "This is a client, but no cbNode was found for token");
1551 if(responseInfo->result == CA_EMPTY)
1553 OIC_LOG(INFO, TAG, "Receiving CA_EMPTY in the ocstack");
1557 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
1558 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
1559 CA_MSG_RESET, 0, NULL, NULL, 0, NULL, CA_RESPONSE_FOR_RES);
1563 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER
1564 || myStackMode == OC_GATEWAY)
1566 OIC_LOG(INFO, TAG, "This is a server, but no observer was found for token");
1567 if (responseInfo->info.type == CA_MSG_ACKNOWLEDGE)
1569 OIC_LOG_V(INFO, TAG, "Received ACK at server for messageId : %d",
1570 responseInfo->info.messageId);
1572 if (responseInfo->info.type == CA_MSG_RESET)
1574 OIC_LOG_V(INFO, TAG, "Received RESET at server for messageId : %d",
1575 responseInfo->info.messageId);
1583 void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
1585 VERIFY_NON_NULL_NR(endPoint, FATAL);
1586 VERIFY_NON_NULL_NR(responseInfo, FATAL);
1588 OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
1590 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1591 #ifdef ROUTING_GATEWAY
1592 bool needRIHandling = false;
1594 * Routing manager is going to update either of endpoint or response or both.
1595 * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
1596 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
1599 OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
1601 if(ret != OC_STACK_OK || !needRIHandling)
1603 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
1609 * Put source in sender endpoint so that the next packet from application can be routed to
1610 * proper destination and remove "RM" coap header option before passing request / response to
1611 * RI as this option will make no sense to either RI or application.
1613 RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
1614 (uint8_t *) &(responseInfo->info.numOptions),
1615 (CAEndpoint_t *) endPoint);
1618 OCHandleResponse(endPoint, responseInfo);
1620 OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
1624 * This function handles error response from CA
1625 * code shall be added to handle the errors
1627 void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
1629 OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
1631 if (NULL == endPoint)
1633 OIC_LOG(ERROR, TAG, "endPoint is NULL");
1637 if (NULL == errorInfo)
1639 OIC_LOG(ERROR, TAG, "errorInfo is NULL");
1643 ClientCB *cbNode = GetClientCB(errorInfo->info.token,
1644 errorInfo->info.tokenLength, NULL, NULL);
1647 OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
1648 CopyEndpointToDevAddr(endPoint, &response.devAddr);
1649 FixUpClientResponse(&response);
1650 response.resourceUri = errorInfo->info.resourceUri;
1651 memcpy(response.identity.id, errorInfo->info.identity.id,
1652 sizeof (response.identity.id));
1653 response.identity.id_length = errorInfo->info.identity.id_length;
1654 response.result = CAResultToOCStackResult(errorInfo->result);
1656 cbNode->callBack(cbNode->context, cbNode->handle, &response);
1659 OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
1663 * This function sends out Direct Stack Responses. These are responses that are not coming
1664 * from the application entity handler. These responses have no payload and are usually ACKs,
1665 * RESETs or some error conditions that were caught by the stack.
1667 OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16_t coapID,
1668 const CAResponseResult_t responseResult, const CAMessageType_t type,
1669 const uint8_t numOptions, const CAHeaderOption_t *options,
1670 CAToken_t token, uint8_t tokenLength, const char *resourceUri,
1671 CADataType_t dataType)
1673 OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
1674 CAResponseInfo_t respInfo = {
1675 .result = responseResult
1677 respInfo.info.messageId = coapID;
1678 respInfo.info.numOptions = numOptions;
1680 if (respInfo.info.numOptions)
1682 respInfo.info.options =
1683 (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
1684 memcpy (respInfo.info.options, options,
1685 sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
1689 respInfo.info.payload = NULL;
1690 respInfo.info.token = token;
1691 respInfo.info.tokenLength = tokenLength;
1692 respInfo.info.type = type;
1693 respInfo.info.resourceUri = OICStrdup (resourceUri);
1694 respInfo.info.acceptFormat = CA_FORMAT_UNDEFINED;
1695 respInfo.info.dataType = dataType;
1697 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
1698 // Add the destination to route option from the endpoint->routeData.
1699 bool doPost = false;
1700 OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
1701 if(OC_STACK_OK != result)
1703 OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
1708 OIC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
1709 CARequestInfo_t reqInfo = {.method = CA_POST };
1710 /* The following initialization is not done in a single initializer block as in
1711 * arduino, .c file is compiled as .cpp and moves it from C99 to C++11. The latter
1712 * does not have designated initalizers. This is a work-around for now.
1714 reqInfo.info.type = CA_MSG_NONCONFIRM;
1715 reqInfo.info.messageId = coapID;
1716 reqInfo.info.tokenLength = tokenLength;
1717 reqInfo.info.token = token;
1718 reqInfo.info.numOptions = respInfo.info.numOptions;
1719 reqInfo.info.payload = NULL;
1720 reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
1721 if (reqInfo.info.numOptions)
1723 reqInfo.info.options =
1724 (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
1725 if (NULL == reqInfo.info.options)
1727 OIC_LOG(ERROR, TAG, "Calloc failed");
1728 return OC_STACK_NO_MEMORY;
1730 memcpy (reqInfo.info.options, respInfo.info.options,
1731 sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
1734 CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
1735 OICFree (reqInfo.info.resourceUri);
1736 OICFree (reqInfo.info.options);
1737 OICFree (respInfo.info.resourceUri);
1738 OICFree (respInfo.info.options);
1739 if (CA_STATUS_OK != caResult)
1741 OIC_LOG(ERROR, TAG, "CASendRequest error");
1742 return CAResultToOCResult(caResult);
1748 CAResult_t caResult = CASendResponse(endPoint, &respInfo);
1750 // resourceUri in the info field is cloned in the CA layer and
1751 // thus ownership is still here.
1752 OICFree (respInfo.info.resourceUri);
1753 OICFree (respInfo.info.options);
1754 if(CA_STATUS_OK != caResult)
1756 OIC_LOG(ERROR, TAG, "CASendResponse error");
1757 return CAResultToOCResult(caResult);
1760 OIC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
1764 OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
1766 OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
1767 OCStackResult result = OC_STACK_ERROR;
1768 if(!protocolRequest)
1770 OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
1771 return OC_STACK_INVALID_PARAM;
1774 OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
1775 protocolRequest->tokenLength);
1778 OIC_LOG(INFO, TAG, "This is a new Server Request");
1779 result = AddServerRequest(&request, protocolRequest->coapID,
1780 protocolRequest->delayedResNeeded, 0, protocolRequest->method,
1781 protocolRequest->numRcvdVendorSpecificHeaderOptions,
1782 protocolRequest->observationOption, protocolRequest->qos,
1783 protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
1784 protocolRequest->payload, protocolRequest->requestToken,
1785 protocolRequest->tokenLength, protocolRequest->resourceUrl,
1786 protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
1787 &protocolRequest->devAddr);
1788 if (OC_STACK_OK != result)
1790 OIC_LOG(ERROR, TAG, "Error adding server request");
1796 OIC_LOG(ERROR, TAG, "Out of Memory");
1797 return OC_STACK_NO_MEMORY;
1800 if(!protocolRequest->reqMorePacket)
1802 request->requestComplete = 1;
1807 OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
1810 if(request->requestComplete)
1812 OIC_LOG(INFO, TAG, "This Server Request is complete");
1813 ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
1814 OCResource *resource = NULL;
1815 result = DetermineResourceHandling (request, &resHandling, &resource);
1816 if (result == OC_STACK_OK)
1818 result = ProcessRequest(resHandling, resource, request);
1823 OIC_LOG(INFO, TAG, "This Server Request is incomplete");
1824 result = OC_STACK_CONTINUE;
1829 void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
1831 OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
1834 if (requestInfo->info.resourceUri &&
1835 strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
1837 HandleKeepAliveRequest(endPoint, requestInfo);
1842 OCStackResult requestResult = OC_STACK_ERROR;
1844 if(myStackMode == OC_CLIENT)
1846 //TODO: should the client be responding to requests?
1850 OCServerProtocolRequest serverRequest = {0};
1852 OIC_LOG_V(INFO, TAG, "Endpoint URI : %s", requestInfo->info.resourceUri);
1854 char * uriWithoutQuery = NULL;
1855 char * query = NULL;
1857 requestResult = getQueryFromUri(requestInfo->info.resourceUri, &query, &uriWithoutQuery);
1859 if (requestResult != OC_STACK_OK || !uriWithoutQuery)
1861 OIC_LOG_V(ERROR, TAG, "getQueryFromUri() failed with OC error code %d\n", requestResult);
1864 OIC_LOG_V(INFO, TAG, "URI without query: %s", uriWithoutQuery);
1865 OIC_LOG_V(INFO, TAG, "Query : %s", query);
1867 if(strlen(uriWithoutQuery) < MAX_URI_LENGTH)
1869 OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl), uriWithoutQuery);
1870 OICFree(uriWithoutQuery);
1874 OIC_LOG(ERROR, TAG, "URI length exceeds MAX_URI_LENGTH.");
1875 OICFree(uriWithoutQuery);
1882 if(strlen(query) < MAX_QUERY_LENGTH)
1884 OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
1889 OIC_LOG(ERROR, TAG, "Query length exceeds MAX_QUERY_LENGTH.");
1895 if ((requestInfo->info.payload) && (0 < requestInfo->info.payloadSize))
1897 serverRequest.reqTotalSize = requestInfo->info.payloadSize;
1898 serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
1899 if (!serverRequest.payload)
1901 OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
1904 memcpy (serverRequest.payload, requestInfo->info.payload,
1905 requestInfo->info.payloadSize);
1909 serverRequest.reqTotalSize = 0;
1912 switch (requestInfo->method)
1915 serverRequest.method = OC_REST_GET;
1918 serverRequest.method = OC_REST_PUT;
1921 serverRequest.method = OC_REST_POST;
1924 serverRequest.method = OC_REST_DELETE;
1927 OIC_LOG_V(ERROR, TAG, "Received CA method %d not supported", requestInfo->method);
1928 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_REQ,
1929 requestInfo->info.type, requestInfo->info.numOptions,
1930 requestInfo->info.options, requestInfo->info.token,
1931 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1933 OICFree(serverRequest.payload);
1937 OIC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token,
1938 requestInfo->info.tokenLength);
1940 serverRequest.tokenLength = requestInfo->info.tokenLength;
1941 if (serverRequest.tokenLength) {
1943 serverRequest.requestToken = (CAToken_t)OICMalloc(requestInfo->info.tokenLength);
1945 if (!serverRequest.requestToken)
1947 OIC_LOG(FATAL, TAG, "Allocation for token failed.");
1948 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_INTERNAL_SERVER_ERROR,
1949 requestInfo->info.type, requestInfo->info.numOptions,
1950 requestInfo->info.options, requestInfo->info.token,
1951 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
1953 OICFree(serverRequest.payload);
1956 memcpy(serverRequest.requestToken, requestInfo->info.token, requestInfo->info.tokenLength);
1959 switch (requestInfo->info.acceptFormat)
1961 case CA_FORMAT_APPLICATION_CBOR:
1962 serverRequest.acceptFormat = OC_FORMAT_CBOR;
1964 case CA_FORMAT_UNDEFINED:
1965 serverRequest.acceptFormat = OC_FORMAT_UNDEFINED;
1968 serverRequest.acceptFormat = OC_FORMAT_UNSUPPORTED;
1971 if (requestInfo->info.type == CA_MSG_CONFIRM)
1973 serverRequest.qos = OC_HIGH_QOS;
1977 serverRequest.qos = OC_LOW_QOS;
1979 // CA does not need the following field
1980 // Are we sure CA does not need them? how is it responding to multicast
1981 serverRequest.delayedResNeeded = 0;
1983 serverRequest.coapID = requestInfo->info.messageId;
1985 CopyEndpointToDevAddr(endPoint, &serverRequest.devAddr);
1987 // copy vendor specific header options
1988 uint8_t tempNum = (requestInfo->info.numOptions);
1990 // Assume no observation requested and it is a pure GET.
1991 // If obs registration/de-registration requested it'll be fetched from the
1992 // options in GetObserveHeaderOption()
1993 serverRequest.observationOption = OC_OBSERVE_NO_OPTION;
1995 GetObserveHeaderOption(&serverRequest.observationOption, requestInfo->info.options, &tempNum);
1996 if (requestInfo->info.numOptions > MAX_HEADER_OPTIONS)
1999 "The request info numOptions is greater than MAX_HEADER_OPTIONS");
2000 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_BAD_OPT,
2001 requestInfo->info.type, requestInfo->info.numOptions,
2002 requestInfo->info.options, requestInfo->info.token,
2003 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2005 OICFree(serverRequest.payload);
2006 OICFree(serverRequest.requestToken);
2009 serverRequest.numRcvdVendorSpecificHeaderOptions = tempNum;
2010 if (serverRequest.numRcvdVendorSpecificHeaderOptions)
2012 memcpy (&(serverRequest.rcvdVendorSpecificHeaderOptions), requestInfo->info.options,
2013 sizeof(CAHeaderOption_t)*tempNum);
2016 requestResult = HandleStackRequests (&serverRequest);
2018 // Send ACK to client as precursor to slow response
2019 if (requestResult == OC_STACK_SLOW_RESOURCE)
2021 if (requestInfo->info.type == CA_MSG_CONFIRM)
2023 SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
2024 CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL,
2028 if (requestResult == OC_STACK_RESOURCE_ERROR
2029 && serverRequest.observationOption == OC_OBSERVE_REGISTER)
2031 OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
2033 else if(!OCResultToSuccess(requestResult))
2035 OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
2037 CAResponseResult_t stackResponse =
2038 OCToCAStackResult(requestResult, serverRequest.method);
2040 SendDirectStackResponse(endPoint, requestInfo->info.messageId, stackResponse,
2041 requestInfo->info.type, requestInfo->info.numOptions,
2042 requestInfo->info.options, requestInfo->info.token,
2043 requestInfo->info.tokenLength, requestInfo->info.resourceUri,
2046 // requestToken is fed to HandleStackRequests, which then goes to AddServerRequest.
2047 // The token is copied in there, and is thus still owned by this function.
2048 OICFree(serverRequest.payload);
2049 OICFree(serverRequest.requestToken);
2050 OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
2053 //This function will be called back by CA layer when a request is received
2054 void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
2056 OIC_LOG(INFO, TAG, "Enter HandleCARequests");
2059 OIC_LOG(ERROR, TAG, "endPoint is NULL");
2065 OIC_LOG(ERROR, TAG, "requestInfo is NULL");
2069 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2070 #ifdef ROUTING_GATEWAY
2071 bool needRIHandling = false;
2072 bool isEmptyMsg = false;
2074 * Routing manager is going to update either of endpoint or request or both.
2075 * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
2076 * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
2077 * destination. It can also remove "RM" coap header option before passing request / response to
2078 * RI as this option will make no sense to either RI or application.
2080 OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
2081 &needRIHandling, &isEmptyMsg);
2082 if(OC_STACK_OK != ret || !needRIHandling)
2084 OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
2090 * Put source in sender endpoint so that the next packet from application can be routed to
2091 * proper destination and remove RM header option.
2093 RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
2094 (uint8_t *) &(requestInfo->info.numOptions),
2095 (CAEndpoint_t *) endPoint);
2097 #ifdef ROUTING_GATEWAY
2101 * In Gateways, the MSGType in route option is used to check if the actual
2102 * response is EMPTY message(4 bytes CoAP Header). In case of Client, the
2103 * EMPTY response is sent in the form of POST request which need to be changed
2104 * to a EMPTY response by RM. This translation is done in this part of the code.
2106 OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
2107 CAResponseInfo_t respInfo = {.result = CA_EMPTY,
2108 .info.messageId = requestInfo->info.messageId,
2109 .info.type = CA_MSG_ACKNOWLEDGE};
2110 OCHandleResponse(endPoint, &respInfo);
2116 // Normal handling of the packet
2117 OCHandleRequests(endPoint, requestInfo);
2119 OIC_LOG(INFO, TAG, "Exit HandleCARequests");
2122 bool validatePlatformInfo(OCPlatformInfo info)
2125 if (!info.platformID)
2127 OIC_LOG(ERROR, TAG, "No platform ID found.");
2131 if (info.manufacturerName)
2133 size_t lenManufacturerName = strlen(info.manufacturerName);
2135 if(lenManufacturerName == 0 || lenManufacturerName > MAX_MANUFACTURER_NAME_LENGTH)
2137 OIC_LOG(ERROR, TAG, "Manufacturer name fails length requirements.");
2143 OIC_LOG(ERROR, TAG, "No manufacturer name present");
2147 if (info.manufacturerUrl)
2149 if(strlen(info.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
2151 OIC_LOG(ERROR, TAG, "Manufacturer url fails length requirements.");
2158 //-----------------------------------------------------------------------------
2160 //-----------------------------------------------------------------------------
2162 OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo)
2165 !raInfo->username ||
2166 !raInfo->hostname ||
2167 !raInfo->xmpp_domain)
2170 return OC_STACK_INVALID_PARAM;
2172 OCStackResult result = CAResultToOCResult(CASetRAInfo((const CARAInfo_t *) raInfo));
2173 gRASetInfo = (result == OC_STACK_OK)? true : false;
2179 OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
2183 return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
2186 OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags)
2188 if(stackState == OC_STACK_INITIALIZED)
2190 OIC_LOG(INFO, TAG, "Subsequent calls to OCInit() without calling \
2191 OCStop() between them are ignored.");
2195 #ifndef ROUTING_GATEWAY
2196 if (OC_GATEWAY == mode)
2198 OIC_LOG(ERROR, TAG, "Routing Manager not supported");
2199 return OC_STACK_INVALID_PARAM;
2206 OIC_LOG(ERROR, TAG, "Need to call OCSetRAInfo before calling OCInit");
2207 return OC_STACK_ERROR;
2211 OCStackResult result = OC_STACK_ERROR;
2212 OIC_LOG(INFO, TAG, "Entering OCInit");
2215 if (!((mode == OC_CLIENT) || (mode == OC_SERVER) || (mode == OC_CLIENT_SERVER)
2216 || (mode == OC_GATEWAY)))
2218 OIC_LOG(ERROR, TAG, "Invalid mode");
2219 return OC_STACK_ERROR;
2223 if (mode == OC_CLIENT || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2225 caglobals.client = true;
2227 if (mode == OC_SERVER || mode == OC_CLIENT_SERVER || mode == OC_GATEWAY)
2229 caglobals.server = true;
2232 caglobals.serverFlags = (CATransportFlags_t)serverFlags;
2233 if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
2235 caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4|CA_IPV6);
2237 caglobals.clientFlags = (CATransportFlags_t)clientFlags;
2238 if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
2240 caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
2243 defaultDeviceHandler = NULL;
2244 defaultDeviceHandlerCallbackParameter = NULL;
2246 result = CAResultToOCResult(CAInitialize());
2247 VERIFY_SUCCESS(result, OC_STACK_OK);
2249 result = CAResultToOCResult(OCSelectNetwork());
2250 VERIFY_SUCCESS(result, OC_STACK_OK);
2252 result = CAResultToOCResult(CARegisterNetworkMonitorHandler(
2253 OCDefaultAdapterStateChangedHandler, OCDefaultConnectionStateChangedHandler));
2254 VERIFY_SUCCESS(result, OC_STACK_OK);
2256 switch (myStackMode)
2259 CARegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2260 result = CAResultToOCResult(CAStartDiscoveryServer());
2261 OIC_LOG(INFO, TAG, "Client mode: CAStartDiscoveryServer");
2264 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2265 result = CAResultToOCResult(CAStartListeningServer());
2266 OIC_LOG(INFO, TAG, "Server mode: CAStartListeningServer");
2268 case OC_CLIENT_SERVER:
2270 SRMRegisterHandler(HandleCARequests, HandleCAResponses, HandleCAErrorResponse);
2271 result = CAResultToOCResult(CAStartListeningServer());
2272 if(result == OC_STACK_OK)
2274 result = CAResultToOCResult(CAStartDiscoveryServer());
2278 VERIFY_SUCCESS(result, OC_STACK_OK);
2281 CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
2284 #ifdef WITH_PRESENCE
2285 PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
2286 #endif // WITH_PRESENCE
2288 //Update Stack state to initialized
2289 stackState = OC_STACK_INITIALIZED;
2291 // Initialize resource
2292 if(myStackMode != OC_CLIENT)
2294 result = initResources();
2297 // Initialize the SRM Policy Engine
2298 if(result == OC_STACK_OK)
2300 result = SRMInitPolicyEngine();
2301 // TODO after BeachHead delivery: consolidate into single SRMInit()
2303 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
2304 RMSetStackMode(mode);
2305 #ifdef ROUTING_GATEWAY
2306 if (OC_GATEWAY == myStackMode)
2308 result = RMInitialize();
2314 if (result == OC_STACK_OK)
2316 result = InitializeKeepAlive(myStackMode);
2321 if(result != OC_STACK_OK)
2323 OIC_LOG(ERROR, TAG, "Stack initialization error");
2324 deleteAllResources();
2326 stackState = OC_STACK_UNINITIALIZED;
2331 OCStackResult OCStop()
2333 OIC_LOG(INFO, TAG, "Entering OCStop");
2335 if (stackState == OC_STACK_UNINIT_IN_PROGRESS)
2337 OIC_LOG(DEBUG, TAG, "Stack already stopping, exiting");
2340 else if (stackState != OC_STACK_INITIALIZED)
2342 OIC_LOG(ERROR, TAG, "Stack not initialized");
2343 return OC_STACK_ERROR;
2346 stackState = OC_STACK_UNINIT_IN_PROGRESS;
2348 #ifdef WITH_PRESENCE
2349 // Ensure that the TTL associated with ANY and ALL presence notifications originating from
2350 // here send with the code "OC_STACK_PRESENCE_STOPPED" result.
2351 presenceResource.presenceTTL = 0;
2352 #endif // WITH_PRESENCE
2354 #ifdef ROUTING_GATEWAY
2355 if (OC_GATEWAY == myStackMode)
2362 TerminateKeepAlive(myStackMode);
2365 // Free memory dynamically allocated for resources
2366 deleteAllResources();
2368 DeletePlatformInfo();
2370 // Remove all observers
2371 DeleteObserverList();
2372 // Remove all the client callbacks
2373 DeleteClientCBList();
2375 // De-init the SRM Policy Engine
2376 // TODO after BeachHead delivery: consolidate into single SRMDeInit()
2377 SRMDeInitPolicyEngine();
2380 stackState = OC_STACK_UNINITIALIZED;
2384 OCStackResult OCStartMulticastServer()
2386 if(stackState != OC_STACK_INITIALIZED)
2388 OIC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
2389 return OC_STACK_ERROR;
2391 CAResult_t ret = CAStartListeningServer();
2392 if (CA_STATUS_OK != ret)
2394 OIC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
2395 return OC_STACK_ERROR;
2400 OCStackResult OCStopMulticastServer()
2402 CAResult_t ret = CAStopListeningServer();
2403 if (CA_STATUS_OK != ret)
2405 OIC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
2406 return OC_STACK_ERROR;
2411 CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
2416 return CA_MSG_CONFIRM;
2421 return CA_MSG_NONCONFIRM;
2426 * A request uri consists of the following components in order:
2429 * CoAP over UDP prefix "coap://"
2430 * CoAP over TCP prefix "coap+tcp://"
2431 * CoAP over DTLS prefix "coaps://"
2432 * CoAP over TLS prefix "coaps+tcp://"
2434 * IPv6 address "[1234::5678]"
2435 * IPv4 address "192.168.1.1"
2436 * optional port ":5683"
2437 * resource uri "/oc/core..."
2439 * for PRESENCE requests, extract resource type.
2441 static OCStackResult ParseRequestUri(const char *fullUri,
2442 OCTransportAdapter adapter,
2443 OCTransportFlags flags,
2444 OCDevAddr **devAddr,
2446 char **resourceType)
2448 VERIFY_NON_NULL(fullUri, FATAL, OC_STACK_INVALID_CALLBACK);
2450 OCStackResult result = OC_STACK_OK;
2451 OCDevAddr *da = NULL;
2455 // provide defaults for all returned values
2462 *resourceUri = NULL;
2466 *resourceType = NULL;
2469 // delimit url prefix, if any
2470 const char *start = fullUri;
2471 char *slash2 = strstr(start, "//");
2476 char *slash = strchr(start, '/');
2479 return OC_STACK_INVALID_URI;
2482 // process url scheme
2483 size_t prefixLen = slash2 - fullUri;
2487 if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
2488 || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
2494 // TODO: this logic should come in with unit tests exercising the various strings
2495 // processs url prefix, if any
2496 size_t urlLen = slash - start;
2500 if (urlLen && devAddr)
2501 { // construct OCDevAddr
2502 if (start[0] == '[')
2504 char *close = strchr(++start, ']');
2505 if (!close || close > slash)
2507 return OC_STACK_INVALID_URI;
2510 if (close[1] == ':')
2517 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2521 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2523 flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
2527 char *dot = strchr(start, '.');
2528 if (dot && dot < slash)
2530 colon = strchr(start, ':');
2531 end = (colon && colon < slash) ? colon : slash;
2536 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
2540 adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
2542 flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
2550 if (len >= sizeof(da->addr))
2552 return OC_STACK_INVALID_URI;
2554 // collect port, if any
2555 if (colon && colon < slash)
2557 for (colon++; colon < slash; colon++)
2560 if (c < '0' || c > '9')
2562 return OC_STACK_INVALID_URI;
2564 port = 10 * port + c - '0';
2569 if (len >= sizeof(da->addr))
2571 return OC_STACK_INVALID_URI;
2574 da = (OCDevAddr *)OICCalloc(sizeof (OCDevAddr), 1);
2577 return OC_STACK_NO_MEMORY;
2579 OICStrcpyPartial(da->addr, sizeof(da->addr), start, len);
2581 da->adapter = adapter;
2583 if (!strncmp(fullUri, "coaps", 5))
2585 da->flags = (OCTransportFlags)(da->flags|CA_SECURE);
2590 // process resource uri, if any
2592 { // request uri and query
2593 size_t ulen = strlen(slash); // resource uri length
2594 size_t tlen = 0; // resource type length
2597 static const char strPresence[] = "/oic/ad?rt=";
2598 static const size_t lenPresence = sizeof(strPresence) - 1;
2599 if (!strncmp(slash, strPresence, lenPresence))
2601 type = slash + lenPresence;
2602 tlen = ulen - lenPresence;
2607 *resourceUri = (char *)OICMalloc(ulen + 1);
2610 result = OC_STACK_NO_MEMORY;
2613 strcpy(*resourceUri, slash);
2616 if (type && resourceType)
2618 *resourceType = (char *)OICMalloc(tlen + 1);
2621 result = OC_STACK_NO_MEMORY;
2625 OICStrcpy(*resourceType, (tlen+1), type);
2632 // free all returned values
2639 OICFree(*resourceUri);
2643 OICFree(*resourceType);
2648 static OCStackResult OCPreparePresence(CAEndpoint_t *endpoint,
2653 char uri[CA_MAX_URI_LENGTH];
2655 FormCanonicalPresenceUri(endpoint, resourceUri, uri, isMulticast);
2657 *requestUri = OICStrdup(uri);
2660 return OC_STACK_NO_MEMORY;
2667 * Discover or Perform requests on a specified resource
2669 OCStackResult OCDoResource(OCDoHandle *handle,
2671 const char *requestUri,
2672 const OCDevAddr *destination,
2674 OCConnectivityType connectivityType,
2675 OCQualityOfService qos,
2676 OCCallbackData *cbData,
2677 OCHeaderOption *options,
2680 OIC_LOG(INFO, TAG, "Entering OCDoResource");
2682 // Validate input parameters
2683 VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
2684 VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
2686 OCStackResult result = OC_STACK_ERROR;
2687 CAResult_t caResult;
2688 CAToken_t token = NULL;
2689 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
2690 ClientCB *clientCB = NULL;
2691 OCDoHandle resHandle = NULL;
2692 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2693 OCDevAddr tmpDevAddr = { OC_DEFAULT_ADAPTER };
2695 OCTransportAdapter adapter;
2696 OCTransportFlags flags;
2697 // the request contents are put here
2698 CARequestInfo_t requestInfo = {.method = CA_GET};
2699 // requestUri will be parsed into the following three variables
2700 OCDevAddr *devAddr = NULL;
2701 char *resourceUri = NULL;
2702 char *resourceType = NULL;
2705 * Support original behavior with address on resourceUri argument.
2707 adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
2708 flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
2712 result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
2713 if (result != OC_STACK_OK)
2715 OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
2719 else if (!checkProxyUri(options, numOptions))
2721 OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
2728 case OC_REST_OBSERVE:
2729 case OC_REST_OBSERVE_ALL:
2730 requestInfo.method = CA_GET;
2733 requestInfo.method = CA_PUT;
2736 requestInfo.method = CA_POST;
2738 case OC_REST_DELETE:
2739 requestInfo.method = CA_DELETE;
2741 case OC_REST_DISCOVER:
2743 #ifdef WITH_PRESENCE
2744 case OC_REST_PRESENCE:
2746 if (destination || devAddr)
2748 requestInfo.isMulticast = false;
2752 tmpDevAddr.adapter = adapter;
2753 tmpDevAddr.flags = flags;
2754 destination = &tmpDevAddr;
2755 requestInfo.isMulticast = true;
2757 // OC_REST_DISCOVER: CA_DISCOVER will become GET and isMulticast.
2758 // OC_REST_PRESENCE: Since "presence" is a stack layer only implementation.
2759 // replacing method type with GET.
2760 requestInfo.method = CA_GET;
2763 result = OC_STACK_INVALID_METHOD;
2767 if (!devAddr && !destination)
2769 OIC_LOG(DEBUG, TAG, "no devAddr and no destination");
2770 result = OC_STACK_INVALID_PARAM;
2774 /* If not original behavior, use destination argument */
2775 if (destination && !devAddr)
2777 devAddr = (OCDevAddr *)OICMalloc(sizeof (OCDevAddr));
2780 result = OC_STACK_NO_MEMORY;
2783 *devAddr = *destination;
2786 resHandle = GenerateInvocationHandle();
2789 result = OC_STACK_NO_MEMORY;
2793 caResult = CAGenerateToken(&token, tokenLength);
2794 if (caResult != CA_STATUS_OK)
2796 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
2797 result= OC_STACK_ERROR;
2801 // fill in request data
2802 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2803 requestInfo.info.token = token;
2804 requestInfo.info.tokenLength = tokenLength;
2805 requestInfo.info.resourceUri = resourceUri;
2807 if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
2809 result = CreateObserveHeaderOption (&(requestInfo.info.options),
2810 options, numOptions, OC_OBSERVE_REGISTER);
2811 if (result != OC_STACK_OK)
2815 requestInfo.info.numOptions = numOptions + 1;
2819 requestInfo.info.numOptions = numOptions;
2820 requestInfo.info.options =
2821 (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
2822 memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
2823 numOptions * sizeof(CAHeaderOption_t));
2826 CopyDevAddrToEndpoint(devAddr, &endpoint);
2831 OCConvertPayload(payload, &requestInfo.info.payload, &requestInfo.info.payloadSize))
2834 OIC_LOG(ERROR, TAG, "Failed to create CBOR Payload");
2837 requestInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
2841 requestInfo.info.payload = NULL;
2842 requestInfo.info.payloadSize = 0;
2843 requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
2846 // prepare for response
2847 #ifdef WITH_PRESENCE
2848 if (method == OC_REST_PRESENCE)
2850 char *presenceUri = NULL;
2851 result = OCPreparePresence(&endpoint, resourceUri, &presenceUri,
2852 requestInfo.isMulticast);
2853 if (OC_STACK_OK != result)
2858 // Assign full presence uri as coap://ip:port/oic/ad to add to callback list.
2859 // Presence notification will form a canonical uri to
2860 // look for callbacks into the application.
2861 resourceUri = presenceUri;
2865 ttl = GetTicks(MAX_CB_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND);
2866 result = AddClientCB(&clientCB, cbData, token, tokenLength, &resHandle,
2867 method, devAddr, resourceUri, resourceType, ttl);
2868 if (OC_STACK_OK != result)
2873 devAddr = NULL; // Client CB list entry now owns it
2874 resourceUri = NULL; // Client CB list entry now owns it
2875 resourceType = NULL; // Client CB list entry now owns it
2878 result = OCSendRequest(&endpoint, &requestInfo);
2879 if (OC_STACK_OK != result)
2886 *handle = resHandle;
2890 if (result != OC_STACK_OK)
2892 OIC_LOG(ERROR, TAG, "OCDoResource error");
2893 FindAndDeleteClientCB(clientCB);
2894 CADestroyToken(token);
2902 // This is the owner of the payload object, so we free it
2903 OCPayloadDestroy(payload);
2904 OICFree(requestInfo.info.payload);
2906 OICFree(resourceUri);
2907 OICFree(resourceType);
2908 OICFree(requestInfo.info.options);
2912 OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
2916 * This ftn is implemented one of two ways in the case of observation:
2918 * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved..
2919 * Remove the callback associated on client side.
2920 * When the next notification comes in from server,
2921 * reply with RESET message to server.
2922 * Keep in mind that the server will react to RESET only
2923 * if the last notification was sent as CON
2925 * 2. qos == OC_CONFIRMABLE. When OCCancel is called,
2926 * and it is associated with an observe request
2927 * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL),
2928 * Send CON Observe request to server with
2929 * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER.
2930 * Remove the callback associated on client side.
2932 OCStackResult ret = OC_STACK_OK;
2933 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
2934 CARequestInfo_t requestInfo = {.method = CA_GET};
2938 return OC_STACK_INVALID_PARAM;
2941 ClientCB *clientCB = GetClientCB(NULL, 0, handle, NULL);
2944 OIC_LOG(ERROR, TAG, "Callback not found. Called OCCancel on same resource twice?");
2945 return OC_STACK_ERROR;
2948 switch (clientCB->method)
2950 case OC_REST_OBSERVE:
2951 case OC_REST_OBSERVE_ALL:
2953 OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
2955 CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
2957 if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
2959 FindAndDeleteClientCB(clientCB);
2963 OIC_LOG(INFO, TAG, "Cancelling observation as CONFIRMABLE");
2965 requestInfo.info.type = qualityOfServiceToMessageType(qos);
2966 requestInfo.info.token = clientCB->token;
2967 requestInfo.info.tokenLength = clientCB->tokenLength;
2969 if (CreateObserveHeaderOption (&(requestInfo.info.options),
2970 options, numOptions, OC_OBSERVE_DEREGISTER) != OC_STACK_OK)
2972 return OC_STACK_ERROR;
2974 requestInfo.info.numOptions = numOptions + 1;
2975 requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
2978 ret = OCSendRequest(&endpoint, &requestInfo);
2980 if (requestInfo.info.options)
2982 OICFree (requestInfo.info.options);
2984 if (requestInfo.info.resourceUri)
2986 OICFree (requestInfo.info.resourceUri);
2991 case OC_REST_DISCOVER:
2992 OIC_LOG_V(INFO, TAG, "Cancelling discovery callback for resource %s",
2993 clientCB->requestUri);
2994 FindAndDeleteClientCB(clientCB);
2997 #ifdef WITH_PRESENCE
2998 case OC_REST_PRESENCE:
2999 FindAndDeleteClientCB(clientCB);
3004 ret = OC_STACK_INVALID_METHOD;
3012 * @brief Register Persistent storage callback.
3013 * @param persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
3015 * OC_STACK_OK - No errors; Success
3016 * OC_STACK_INVALID_PARAM - Invalid parameter
3018 OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
3020 OIC_LOG(INFO, TAG, "RegisterPersistentStorageHandler !!");
3021 if(!persistentStorageHandler)
3023 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3024 return OC_STACK_INVALID_PARAM;
3028 if( !persistentStorageHandler->open ||
3029 !persistentStorageHandler->close ||
3030 !persistentStorageHandler->read ||
3031 !persistentStorageHandler->unlink ||
3032 !persistentStorageHandler->write)
3034 OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
3035 return OC_STACK_INVALID_PARAM;
3038 return SRMRegisterPersistentStorageHandler(persistentStorageHandler);
3041 #ifdef WITH_PRESENCE
3043 OCStackResult OCProcessPresence()
3045 OCStackResult result = OC_STACK_OK;
3047 // the following line floods the log with messages that are irrelevant
3048 // to most purposes. Uncomment as needed.
3049 //OIC_LOG(INFO, TAG, "Entering RequestPresence");
3050 ClientCB* cbNode = NULL;
3051 OCClientResponse clientResponse;
3052 OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
3054 LL_FOREACH(cbList, cbNode)
3056 if (OC_REST_PRESENCE != cbNode->method || !cbNode->presence)
3061 uint32_t now = GetTicks(0);
3062 OIC_LOG_V(DEBUG, TAG, "this TTL level %d",
3063 cbNode->presence->TTLlevel);
3064 OIC_LOG_V(DEBUG, TAG, "current ticks %d", now);
3066 if (cbNode->presence->TTLlevel > PresenceTimeOutSize)
3071 if (cbNode->presence->TTLlevel < PresenceTimeOutSize)
3073 OIC_LOG_V(DEBUG, TAG, "timeout ticks %d",
3074 cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
3076 if (cbNode->presence->TTLlevel >= PresenceTimeOutSize)
3078 OIC_LOG(DEBUG, TAG, "No more timeout ticks");
3080 clientResponse.sequenceNumber = 0;
3081 clientResponse.result = OC_STACK_PRESENCE_TIMEOUT;
3082 clientResponse.devAddr = *cbNode->devAddr;
3083 FixUpClientResponse(&clientResponse);
3084 clientResponse.payload = NULL;
3086 // Increment the TTLLevel (going to a next state), so we don't keep
3087 // sending presence notification to client.
3088 cbNode->presence->TTLlevel++;
3089 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
3090 cbNode->presence->TTLlevel);
3092 cbResult = cbNode->callBack(cbNode->context, cbNode->handle, &clientResponse);
3093 if (cbResult == OC_STACK_DELETE_TRANSACTION)
3095 FindAndDeleteClientCB(cbNode);
3099 if (now < cbNode->presence->timeOut[cbNode->presence->TTLlevel])
3104 CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
3105 CAInfo_t requestData = {.type = CA_MSG_CONFIRM};
3106 CARequestInfo_t requestInfo = {.method = CA_GET};
3108 OIC_LOG(DEBUG, TAG, "time to test server presence");
3110 CopyDevAddrToEndpoint(cbNode->devAddr, &endpoint);
3112 requestData.type = CA_MSG_NONCONFIRM;
3113 requestData.token = cbNode->token;
3114 requestData.tokenLength = cbNode->tokenLength;
3115 requestData.resourceUri = OC_RSRVD_PRESENCE_URI;
3116 requestInfo.method = CA_GET;
3117 requestInfo.info = requestData;
3119 result = OCSendRequest(&endpoint, &requestInfo);
3120 if (OC_STACK_OK != result)
3125 cbNode->presence->TTLlevel++;
3126 OIC_LOG_V(DEBUG, TAG, "moving to TTL level %d", cbNode->presence->TTLlevel);
3129 if (result != OC_STACK_OK)
3131 OIC_LOG(ERROR, TAG, "OCProcessPresence error");
3136 #endif // WITH_PRESENCE
3138 OCStackResult OCProcess()
3140 #ifdef WITH_PRESENCE
3141 OCProcessPresence();
3143 CAHandleRequestResponse();
3145 #ifdef ROUTING_GATEWAY
3155 #ifdef WITH_PRESENCE
3156 OCStackResult OCStartPresence(const uint32_t ttl)
3158 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
3159 OCChangeResourceProperty(
3160 &(((OCResource *)presenceResource.handle)->resourceProperties),
3163 if (OC_MAX_PRESENCE_TTL_SECONDS < ttl)
3165 presenceResource.presenceTTL = OC_MAX_PRESENCE_TTL_SECONDS;
3166 OIC_LOG(INFO, TAG, "Setting Presence TTL to max value");
3170 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
3171 OIC_LOG(INFO, TAG, "Setting Presence TTL to default value");
3175 presenceResource.presenceTTL = ttl;
3177 OIC_LOG_V(DEBUG, TAG, "Presence TTL is %" PRIu32 " seconds", presenceResource.presenceTTL);
3179 if (OC_PRESENCE_UNINITIALIZED == presenceState)
3181 presenceState = OC_PRESENCE_INITIALIZED;
3183 OCDevAddr devAddr = { OC_DEFAULT_ADAPTER };
3185 CAToken_t caToken = NULL;
3186 CAResult_t caResult = CAGenerateToken(&caToken, tokenLength);
3187 if (caResult != CA_STATUS_OK)
3189 OIC_LOG(ERROR, TAG, "CAGenerateToken error");
3190 CADestroyToken(caToken);
3191 return OC_STACK_ERROR;
3194 AddObserver(OC_RSRVD_PRESENCE_URI, NULL, 0, caToken, tokenLength,
3195 (OCResource *)presenceResource.handle, OC_LOW_QOS, OC_FORMAT_UNDEFINED, &devAddr);
3196 CADestroyToken(caToken);
3199 // Each time OCStartPresence is called
3200 // a different random 32-bit integer number is used
3201 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3203 return SendPresenceNotification(((OCResource *)presenceResource.handle)->rsrcType,
3204 OC_PRESENCE_TRIGGER_CREATE);
3207 OCStackResult OCStopPresence()
3209 OCStackResult result = OC_STACK_ERROR;
3211 if(presenceResource.handle)
3213 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3215 // make resource inactive
3216 result = OCChangeResourceProperty(
3217 &(((OCResource *) presenceResource.handle)->resourceProperties),
3221 if(result != OC_STACK_OK)
3224 "Changing the presence resource properties to ACTIVE not successful");
3228 return SendStopNotification();
3232 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler,
3233 void* callbackParameter)
3235 defaultDeviceHandler = entityHandler;
3236 defaultDeviceHandlerCallbackParameter = callbackParameter;
3241 OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo)
3243 OIC_LOG(INFO, TAG, "Entering OCSetPlatformInfo");
3245 if(myStackMode == OC_SERVER || myStackMode == OC_CLIENT_SERVER || myStackMode == OC_GATEWAY)
3247 if (validatePlatformInfo(platformInfo))
3249 return SavePlatformInfo(platformInfo);
3253 return OC_STACK_INVALID_PARAM;
3258 return OC_STACK_ERROR;
3262 OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
3264 OIC_LOG(INFO, TAG, "Entering OCSetDeviceInfo");
3266 if (!deviceInfo.deviceName || deviceInfo.deviceName[0] == '\0')
3268 OIC_LOG(ERROR, TAG, "Null or empty device name.");
3269 return OC_STACK_INVALID_PARAM;
3272 if (deviceInfo.types)
3274 OCStringLL *type = deviceInfo.types;
3275 OCResource *resource = findResource((OCResource *) deviceResource);
3278 return OC_STACK_INVALID_PARAM;
3283 OCBindResourceTypeToResource(deviceResource, type->value);
3287 return SaveDeviceInfo(deviceInfo);
3290 OCStackResult OCCreateResource(OCResourceHandle *handle,
3291 const char *resourceTypeName,
3292 const char *resourceInterfaceName,
3293 const char *uri, OCEntityHandler entityHandler,
3294 void* callbackParam,
3295 uint8_t resourceProperties)
3298 OCResource *pointer = NULL;
3299 OCStackResult result = OC_STACK_ERROR;
3301 OIC_LOG(INFO, TAG, "Entering OCCreateResource");
3303 if(myStackMode == OC_CLIENT)
3305 return OC_STACK_INVALID_PARAM;
3307 // Validate parameters
3308 if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
3310 OIC_LOG(ERROR, TAG, "URI is empty or too long");
3311 return OC_STACK_INVALID_URI;
3313 // Is it presented during resource discovery?
3314 if (!handle || !resourceTypeName || resourceTypeName[0] == '\0' )
3316 OIC_LOG(ERROR, TAG, "Input parameter is NULL");
3317 return OC_STACK_INVALID_PARAM;
3320 if (!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
3322 resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
3326 resourceProperties = resourceProperties | OC_MQ_PUBLISHER;
3328 // Make sure resourceProperties bitmask has allowed properties specified
3329 if (resourceProperties
3330 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE |
3331 OC_EXPLICIT_DISCOVERABLE
3340 OIC_LOG(ERROR, TAG, "Invalid property");
3341 return OC_STACK_INVALID_PARAM;
3344 // If the headResource is NULL, then no resources have been created...
3345 pointer = headResource;
3348 // At least one resources is in the resource list, so we need to search for
3349 // repeated URLs, which are not allowed. If a repeat is found, exit with an error
3352 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
3354 OIC_LOG_V(ERROR, TAG, "Resource %s already exists", uri);
3355 return OC_STACK_INVALID_PARAM;
3357 pointer = pointer->next;
3360 // Create the pointer and insert it into the resource list
3361 pointer = (OCResource *) OICCalloc(1, sizeof(OCResource));
3364 result = OC_STACK_NO_MEMORY;
3367 pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER;
3369 insertResource(pointer);
3372 pointer->uri = OICStrdup(uri);
3375 result = OC_STACK_NO_MEMORY;
3379 // Set properties. Set OC_ACTIVE
3380 pointer->resourceProperties = (OCResourceProperty) (resourceProperties
3383 // Add the resourcetype to the resource
3384 result = BindResourceTypeToResource(pointer, resourceTypeName);
3385 if (result != OC_STACK_OK)
3387 OIC_LOG(ERROR, TAG, "Error adding resourcetype");
3391 // Add the resourceinterface to the resource
3392 result = BindResourceInterfaceToResource(pointer, resourceInterfaceName);
3393 if (result != OC_STACK_OK)
3395 OIC_LOG(ERROR, TAG, "Error adding resourceinterface");
3399 // If an entity handler has been passed, attach it to the newly created
3400 // resource. Otherwise, set the default entity handler.
3403 pointer->entityHandler = entityHandler;
3404 pointer->entityHandlerCallbackParam = callbackParam;
3408 pointer->entityHandler = defaultResourceEHandler;
3409 pointer->entityHandlerCallbackParam = NULL;
3412 // Initialize a pointer indicating child resources in case of collection
3413 pointer->rsrcChildResourcesHead = NULL;
3416 result = OC_STACK_OK;
3418 #ifdef WITH_PRESENCE
3419 if (presenceResource.handle)
3421 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3422 SendPresenceNotification(pointer->rsrcType, OC_PRESENCE_TRIGGER_CREATE);
3426 if (result != OC_STACK_OK)
3428 // Deep delete of resource and other dynamic elements that it contains
3429 deleteResource(pointer);
3434 OCStackResult OCBindResource(
3435 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3437 OCResource *resource = NULL;
3438 OCChildResource *tempChildResource = NULL;
3439 OCChildResource *newChildResource = NULL;
3441 OIC_LOG(INFO, TAG, "Entering OCBindResource");
3443 // Validate parameters
3444 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3445 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3446 // Container cannot contain itself
3447 if (collectionHandle == resourceHandle)
3449 OIC_LOG(ERROR, TAG, "Added handle equals collection handle");
3450 return OC_STACK_INVALID_PARAM;
3453 // Use the handle to find the resource in the resource linked list
3454 resource = findResource((OCResource *) collectionHandle);
3457 OIC_LOG(ERROR, TAG, "Collection handle not found");
3458 return OC_STACK_INVALID_PARAM;
3461 // Look for an open slot to add add the child resource.
3462 // If found, add it and return success
3464 tempChildResource = resource->rsrcChildResourcesHead;
3466 while(resource->rsrcChildResourcesHead && tempChildResource->next)
3468 // TODO: what if one of child resource was deregistered without unbinding?
3469 tempChildResource = tempChildResource->next;
3472 // Do memory allocation for child resource
3473 newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
3474 if(!newChildResource)
3476 OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
3477 return OC_STACK_ERROR;
3480 newChildResource->rsrcResource = (OCResource *) resourceHandle;
3481 newChildResource->next = NULL;
3483 if(!resource->rsrcChildResourcesHead)
3485 resource->rsrcChildResourcesHead = newChildResource;
3488 tempChildResource->next = newChildResource;
3491 OIC_LOG(INFO, TAG, "resource bound");
3493 #ifdef WITH_PRESENCE
3494 if (presenceResource.handle)
3496 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3497 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3498 OC_PRESENCE_TRIGGER_CHANGE);
3505 OCStackResult OCUnBindResource(
3506 OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
3508 OCResource *resource = NULL;
3509 OCChildResource *tempChildResource = NULL;
3510 OCChildResource *tempLastChildResource = NULL;
3512 OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
3514 // Validate parameters
3515 VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
3516 VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
3517 // Container cannot contain itself
3518 if (collectionHandle == resourceHandle)
3520 OIC_LOG(ERROR, TAG, "removing handle equals collection handle");
3521 return OC_STACK_INVALID_PARAM;
3524 // Use the handle to find the resource in the resource linked list
3525 resource = findResource((OCResource *) collectionHandle);
3528 OIC_LOG(ERROR, TAG, "Collection handle not found");
3529 return OC_STACK_INVALID_PARAM;
3532 // Look for an open slot to add add the child resource.
3533 // If found, add it and return success
3534 if(!resource->rsrcChildResourcesHead)
3536 OIC_LOG(INFO, TAG, "resource not found in collection");
3538 // Unable to add resourceHandle, so return error
3539 return OC_STACK_ERROR;
3543 tempChildResource = resource->rsrcChildResourcesHead;
3545 while (tempChildResource)
3547 if(tempChildResource->rsrcResource == resourceHandle)
3549 // if resource going to be unbinded is the head one.
3550 if( tempChildResource == resource->rsrcChildResourcesHead )
3552 OCChildResource *temp = resource->rsrcChildResourcesHead->next;
3553 OICFree(resource->rsrcChildResourcesHead);
3554 resource->rsrcChildResourcesHead = temp;
3559 OCChildResource *temp = tempChildResource->next;
3560 OICFree(tempChildResource);
3561 tempLastChildResource->next = temp;
3565 OIC_LOG(INFO, TAG, "resource unbound");
3567 // Send notification when resource is unbounded successfully.
3568 #ifdef WITH_PRESENCE
3569 if (presenceResource.handle)
3571 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3572 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
3573 OC_PRESENCE_TRIGGER_CHANGE);
3576 tempChildResource = NULL;
3577 tempLastChildResource = NULL;
3583 tempLastChildResource = tempChildResource;
3584 tempChildResource = tempChildResource->next;
3587 OIC_LOG(INFO, TAG, "resource not found in collection");
3589 tempChildResource = NULL;
3590 tempLastChildResource = NULL;
3592 // Unable to add resourceHandle, so return error
3593 return OC_STACK_ERROR;
3596 static bool ValidateResourceTypeInterface(const char *resourceItemName)
3598 if (!resourceItemName)
3602 // Per RFC 6690 only registered values must follow the first rule below.
3603 // At this point in time the only values registered begin with "core", and
3604 // all other values are specified as opaque strings where multiple values
3605 // are separated by a space.
3606 if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
3608 for(size_t index = sizeof(CORESPEC) - 1; resourceItemName[index]; ++index)
3610 if (resourceItemName[index] != '.'
3611 && resourceItemName[index] != '-'
3612 && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
3613 && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
3621 for (size_t index = 0; resourceItemName[index]; ++index)
3623 if (resourceItemName[index] == ' '
3624 || resourceItemName[index] == '\t'
3625 || resourceItemName[index] == '\r'
3626 || resourceItemName[index] == '\n')
3636 OCStackResult BindResourceTypeToResource(OCResource* resource,
3637 const char *resourceTypeName)
3639 OCResourceType *pointer = NULL;
3641 OCStackResult result = OC_STACK_ERROR;
3643 VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM);
3645 if (!ValidateResourceTypeInterface(resourceTypeName))
3647 OIC_LOG(ERROR, TAG, "resource type illegal (see RFC 6690)");
3648 return OC_STACK_INVALID_PARAM;
3651 pointer = (OCResourceType *) OICCalloc(1, sizeof(OCResourceType));
3654 result = OC_STACK_NO_MEMORY;
3658 str = OICStrdup(resourceTypeName);
3661 result = OC_STACK_NO_MEMORY;
3664 pointer->resourcetypename = str;
3665 pointer->next = NULL;
3667 insertResourceType(resource, pointer);
3668 result = OC_STACK_OK;
3671 if (result != OC_STACK_OK)
3680 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
3681 const char *resourceInterfaceName)
3683 OCResourceInterface *pointer = NULL;
3685 OCStackResult result = OC_STACK_ERROR;
3687 VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM);
3689 if (!ValidateResourceTypeInterface(resourceInterfaceName))
3691 OIC_LOG(ERROR, TAG, "resource /interface illegal (see RFC 6690)");
3692 return OC_STACK_INVALID_PARAM;
3695 OIC_LOG_V(INFO, TAG, "Binding %s interface to %s", resourceInterfaceName, resource->uri);
3697 pointer = (OCResourceInterface *) OICCalloc(1, sizeof(OCResourceInterface));
3700 result = OC_STACK_NO_MEMORY;
3704 str = OICStrdup(resourceInterfaceName);
3707 result = OC_STACK_NO_MEMORY;
3710 pointer->name = str;
3712 // Bind the resourceinterface to the resource
3713 insertResourceInterface(resource, pointer);
3715 result = OC_STACK_OK;
3718 if (result != OC_STACK_OK)
3727 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
3728 const char *resourceTypeName)
3731 OCStackResult result = OC_STACK_ERROR;
3732 OCResource *resource = NULL;
3734 resource = findResource((OCResource *) handle);
3737 OIC_LOG(ERROR, TAG, "Resource not found");
3738 return OC_STACK_ERROR;
3741 result = BindResourceTypeToResource(resource, resourceTypeName);
3743 #ifdef WITH_PRESENCE
3744 if(presenceResource.handle)
3746 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3747 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3754 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
3755 const char *resourceInterfaceName)
3758 OCStackResult result = OC_STACK_ERROR;
3759 OCResource *resource = NULL;
3761 resource = findResource((OCResource *) handle);
3764 OIC_LOG(ERROR, TAG, "Resource not found");
3765 return OC_STACK_ERROR;
3768 result = BindResourceInterfaceToResource(resource, resourceInterfaceName);
3770 #ifdef WITH_PRESENCE
3771 if (presenceResource.handle)
3773 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3774 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3781 OCStackResult OCGetNumberOfResources(uint8_t *numResources)
3783 OCResource *pointer = headResource;
3785 VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
3789 *numResources = *numResources + 1;
3790 pointer = pointer->next;
3795 OCResourceHandle OCGetResourceHandle(uint8_t index)
3797 OCResource *pointer = headResource;
3799 for( uint8_t i = 0; i < index && pointer; ++i)
3801 pointer = pointer->next;
3803 return (OCResourceHandle) pointer;
3806 OCStackResult OCDeleteResource(OCResourceHandle handle)
3810 OIC_LOG(ERROR, TAG, "Invalid handle for deletion");
3811 return OC_STACK_INVALID_PARAM;
3814 OCResource *resource = findResource((OCResource *) handle);
3815 if (resource == NULL)
3817 OIC_LOG(ERROR, TAG, "Resource not found");
3818 return OC_STACK_NO_RESOURCE;
3821 if (deleteResource((OCResource *) handle) != OC_STACK_OK)
3823 OIC_LOG(ERROR, TAG, "Error deleting resource");
3824 return OC_STACK_ERROR;
3830 const char *OCGetResourceUri(OCResourceHandle handle)
3832 OCResource *resource = NULL;
3834 resource = findResource((OCResource *) handle);
3837 return resource->uri;
3839 return (const char *) NULL;
3842 OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
3844 OCResource *resource = NULL;
3846 resource = findResource((OCResource *) handle);
3849 return resource->resourceProperties;
3851 return (OCResourceProperty)-1;
3854 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
3855 uint8_t *numResourceTypes)
3857 OCResource *resource = NULL;
3858 OCResourceType *pointer = NULL;
3860 VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
3861 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3863 *numResourceTypes = 0;
3865 resource = findResource((OCResource *) handle);
3868 pointer = resource->rsrcType;
3871 *numResourceTypes = *numResourceTypes + 1;
3872 pointer = pointer->next;
3878 const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
3880 OCResourceType *resourceType = NULL;
3882 resourceType = findResourceTypeAtIndex(handle, index);
3885 return resourceType->resourcetypename;
3887 return (const char *) NULL;
3890 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
3891 uint8_t *numResourceInterfaces)
3893 OCResourceInterface *pointer = NULL;
3894 OCResource *resource = NULL;
3896 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3897 VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM);
3899 *numResourceInterfaces = 0;
3900 resource = findResource((OCResource *) handle);
3903 pointer = resource->rsrcInterface;
3906 *numResourceInterfaces = *numResourceInterfaces + 1;
3907 pointer = pointer->next;
3913 const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
3915 OCResourceInterface *resourceInterface = NULL;
3917 resourceInterface = findResourceInterfaceAtIndex(handle, index);
3918 if (resourceInterface)
3920 return resourceInterface->name;
3922 return (const char *) NULL;
3925 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
3928 OCResource *resource = NULL;
3929 OCChildResource *tempChildResource = NULL;
3932 resource = findResource((OCResource *) collectionHandle);
3938 tempChildResource = resource->rsrcChildResourcesHead;
3940 while(tempChildResource)
3944 return tempChildResource->rsrcResource;
3947 tempChildResource = tempChildResource->next;
3950 // In this case, the number of resource handles in the collection exceeds the index
3951 tempChildResource = NULL;
3955 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
3956 OCEntityHandler entityHandler,
3957 void* callbackParam)
3959 OCResource *resource = NULL;
3961 // Validate parameters
3962 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
3964 // Use the handle to find the resource in the resource linked list
3965 resource = findResource((OCResource *)handle);
3968 OIC_LOG(ERROR, TAG, "Resource not found");
3969 return OC_STACK_ERROR;
3973 resource->entityHandler = entityHandler;
3974 resource->entityHandlerCallbackParam = callbackParam;
3976 #ifdef WITH_PRESENCE
3977 if (presenceResource.handle)
3979 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
3980 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_CHANGE);
3987 OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
3989 OCResource *resource = NULL;
3991 resource = findResource((OCResource *)handle);
3994 OIC_LOG(ERROR, TAG, "Resource not found");
3999 return resource->entityHandler;
4002 void incrementSequenceNumber(OCResource * resPtr)
4004 // Increment the sequence number
4005 resPtr->sequenceNum += 1;
4006 if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER)
4008 resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1;
4013 #ifdef WITH_PRESENCE
4014 OCStackResult SendPresenceNotification(OCResourceType *resourceType,
4015 OCPresenceTrigger trigger)
4017 OCResource *resPtr = NULL;
4018 OCStackResult result = OC_STACK_ERROR;
4019 OCMethod method = OC_REST_PRESENCE;
4020 uint32_t maxAge = 0;
4021 resPtr = findResource((OCResource *) presenceResource.handle);
4024 return OC_STACK_NO_RESOURCE;
4027 if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE)
4029 maxAge = presenceResource.presenceTTL;
4031 result = SendAllObserverNotification(method, resPtr, maxAge,
4032 trigger, resourceType, OC_LOW_QOS);
4038 OCStackResult SendStopNotification()
4040 OCResource *resPtr = NULL;
4041 OCStackResult result = OC_STACK_ERROR;
4042 OCMethod method = OC_REST_PRESENCE;
4043 resPtr = findResource((OCResource *) presenceResource.handle);
4046 return OC_STACK_NO_RESOURCE;
4049 // maxAge is 0. ResourceType is NULL.
4050 result = SendAllObserverNotification(method, resPtr, 0, OC_PRESENCE_TRIGGER_DELETE,
4056 #endif // WITH_PRESENCE
4057 OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
4059 OCResource *resPtr = NULL;
4060 OCStackResult result = OC_STACK_ERROR;
4061 OCMethod method = OC_REST_NOMETHOD;
4062 uint32_t maxAge = 0;
4064 OIC_LOG(INFO, TAG, "Notifying all observers");
4065 #ifdef WITH_PRESENCE
4066 if(handle == presenceResource.handle)
4070 #endif // WITH_PRESENCE
4071 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4073 // Verify that the resource exists
4074 resPtr = findResource ((OCResource *) handle);
4077 return OC_STACK_NO_RESOURCE;
4081 //only increment in the case of regular observing (not presence)
4082 incrementSequenceNumber(resPtr);
4083 method = OC_REST_OBSERVE;
4084 maxAge = MAX_OBSERVE_AGE;
4085 #ifdef WITH_PRESENCE
4086 result = SendAllObserverNotification (method, resPtr, maxAge,
4087 OC_PRESENCE_TRIGGER_DELETE, NULL, qos);
4089 result = SendAllObserverNotification (method, resPtr, maxAge, qos);
4096 OCNotifyListOfObservers (OCResourceHandle handle,
4097 OCObservationId *obsIdList,
4098 uint8_t numberOfIds,
4099 const OCRepPayload *payload,
4100 OCQualityOfService qos)
4102 OIC_LOG(INFO, TAG, "Entering OCNotifyListOfObservers");
4104 OCResource *resPtr = NULL;
4105 //TODO: we should allow the server to define this
4106 uint32_t maxAge = MAX_OBSERVE_AGE;
4108 VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR);
4109 VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR);
4110 VERIFY_NON_NULL(payload, ERROR, OC_STACK_ERROR);
4112 resPtr = findResource ((OCResource *) handle);
4113 if (NULL == resPtr || myStackMode == OC_CLIENT)
4115 return OC_STACK_NO_RESOURCE;
4119 incrementSequenceNumber(resPtr);
4121 return (SendListObserverNotification(resPtr, obsIdList, numberOfIds,
4122 payload, maxAge, qos));
4125 OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
4127 OCStackResult result = OC_STACK_ERROR;
4128 OCServerRequest *serverRequest = NULL;
4130 OIC_LOG(INFO, TAG, "Entering OCDoResponse");
4132 // Validate input parameters
4133 VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM);
4134 VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM);
4137 // Get pointer to request info
4138 serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
4141 // response handler in ocserverrequest.c. Usually HandleSingleResponse.
4142 result = serverRequest->ehResponseHandler(ehResponse);
4148 //#ifdef DIRECT_PAIRING
4149 const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
4151 OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
4152 if(OC_STACK_OK != DPDeviceDiscovery(waittime))
4154 OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
4158 return (const OCDPDev_t*)DPGetDiscoveredDevices();
4161 const OCDPDev_t* OCGetDirectPairedDevices()
4163 return (const OCDPDev_t*)DPGetPairedDevices();
4166 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
4167 OCDirectPairingCB resultCallback)
4169 OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
4170 if(NULL == peer || NULL == pinNumber)
4172 OIC_LOG(ERROR, TAG, "Invalid parameters");
4173 return OC_STACK_INVALID_PARAM;
4175 if (NULL == resultCallback)
4177 OIC_LOG(ERROR, TAG, "Invalid callback");
4178 return OC_STACK_INVALID_CALLBACK;
4181 return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
4182 pinNumber, (OCDirectPairingResultCB)resultCallback);
4184 //#endif // DIRECT_PAIRING
4186 //-----------------------------------------------------------------------------
4187 // Private internal function definitions
4188 //-----------------------------------------------------------------------------
4189 static OCDoHandle GenerateInvocationHandle()
4191 OCDoHandle handle = NULL;
4192 // Generate token here, it will be deleted when the transaction is deleted
4193 handle = (OCDoHandle) OICMalloc(sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4196 OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[CA_MAX_TOKEN_LEN]));
4202 #ifdef WITH_PRESENCE
4203 OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
4204 OCResourceProperty resourceProperties, uint8_t enable)
4208 return OC_STACK_INVALID_PARAM;
4210 if (resourceProperties
4211 > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
4213 OIC_LOG(ERROR, TAG, "Invalid property");
4214 return OC_STACK_INVALID_PARAM;
4218 *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties));
4222 *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties);
4228 OCStackResult initResources()
4230 OCStackResult result = OC_STACK_OK;
4232 headResource = NULL;
4233 tailResource = NULL;
4234 // Init Virtual Resources
4235 #ifdef WITH_PRESENCE
4236 presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL_SECONDS;
4238 result = OCCreateResource(&presenceResource.handle,
4239 OC_RSRVD_RESOURCE_TYPE_PRESENCE,
4241 OC_RSRVD_PRESENCE_URI,
4245 //make resource inactive
4246 result = OCChangeResourceProperty(
4247 &(((OCResource *) presenceResource.handle)->resourceProperties),
4250 #ifndef WITH_ARDUINO
4251 if (result == OC_STACK_OK)
4253 result = SRMInitSecureResources();
4257 if(result == OC_STACK_OK)
4259 CreateResetProfile();
4260 result = OCCreateResource(&deviceResource,
4261 OC_RSRVD_RESOURCE_TYPE_DEVICE,
4262 OC_RSRVD_INTERFACE_DEFAULT,
4263 OC_RSRVD_DEVICE_URI,
4267 if(result == OC_STACK_OK)
4269 result = BindResourceInterfaceToResource((OCResource *)deviceResource,
4270 OC_RSRVD_INTERFACE_READ);
4274 if(result == OC_STACK_OK)
4276 result = OCCreateResource(&platformResource,
4277 OC_RSRVD_RESOURCE_TYPE_PLATFORM,
4278 OC_RSRVD_INTERFACE_DEFAULT,
4279 OC_RSRVD_PLATFORM_URI,
4283 if(result == OC_STACK_OK)
4285 result = BindResourceInterfaceToResource((OCResource *)platformResource,
4286 OC_RSRVD_INTERFACE_READ);
4293 void insertResource(OCResource *resource)
4297 headResource = resource;
4298 tailResource = resource;
4302 tailResource->next = resource;
4303 tailResource = resource;
4305 resource->next = NULL;
4308 OCResource *findResource(OCResource *resource)
4310 OCResource *pointer = headResource;
4314 if (pointer == resource)
4318 pointer = pointer->next;
4323 void deleteAllResources()
4325 OCResource *pointer = headResource;
4326 OCResource *temp = NULL;
4330 temp = pointer->next;
4331 #ifdef WITH_PRESENCE
4332 if (pointer != (OCResource *) presenceResource.handle)
4334 #endif // WITH_PRESENCE
4335 deleteResource(pointer);
4336 #ifdef WITH_PRESENCE
4338 #endif // WITH_PRESENCE
4341 memset(&platformResource, 0, sizeof(platformResource));
4342 memset(&deviceResource, 0, sizeof(deviceResource));
4344 memset(&brokerResource, 0, sizeof(brokerResource));
4347 SRMDeInitSecureResources();
4349 #ifdef WITH_PRESENCE
4350 // Ensure that the last resource to be deleted is the presence resource. This allows for all
4351 // presence notification attributed to their deletion to be processed.
4352 deleteResource((OCResource *) presenceResource.handle);
4353 memset(&presenceResource, 0, sizeof(presenceResource));
4354 #endif // WITH_PRESENCE
4357 OCStackResult deleteResource(OCResource *resource)
4359 OCResource *prev = NULL;
4360 OCResource *temp = NULL;
4363 OIC_LOG(DEBUG,TAG,"resource is NULL");
4364 return OC_STACK_INVALID_PARAM;
4367 OIC_LOG_V (INFO, TAG, "Deleting resource %s", resource->uri);
4369 temp = headResource;
4372 if (temp == resource)
4374 // Invalidate all Resource Properties.
4375 resource->resourceProperties = (OCResourceProperty) 0;
4376 #ifdef WITH_PRESENCE
4377 if(resource != (OCResource *) presenceResource.handle)
4379 #endif // WITH_PRESENCE
4380 OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS);
4381 #ifdef WITH_PRESENCE
4384 if(presenceResource.handle)
4386 ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
4387 SendPresenceNotification(resource->rsrcType, OC_PRESENCE_TRIGGER_DELETE);
4390 // Only resource in list.
4391 if (temp == headResource && temp == tailResource)
4393 headResource = NULL;
4394 tailResource = NULL;
4397 else if (temp == headResource)
4399 headResource = temp->next;
4402 else if (temp == tailResource)
4404 tailResource = prev;
4405 tailResource->next = NULL;
4409 prev->next = temp->next;
4412 deleteResourceElements(temp);
4423 return OC_STACK_ERROR;
4426 void deleteResourceElements(OCResource *resource)
4433 OICFree(resource->uri);
4434 deleteResourceType(resource->rsrcType);
4435 deleteResourceInterface(resource->rsrcInterface);
4438 void deleteResourceType(OCResourceType *resourceType)
4440 OCResourceType *pointer = resourceType;
4441 OCResourceType *next = NULL;
4445 next = pointer->next;
4446 OICFree(pointer->resourcetypename);
4452 void deleteResourceInterface(OCResourceInterface *resourceInterface)
4454 OCResourceInterface *pointer = resourceInterface;
4455 OCResourceInterface *next = NULL;
4459 next = pointer->next;
4460 OICFree(pointer->name);
4466 void insertResourceType(OCResource *resource, OCResourceType *resourceType)
4468 OCResourceType *pointer = NULL;
4469 OCResourceType *previous = NULL;
4470 if (!resource || !resourceType)
4474 // resource type list is empty.
4475 else if (!resource->rsrcType)
4477 resource->rsrcType = resourceType;
4481 pointer = resource->rsrcType;
4485 if (!strcmp(resourceType->resourcetypename, pointer->resourcetypename))
4487 OIC_LOG_V(INFO, TAG, "Type %s already exists", resourceType->resourcetypename);
4488 OICFree(resourceType->resourcetypename);
4489 OICFree(resourceType);
4493 pointer = pointer->next;
4498 previous->next = resourceType;
4501 resourceType->next = NULL;
4503 OIC_LOG_V(INFO, TAG, "Added type %s to %s", resourceType->resourcetypename, resource->uri);
4506 OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
4508 OCResource *resource = NULL;
4509 OCResourceType *pointer = NULL;
4511 // Find the specified resource
4512 resource = findResource((OCResource *) handle);
4518 // Make sure a resource has a resourcetype
4519 if (!resource->rsrcType)
4524 // Iterate through the list
4525 pointer = resource->rsrcType;
4526 for(uint8_t i = 0; i< index && pointer; ++i)
4528 pointer = pointer->next;
4533 OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName)
4535 if(resourceTypeList && resourceTypeName)
4537 OCResourceType * rtPointer = resourceTypeList;
4538 while(resourceTypeName && rtPointer)
4540 OIC_LOG_V(DEBUG, TAG, "current resourceType : %s", rtPointer->resourcetypename);
4541 if(rtPointer->resourcetypename &&
4542 strcmp(resourceTypeName, (const char *)
4543 (rtPointer->resourcetypename)) == 0)
4547 rtPointer = rtPointer->next;
4555 * Insert a new interface into interface linked list only if not already present.
4556 * If alredy present, 2nd arg is free'd.
4557 * Default interface will always be first if present.
4559 void insertResourceInterface(OCResource *resource, OCResourceInterface *newInterface)
4561 OCResourceInterface *pointer = NULL;
4562 OCResourceInterface *previous = NULL;
4564 newInterface->next = NULL;
4566 OCResourceInterface **firstInterface = &(resource->rsrcInterface);
4568 if (!*firstInterface)
4570 // If first interface is not oic.if.baseline, by default add it as first interface type.
4571 if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
4573 *firstInterface = newInterface;
4577 OCStackResult result = BindResourceInterfaceToResource(resource,
4578 OC_RSRVD_INTERFACE_DEFAULT);
4579 if (result != OC_STACK_OK)
4581 OICFree(newInterface->name);
4582 OICFree(newInterface);
4585 if (*firstInterface)
4587 (*firstInterface)->next = newInterface;
4591 // If once add oic.if.baseline, later too below code take care of freeing memory.
4592 else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4594 if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
4596 OICFree(newInterface->name);
4597 OICFree(newInterface);
4600 // This code will not hit anymore, keeping
4603 newInterface->next = *firstInterface;
4604 *firstInterface = newInterface;
4609 pointer = *firstInterface;
4612 if (strcmp(newInterface->name, pointer->name) == 0)
4614 OICFree(newInterface->name);
4615 OICFree(newInterface);
4619 pointer = pointer->next;
4624 previous->next = newInterface;
4629 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
4632 OCResource *resource = NULL;
4633 OCResourceInterface *pointer = NULL;
4635 // Find the specified resource
4636 resource = findResource((OCResource *) handle);
4642 // Make sure a resource has a resourceinterface
4643 if (!resource->rsrcInterface)
4648 // Iterate through the list
4649 pointer = resource->rsrcInterface;
4651 for (uint8_t i = 0; i < index && pointer; ++i)
4653 pointer = pointer->next;
4659 * This function splits the uri using the '?' delimiter.
4660 * "uriWithoutQuery" is the block of characters between the beginning
4661 * till the delimiter or '\0' which ever comes first.
4662 * "query" is whatever is to the right of the delimiter if present.
4663 * No delimiter sets the query to NULL.
4664 * If either are present, they will be malloc'ed into the params 2, 3.
4665 * The first param, *uri is left untouched.
4667 * NOTE: This function does not account for whitespace at the end of the uri NOR
4668 * malformed uri's with '??'. Whitespace at the end will be assumed to be
4669 * part of the query.
4671 OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithoutQuery)
4675 return OC_STACK_INVALID_URI;
4677 if(!query || !uriWithoutQuery)
4679 return OC_STACK_INVALID_PARAM;
4683 *uriWithoutQuery = NULL;
4685 size_t uriWithoutQueryLen = 0;
4686 size_t queryLen = 0;
4687 size_t uriLen = strlen(uri);
4689 char *pointerToDelimiter = strstr(uri, "?");
4691 uriWithoutQueryLen = pointerToDelimiter == NULL ? uriLen : (size_t)(pointerToDelimiter - uri);
4692 queryLen = pointerToDelimiter == NULL ? 0 : uriLen - uriWithoutQueryLen - 1;
4694 if (uriWithoutQueryLen)
4696 *uriWithoutQuery = (char *) OICCalloc(uriWithoutQueryLen + 1, 1);
4697 if (!*uriWithoutQuery)
4701 OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
4705 *query = (char *) OICCalloc(queryLen + 1, 1);
4708 OICFree(*uriWithoutQuery);
4709 *uriWithoutQuery = NULL;
4712 OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
4718 return OC_STACK_NO_MEMORY;
4721 static const OicUuid_t* OCGetServerInstanceID(void)
4723 static bool generated = false;
4724 static OicUuid_t sid;
4730 if (OC_STACK_OK != GetDoxmDeviceID(&sid))
4732 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
4739 const char* OCGetServerInstanceIDString(void)
4741 static bool generated = false;
4742 static char sidStr[UUID_STRING_SIZE];
4749 const OicUuid_t *sid = OCGetServerInstanceID();
4750 if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
4752 OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
4760 CAResult_t OCSelectNetwork()
4762 CAResult_t retResult = CA_STATUS_FAILED;
4763 CAResult_t caResult = CA_STATUS_OK;
4765 CATransportAdapter_t connTypes[] = {
4767 CA_ADAPTER_RFCOMM_BTEDR,
4768 CA_ADAPTER_GATT_BTLE,
4771 ,CA_ADAPTER_REMOTE_ACCESS
4778 int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]);
4780 for(int i = 0; i < numConnTypes; i++)
4782 // If CA status is not initialized, CASelectNetwork() will not be called.
4783 if (caResult != CA_STATUS_NOT_INITIALIZED)
4785 caResult = CASelectNetwork(connTypes[i]);
4786 if (caResult == CA_STATUS_OK)
4788 retResult = CA_STATUS_OK;
4793 if (retResult != CA_STATUS_OK)
4795 return caResult; // Returns error of appropriate transport that failed fatally.
4801 OCStackResult CAResultToOCResult(CAResult_t caResult)
4807 case CA_STATUS_INVALID_PARAM:
4808 return OC_STACK_INVALID_PARAM;
4809 case CA_ADAPTER_NOT_ENABLED:
4810 return OC_STACK_ADAPTER_NOT_ENABLED;
4811 case CA_SERVER_STARTED_ALREADY:
4813 case CA_SERVER_NOT_STARTED:
4814 return OC_STACK_ERROR;
4815 case CA_DESTINATION_NOT_REACHABLE:
4816 return OC_STACK_COMM_ERROR;
4817 case CA_SOCKET_OPERATION_FAILED:
4818 return OC_STACK_COMM_ERROR;
4819 case CA_SEND_FAILED:
4820 return OC_STACK_COMM_ERROR;
4821 case CA_RECEIVE_FAILED:
4822 return OC_STACK_COMM_ERROR;
4823 case CA_MEMORY_ALLOC_FAILED:
4824 return OC_STACK_NO_MEMORY;
4825 case CA_REQUEST_TIMEOUT:
4826 return OC_STACK_TIMEOUT;
4827 case CA_DESTINATION_DISCONNECTED:
4828 return OC_STACK_COMM_ERROR;
4829 case CA_STATUS_FAILED:
4830 return OC_STACK_ERROR;
4831 case CA_NOT_SUPPORTED:
4832 return OC_STACK_NOTIMPL;
4834 return OC_STACK_ERROR;
4838 bool OCResultToSuccess(OCStackResult ocResult)
4843 case OC_STACK_RESOURCE_CREATED:
4844 case OC_STACK_RESOURCE_DELETED:
4845 case OC_STACK_CONTINUE:
4846 case OC_STACK_RESOURCE_CHANGED:
4847 case OC_STACK_SLOW_RESOURCE:
4855 OCStackResult OCSetProxyURI(const char *uri)
4857 return CAResultToOCResult(CASetProxyUri(uri));
4861 #if defined(RD_CLIENT) || defined(RD_SERVER)
4862 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
4864 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4866 OCResource *resource = NULL;
4868 resource = findResource((OCResource *) handle);
4871 OIC_LOG(ERROR, TAG, "Resource not found");
4872 return OC_STACK_ERROR;
4875 resource->ins = ins;
4880 OCResourceHandle OCGetResourceHandleAtUri(const char *uri)
4884 OIC_LOG(ERROR, TAG, "Resource uri is NULL");
4888 OCResource *pointer = headResource;
4892 if (strncmp(uri, pointer->uri, MAX_URI_LENGTH) == 0)
4894 OIC_LOG_V(DEBUG, TAG, "Found Resource %s", uri);
4897 pointer = pointer->next;
4902 OCStackResult OCGetResourceIns(OCResourceHandle handle, uint8_t *ins)
4904 OCResource *resource = NULL;
4906 VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
4907 VERIFY_NON_NULL(ins, ERROR, OC_STACK_INVALID_PARAM);
4909 resource = findResource((OCResource *) handle);
4912 *ins = resource->ins;
4915 return OC_STACK_ERROR;
4918 OCStackResult OCSetHeaderOption(OCHeaderOption* ocHdrOpt, size_t* numOptions, uint16_t optionID,
4919 void* optionData, size_t optionDataLength)
4923 OIC_LOG (INFO, TAG, "Header options are NULL");
4924 return OC_STACK_INVALID_PARAM;
4929 OIC_LOG (INFO, TAG, "optionData are NULL");
4930 return OC_STACK_INVALID_PARAM;
4935 OIC_LOG (INFO, TAG, "numOptions is NULL");
4936 return OC_STACK_INVALID_PARAM;
4939 if (*numOptions >= MAX_HEADER_OPTIONS)
4941 OIC_LOG (INFO, TAG, "Exceeding MAX_HEADER_OPTIONS");
4942 return OC_STACK_NO_MEMORY;
4945 ocHdrOpt += *numOptions;
4946 ocHdrOpt->protocolID = OC_COAP_ID;
4947 ocHdrOpt->optionID = optionID;
4948 ocHdrOpt->optionLength =
4949 optionDataLength < MAX_HEADER_OPTION_DATA_LENGTH ?
4950 optionDataLength : MAX_HEADER_OPTION_DATA_LENGTH;
4951 memcpy(ocHdrOpt->optionData, (const void*) optionData, ocHdrOpt->optionLength);
4956 OCStackResult OCGetHeaderOption(OCHeaderOption* ocHdrOpt, size_t numOptions, uint16_t optionID,
4957 void* optionData, size_t optionDataLength, uint16_t* receivedDataLength)
4959 if (!ocHdrOpt || !numOptions)
4961 OIC_LOG (INFO, TAG, "No options present");
4967 OIC_LOG (INFO, TAG, "optionData are NULL");
4968 return OC_STACK_INVALID_PARAM;
4971 if (!receivedDataLength)
4973 OIC_LOG (INFO, TAG, "receivedDataLength is NULL");
4974 return OC_STACK_INVALID_PARAM;
4977 for (uint8_t i = 0; i < numOptions; i++)
4979 if (ocHdrOpt[i].optionID == optionID)
4981 if (optionDataLength >= ocHdrOpt->optionLength)
4983 memcpy(optionData, ocHdrOpt->optionData, ocHdrOpt->optionLength);
4984 *receivedDataLength = ocHdrOpt->optionLength;
4989 OIC_LOG (ERROR, TAG, "optionDataLength is less than the length of received data");
4990 return OC_STACK_ERROR;
4998 void OCDefaultAdapterStateChangedHandler(CATransportAdapter_t adapter, bool enabled)
5000 OIC_LOG(DEBUG, TAG, "OCDefaultAdapterStateChangedHandler");
5001 if (g_adapterHandler)
5003 g_adapterHandler(adapter, enabled);
5007 void OCDefaultConnectionStateChangedHandler(const CAEndpoint_t *info, bool isConnected)
5009 OIC_LOG(DEBUG, TAG, "OCDefaultConnectionStateChangedHandler");
5010 if (g_connectionHandler)
5012 g_connectionHandler(info, isConnected);
5016 void OCSetNetworkMonitorHandler(CAAdapterStateChangedCB adapterHandler,
5017 CAConnectionStateChangedCB connectionHandler)
5019 OIC_LOG(DEBUG, TAG, "OCSetNetworkMonitorHandler");
5020 g_adapterHandler = adapterHandler;
5021 g_connectionHandler = connectionHandler;